blob: 1348ef0f2935c068dd0675cdd137ee1f426e2032 [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);
231 mInputSurface = surface;
232 return mInputSurface->connect(mComponent);
233}
234
235status_t CCodecBufferChannel::signalEndOfInputStream() {
236 if (mInputSurface == nullptr) {
237 return INVALID_OPERATION;
238 }
239 return mInputSurface->signalEndOfInputStream();
240}
241
Sungtak Lee04b30352020-07-27 13:57:25 -0700242status_t CCodecBufferChannel::queueInputBufferInternal(
243 sp<MediaCodecBuffer> buffer,
244 std::shared_ptr<C2LinearBlock> encryptedBlock,
245 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800246 int64_t timeUs;
247 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
248
249 if (mInputMetEos) {
250 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
251 return OK;
252 }
253
254 int32_t flags = 0;
255 int32_t tmp = 0;
256 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200257 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800258 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
259 eos = true;
260 mInputMetEos = true;
261 ALOGV("[%s] input EOS", mName);
262 }
263 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
264 flags |= C2FrameData::FLAG_CODEC_CONFIG;
265 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200266 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
267 tunnelFirstFrame = true;
268 }
Marc Kassis96343b42022-12-09 11:49:44 +0100269 if (buffer->meta()->findInt32("decode-only", &tmp) && tmp) {
270 flags |= C2FrameData::FLAG_DROP_FRAME;
271 }
Arun Johnsonf4a81f72023-11-09 21:22:48 +0000272 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu time: %lld",
273 mName, buffer->size(), (long long)timeUs);
Wonsik Kime1104ca2020-11-24 15:01:33 -0800274 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800275 std::unique_ptr<C2Work> work(new C2Work);
276 work->input.ordinal.timestamp = timeUs;
277 work->input.ordinal.frameIndex = mFrameIndex++;
278 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
279 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
280 // Keep client timestamp in customOrdinal
281 work->input.ordinal.customOrdinal = timeUs;
282 work->input.buffers.clear();
283
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700284 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800285 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800286
Pawin Vongmasa36653902018-11-15 00:10:25 -0800287 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700288 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800289 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700290 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800291 return -ENOENT;
292 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700293 // TODO: we want to delay copying buffers.
294 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
295 copy = input->buffers->cloneAndReleaseBuffer(buffer);
296 if (copy != nullptr) {
297 (void)input->extraBuffers.assignSlot(copy);
298 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
299 return UNKNOWN_ERROR;
300 }
301 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
302 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
303 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700304 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700305 } else {
306 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
307 "buffer starvation on component.", mName);
308 }
309 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800310 if (input->frameReassembler) {
311 usesFrameReassembler = true;
312 input->frameReassembler.process(buffer, &items);
313 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900314 int32_t cvo = 0;
315 if (buffer->meta()->findInt32("cvo", &cvo)) {
316 int32_t rotation = cvo % 360;
317 // change rotation to counter-clock wise.
318 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
319
320 Mutexed<OutputSurface>::Locked output(mOutputSurface);
321 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
322 output->rotation[frameIndex] = rotation;
323 }
Arun Johnsonf4a81f72023-11-09 21:22:48 +0000324 sp<RefBase> obj;
325 if (buffer->meta()->findObject("accessUnitInfo", &obj)) {
326 ALOGV("Filling C2Info from multiple access units");
327 sp<WrapperObject<std::vector<AccessUnitInfo>>> infos{
328 (decltype(infos.get()))obj.get()};
329 std::vector<AccessUnitInfo> &accessUnitInfoVec = infos->value;
330 std::vector<C2AccessUnitInfosStruct> multipleAccessUnitInfos;
331 uint32_t outFlags = 0;
332 for (int i = 0; i < accessUnitInfoVec.size(); i++) {
333 outFlags = 0;
334 outFlags = convertFlags(accessUnitInfoVec[i].mFlags, true);
335 if (eos && (outFlags & C2FrameData::FLAG_END_OF_STREAM)) {
336 outFlags &= (~C2FrameData::FLAG_END_OF_STREAM);
337 }
338 multipleAccessUnitInfos.emplace_back(
339 outFlags,
340 accessUnitInfoVec[i].mSize,
341 accessUnitInfoVec[i].mTimestamp);
342 ALOGV("%d) flags: %d, size: %d, time: %llu",
343 i, outFlags, accessUnitInfoVec[i].mSize,
344 (long long)accessUnitInfoVec[i].mTimestamp);
345
346 }
347 const std::shared_ptr<C2AccessUnitInfos::input> c2AccessUnitInfos =
348 C2AccessUnitInfos::input::AllocShared(
349 multipleAccessUnitInfos.size(), 0u, multipleAccessUnitInfos);
350 c2buffer->setInfo(c2AccessUnitInfos);
351 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800352 work->input.buffers.push_back(c2buffer);
353 if (encryptedBlock) {
354 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
355 kParamIndexEncryptedBuffer,
356 encryptedBlock->share(0, blockSize, C2Fence())));
357 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700358 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800359 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700360 Mutexed<Input>::Locked input(mInput);
361 if (input->frameReassembler) {
362 usesFrameReassembler = true;
363 // drain any pending items with eos
364 input->frameReassembler.process(buffer, &items);
365 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800366 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800367 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800368 if (usesFrameReassembler) {
369 if (!items.empty()) {
370 items.front()->input.configUpdate = std::move(mParamsToBeSet);
371 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
372 }
373 } else {
374 work->input.flags = (C2FrameData::flags_t)flags;
Harish Mahendrakar38a99c22024-02-26 20:28:05 +0530375
Wonsik Kime1104ca2020-11-24 15:01:33 -0800376 // TODO: fill info's
Harish Mahendrakar38a99c22024-02-26 20:28:05 +0530377 if (android::media::codec::provider_->region_of_interest()
378 && android::media::codec::provider_->region_of_interest_support()) {
379 if (mInfoBuffers.size()) {
380 for (auto infoBuffer : mInfoBuffers) {
381 work->input.infoBuffers.emplace_back(*infoBuffer);
382 }
383 mInfoBuffers.clear();
384 }
385 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800386
Wonsik Kime1104ca2020-11-24 15:01:33 -0800387 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200388 if (tunnelFirstFrame) {
389 C2StreamTunnelHoldRender::input tunnelHoldRender{
390 0u /* stream */,
391 C2_TRUE /* value */
392 };
393 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
394 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800395 work->worklets.clear();
396 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800397
Wonsik Kime1104ca2020-11-24 15:01:33 -0800398 items.push_back(std::move(work));
399
400 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800401 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800402 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800403 work.reset(new C2Work);
404 work->input.ordinal.timestamp = timeUs;
405 work->input.ordinal.frameIndex = mFrameIndex++;
406 // WORKAROUND: keep client timestamp in customOrdinal
407 work->input.ordinal.customOrdinal = timeUs;
408 work->input.buffers.clear();
409 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800410 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800411 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800412 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800413 c2_status_t err = C2_OK;
414 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700415 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
416 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800417 {
418 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
419 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
420 for (const std::unique_ptr<C2Work> &work : items) {
421 watcher->onWorkQueued(
422 work->input.ordinal.frameIndex.peeku(),
423 std::vector(work->input.buffers),
424 now);
425 }
426 }
427 err = mComponent->queue(&items);
428 }
429 if (err != C2_OK) {
430 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
431 for (const std::unique_ptr<C2Work> &work : items) {
432 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
433 }
434 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700435 Mutexed<Input>::Locked input(mInput);
436 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700437 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700438 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700439 } else if (buffer) {
440 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700441 }
442 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
443 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800444 }
445
446 feedInputBufferIfAvailableInternal();
447 return err;
448}
449
450status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
451 QueueGuard guard(mSync);
452 if (!guard.isRunning()) {
453 ALOGD("[%s] setParameters is only supported in the running state.", mName);
454 return -ENOSYS;
455 }
456 mParamsToBeSet.insert(mParamsToBeSet.end(),
457 std::make_move_iterator(params.begin()),
458 std::make_move_iterator(params.end()));
459 params.clear();
460 return OK;
461}
462
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800463status_t CCodecBufferChannel::attachBuffer(
464 const std::shared_ptr<C2Buffer> &c2Buffer,
465 const sp<MediaCodecBuffer> &buffer) {
466 if (!buffer->copy(c2Buffer)) {
467 return -ENOSYS;
468 }
469 return OK;
470}
471
472void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
473 if (!mDecryptDestination || mDecryptDestination->size() < size) {
474 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
475 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
476 mCrypto->unsetHeap(mHeapSeqNum);
477 }
478 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
479 if (mCrypto) {
480 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
481 }
482 }
483}
484
485int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
486 CHECK(mCrypto);
487 auto it = mHeapSeqNumMap.find(memory);
488 int32_t heapSeqNum = -1;
489 if (it == mHeapSeqNumMap.end()) {
490 heapSeqNum = mCrypto->setHeap(memory);
491 mHeapSeqNumMap.emplace(memory, heapSeqNum);
492 } else {
493 heapSeqNum = it->second;
494 }
495 return heapSeqNum;
496}
497
Arun Johnson564f3a92024-02-01 19:09:45 +0000498typedef WrapperObject<std::vector<AccessUnitInfo>> BufferInfosWrapper;
499typedef WrapperObject<std::vector<std::unique_ptr<CodecCryptoInfo>>> CryptoInfosWrapper;
500status_t CCodecBufferChannel::attachEncryptedBuffers(
501 const sp<hardware::HidlMemory> &memory,
502 size_t offset,
503 const sp<MediaCodecBuffer> &buffer,
504 bool secure,
505 AString* errorDetailMsg) {
506 static const C2MemoryUsage kDefaultReadWriteUsage{
507 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
508 if (!hasCryptoOrDescrambler()) {
509 ALOGE("attachEncryptedBuffers requires Crypto/descrambler object");
510 return -ENOSYS;
511 }
512 size_t size = 0;
513 CHECK(buffer->meta()->findSize("ssize", &size));
514 if (size == 0) {
515 buffer->setRange(0, 0);
516 return OK;
517 }
518 sp<RefBase> obj;
519 CHECK(buffer->meta()->findObject("cryptoInfos", &obj));
520 sp<CryptoInfosWrapper> cryptoInfos{(CryptoInfosWrapper *)obj.get()};
521 CHECK(buffer->meta()->findObject("accessUnitInfo", &obj));
522 sp<BufferInfosWrapper> bufferInfos{(BufferInfosWrapper *)obj.get()};
523 if (secure || (mCrypto == nullptr)) {
524 if (cryptoInfos->value.size() != 1) {
525 ALOGE("Cannot decrypt multiple access units");
526 return -ENOSYS;
527 }
528 // we are dealing with just one cryptoInfo or descrambler.
529 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[0]);
530 if (info == nullptr) {
531 ALOGE("Cannot decrypt, CryptoInfos are null.");
532 return -ENOSYS;
533 }
534 return attachEncryptedBuffer(
535 memory,
536 secure,
537 info->mKey,
538 info->mIv,
539 info->mMode,
540 info->mPattern,
541 offset,
542 info->mSubSamples,
543 info->mNumSubSamples,
544 buffer,
545 errorDetailMsg);
546 }
547 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
548 std::shared_ptr<C2LinearBlock> block;
549 c2_status_t err = pool->fetchLinearBlock(
550 size,
551 kDefaultReadWriteUsage,
552 &block);
553 if (err != C2_OK) {
554 ALOGI("[%s] attachEncryptedBuffers: fetchLinearBlock failed: size = %zu (%s) err = %d",
555 mName, size, secure ? "secure" : "non-secure", err);
556 return NO_MEMORY;
557 }
558 ensureDecryptDestination(size);
559 C2WriteView wView = block->map().get();
560 if (wView.error() != C2_OK) {
561 ALOGI("[%s] attachEncryptedBuffers: block map error: %d (non-secure)",
562 mName, wView.error());
563 return UNKNOWN_ERROR;
564 }
565
566 ssize_t result = -1;
Arun Johnson82174a12024-02-27 04:53:59 +0000567 size_t srcOffset = offset;
Arun Johnson564f3a92024-02-01 19:09:45 +0000568 size_t outBufferSize = 0;
569 uint32_t cryptoInfoIdx = 0;
570 int32_t heapSeqNum = getHeapSeqNum(memory);
571 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
572 hardware::drm::V1_0::DestinationBuffer dst;
573 dst.type = DrmBufferType::SHARED_MEMORY;
574 IMemoryToSharedBuffer(
575 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
576 for (int i = 0; i < bufferInfos->value.size(); i++) {
577 if (bufferInfos->value[i].mSize > 0) {
578 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[cryptoInfoIdx++]);
Arun Johnson82174a12024-02-27 04:53:59 +0000579 src.offset = srcOffset;
580 src.size = bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +0000581 result = mCrypto->decrypt(
582 (uint8_t*)info->mKey,
583 (uint8_t*)info->mIv,
584 info->mMode,
585 info->mPattern,
586 src,
Arun Johnson82174a12024-02-27 04:53:59 +0000587 0,
Arun Johnson564f3a92024-02-01 19:09:45 +0000588 info->mSubSamples,
589 info->mNumSubSamples,
590 dst,
591 errorDetailMsg);
Arun Johnson82174a12024-02-27 04:53:59 +0000592 srcOffset += bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +0000593 if (result < 0) {
594 ALOGI("[%s] attachEncryptedBuffers: decrypt failed: result = %zd",
595 mName, result);
596 return result;
597 }
598 if (wView.error() == C2_OK) {
599 if (wView.size() < result) {
600 ALOGI("[%s] attachEncryptedBuffers: block size too small:"
601 "size=%u result=%zd (non-secure)", mName, wView.size(), result);
602 return UNKNOWN_ERROR;
603 }
604 memcpy(wView.data(), mDecryptDestination->unsecurePointer(), result);
605 bufferInfos->value[i].mSize = result;
606 wView.setOffset(wView.offset() + result);
607 }
608 outBufferSize += result;
609 }
610 }
611 if (wView.error() == C2_OK) {
612 wView.setOffset(0);
613 }
614 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
Arun Johnson82174a12024-02-27 04:53:59 +0000615 block->share(0, outBufferSize, C2Fence{}))};
Arun Johnson564f3a92024-02-01 19:09:45 +0000616 if (!buffer->copy(c2Buffer)) {
617 ALOGI("[%s] attachEncryptedBuffers: buffer copy failed", mName);
618 return -ENOSYS;
619 }
620 return OK;
621}
622
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800623status_t CCodecBufferChannel::attachEncryptedBuffer(
624 const sp<hardware::HidlMemory> &memory,
625 bool secure,
626 const uint8_t *key,
627 const uint8_t *iv,
628 CryptoPlugin::Mode mode,
629 CryptoPlugin::Pattern pattern,
630 size_t offset,
631 const CryptoPlugin::SubSample *subSamples,
632 size_t numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000633 const sp<MediaCodecBuffer> &buffer,
634 AString* errorDetailMsg) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800635 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
636 static const C2MemoryUsage kDefaultReadWriteUsage{
637 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
638
639 size_t size = 0;
640 for (size_t i = 0; i < numSubSamples; ++i) {
641 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
642 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700643 if (size == 0) {
644 buffer->setRange(0, 0);
645 return OK;
646 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800647 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
648 std::shared_ptr<C2LinearBlock> block;
649 c2_status_t err = pool->fetchLinearBlock(
650 size,
651 secure ? kSecureUsage : kDefaultReadWriteUsage,
652 &block);
653 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700654 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
655 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800656 return NO_MEMORY;
657 }
658 if (!secure) {
659 ensureDecryptDestination(size);
660 }
661 ssize_t result = -1;
662 ssize_t codecDataOffset = 0;
663 if (mCrypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800664 int32_t heapSeqNum = getHeapSeqNum(memory);
665 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
666 hardware::drm::V1_0::DestinationBuffer dst;
667 if (secure) {
668 dst.type = DrmBufferType::NATIVE_HANDLE;
669 dst.secureMemory = hardware::hidl_handle(block->handle());
670 } else {
671 dst.type = DrmBufferType::SHARED_MEMORY;
672 IMemoryToSharedBuffer(
673 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
674 }
675 result = mCrypto->decrypt(
676 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000677 dst, errorDetailMsg);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800678 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700679 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800680 return result;
681 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800682 } else {
683 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
684 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
685 hidl_vec<SubSample> hidlSubSamples;
686 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
687
688 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
689 hardware::cas::native::V1_0::DestinationBuffer dst;
690 if (secure) {
691 dst.type = BufferType::NATIVE_HANDLE;
692 dst.secureMemory = hardware::hidl_handle(block->handle());
693 } else {
694 dst.type = BufferType::SHARED_MEMORY;
695 dst.nonsecureMemory = src;
696 }
697
698 CasStatus status = CasStatus::OK;
699 hidl_string detailedError;
700 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
701
702 if (key != nullptr) {
703 sctrl = (ScramblingControl)key[0];
704 // Adjust for the PES offset
705 codecDataOffset = key[2] | (key[3] << 8);
706 }
707
708 auto returnVoid = mDescrambler->descramble(
709 sctrl,
710 hidlSubSamples,
711 src,
712 0,
713 dst,
714 0,
715 [&status, &result, &detailedError] (
716 CasStatus _status, uint32_t _bytesWritten,
717 const hidl_string& _detailedError) {
718 status = _status;
719 result = (ssize_t)_bytesWritten;
720 detailedError = _detailedError;
721 });
Arun Johnson634d0802023-02-14 22:07:51 +0000722 if (errorDetailMsg) {
723 errorDetailMsg->setTo(detailedError.c_str(), detailedError.size());
724 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800725 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
726 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
727 mName, returnVoid.description().c_str(), status, result);
728 return UNKNOWN_ERROR;
729 }
730
731 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700732 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
733 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800734 return BAD_VALUE;
735 }
736 }
737 if (!secure) {
738 C2WriteView view = block->map().get();
739 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700740 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
741 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800742 return UNKNOWN_ERROR;
743 }
744 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700745 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
746 "(non-secure)",
747 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800748 return UNKNOWN_ERROR;
749 }
750 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
751 }
752 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
753 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
754 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700755 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800756 return -ENOSYS;
757 }
758 return OK;
759}
760
Pawin Vongmasa36653902018-11-15 00:10:25 -0800761status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
762 QueueGuard guard(mSync);
763 if (!guard.isRunning()) {
764 ALOGD("[%s] No more buffers should be queued at current state.", mName);
765 return -ENOSYS;
766 }
767 return queueInputBufferInternal(buffer);
768}
769
770status_t CCodecBufferChannel::queueSecureInputBuffer(
771 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
772 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
773 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
774 AString *errorDetailMsg) {
775 QueueGuard guard(mSync);
776 if (!guard.isRunning()) {
777 ALOGD("[%s] No more buffers should be queued at current state.", mName);
778 return -ENOSYS;
779 }
780
781 if (!hasCryptoOrDescrambler()) {
782 return -ENOSYS;
783 }
784 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
785
Sungtak Lee04b30352020-07-27 13:57:25 -0700786 std::shared_ptr<C2LinearBlock> block;
787 size_t allocSize = buffer->size();
788 size_t bufferSize = 0;
789 c2_status_t blockRes = C2_OK;
790 bool copied = false;
Arun Johnson7ba67072023-11-06 22:23:04 +0000791 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
792 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
Sungtak Lee04b30352020-07-27 13:57:25 -0700793 if (mSendEncryptedInfoBuffer) {
794 static const C2MemoryUsage kDefaultReadWriteUsage{
795 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
796 constexpr int kAllocGranule0 = 1024 * 64;
797 constexpr int kAllocGranule1 = 1024 * 1024;
798 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
799 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
800 if (allocSize <= kAllocGranule1) {
801 bufferSize = align(allocSize, kAllocGranule0);
802 } else {
803 bufferSize = align(allocSize, kAllocGranule1);
804 }
805 blockRes = pool->fetchLinearBlock(
806 bufferSize, kDefaultReadWriteUsage, &block);
807
808 if (blockRes == C2_OK) {
809 C2WriteView view = block->map().get();
810 if (view.error() == C2_OK && view.size() == bufferSize) {
811 copied = true;
812 // TODO: only copy clear sections
813 memcpy(view.data(), buffer->data(), allocSize);
814 }
815 }
816 }
817
818 if (!copied) {
819 block.reset();
820 }
821
Pawin Vongmasa36653902018-11-15 00:10:25 -0800822 ssize_t result = -1;
823 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700824 if (numSubSamples == 1
825 && subSamples[0].mNumBytesOfClearData == 0
826 && subSamples[0].mNumBytesOfEncryptedData == 0) {
827 // We don't need to go through crypto or descrambler if the input is empty.
828 result = 0;
829 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700830 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800831 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700832 destination.type = DrmBufferType::NATIVE_HANDLE;
833 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800834 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700835 destination.type = DrmBufferType::SHARED_MEMORY;
836 IMemoryToSharedBuffer(
837 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800838 }
Robert Shih895fba92019-07-16 16:29:44 -0700839 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800840 encryptedBuffer->fillSourceBuffer(&source);
841 result = mCrypto->decrypt(
842 key, iv, mode, pattern, source, buffer->offset(),
843 subSamples, numSubSamples, destination, errorDetailMsg);
844 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700845 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800846 return result;
847 }
Robert Shih895fba92019-07-16 16:29:44 -0700848 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800849 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
850 }
851 } else {
852 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
853 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
854 hidl_vec<SubSample> hidlSubSamples;
855 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
856
857 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
858 encryptedBuffer->fillSourceBuffer(&srcBuffer);
859
860 DestinationBuffer dstBuffer;
861 if (secure) {
862 dstBuffer.type = BufferType::NATIVE_HANDLE;
863 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
864 } else {
865 dstBuffer.type = BufferType::SHARED_MEMORY;
866 dstBuffer.nonsecureMemory = srcBuffer;
867 }
868
869 CasStatus status = CasStatus::OK;
870 hidl_string detailedError;
871 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
872
873 if (key != nullptr) {
874 sctrl = (ScramblingControl)key[0];
875 // Adjust for the PES offset
876 codecDataOffset = key[2] | (key[3] << 8);
877 }
878
879 auto returnVoid = mDescrambler->descramble(
880 sctrl,
881 hidlSubSamples,
882 srcBuffer,
883 0,
884 dstBuffer,
885 0,
886 [&status, &result, &detailedError] (
887 CasStatus _status, uint32_t _bytesWritten,
888 const hidl_string& _detailedError) {
889 status = _status;
890 result = (ssize_t)_bytesWritten;
891 detailedError = _detailedError;
892 });
893
894 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
895 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
896 mName, returnVoid.description().c_str(), status, result);
897 return UNKNOWN_ERROR;
898 }
899
900 if (result < codecDataOffset) {
901 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
902 return BAD_VALUE;
903 }
904
905 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
906
907 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
908 encryptedBuffer->copyDecryptedContentFromMemory(result);
909 }
910 }
911
912 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700913
914 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800915}
916
Arun Johnson564f3a92024-02-01 19:09:45 +0000917status_t CCodecBufferChannel::queueSecureInputBuffers(
918 const sp<MediaCodecBuffer> &buffer,
919 bool secure,
920 AString *errorDetailMsg) {
921 QueueGuard guard(mSync);
922 if (!guard.isRunning()) {
923 ALOGD("[%s] No more buffers should be queued at current state.", mName);
924 return -ENOSYS;
925 }
926
927 if (!hasCryptoOrDescrambler()) {
928 ALOGE("queueSecureInputBuffers requires a Crypto/descrambler Object");
929 return -ENOSYS;
930 }
931 sp<RefBase> obj;
932 CHECK(buffer->meta()->findObject("cryptoInfos", &obj));
933 sp<CryptoInfosWrapper> cryptoInfos{(CryptoInfosWrapper *)obj.get()};
934 CHECK(buffer->meta()->findObject("accessUnitInfo", &obj));
935 sp<BufferInfosWrapper> bufferInfos{(BufferInfosWrapper *)obj.get()};
936 if (secure || mCrypto == nullptr) {
937 if (cryptoInfos->value.size() != 1) {
938 ALOGE("Cannot decrypt multiple access units on native handles");
939 return -ENOSYS;
940 }
941 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[0]);
942 if (info == nullptr) {
943 ALOGE("Cannot decrypt, CryptoInfos are null");
944 return -ENOSYS;
945 }
946 return queueSecureInputBuffer(
947 buffer,
948 secure,
949 info->mKey,
950 info->mIv,
951 info->mMode,
952 info->mPattern,
953 info->mSubSamples,
954 info->mNumSubSamples,
955 errorDetailMsg);
956 }
957 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
958
959 std::shared_ptr<C2LinearBlock> block;
960 size_t allocSize = buffer->size();
961 size_t bufferSize = 0;
962 c2_status_t blockRes = C2_OK;
963 bool copied = false;
964 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
965 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
966 if (mSendEncryptedInfoBuffer) {
967 static const C2MemoryUsage kDefaultReadWriteUsage{
968 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
969 constexpr int kAllocGranule0 = 1024 * 64;
970 constexpr int kAllocGranule1 = 1024 * 1024;
971 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
972 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
973 if (allocSize <= kAllocGranule1) {
974 bufferSize = align(allocSize, kAllocGranule0);
975 } else {
976 bufferSize = align(allocSize, kAllocGranule1);
977 }
978 blockRes = pool->fetchLinearBlock(
979 bufferSize, kDefaultReadWriteUsage, &block);
980
981 if (blockRes == C2_OK) {
982 C2WriteView view = block->map().get();
983 if (view.error() == C2_OK && view.size() == bufferSize) {
984 copied = true;
985 // TODO: only copy clear sections
986 memcpy(view.data(), buffer->data(), allocSize);
987 }
988 }
989 }
990
991 if (!copied) {
992 block.reset();
993 }
994 // size of cryptoInfo and accessUnitInfo should be the same?
995 ssize_t result = -1;
Arun Johnson82174a12024-02-27 04:53:59 +0000996 size_t srcOffset = 0;
Arun Johnson564f3a92024-02-01 19:09:45 +0000997 size_t outBufferSize = 0;
998 uint32_t cryptoInfoIdx = 0;
999 {
1000 // scoped this block to enable destruction of mappedBlock
1001 std::unique_ptr<EncryptedLinearBlockBuffer::MappedBlock> mappedBlock = nullptr;
1002 hardware::drm::V1_0::DestinationBuffer destination;
1003 destination.type = DrmBufferType::SHARED_MEMORY;
1004 IMemoryToSharedBuffer(
1005 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
1006 encryptedBuffer->getMappedBlock(&mappedBlock);
1007 hardware::drm::V1_0::SharedBuffer source;
1008 encryptedBuffer->fillSourceBuffer(&source);
Arun Johnson82174a12024-02-27 04:53:59 +00001009 srcOffset = source.offset;
Arun Johnson564f3a92024-02-01 19:09:45 +00001010 for (int i = 0 ; i < bufferInfos->value.size(); i++) {
1011 if (bufferInfos->value[i].mSize > 0) {
1012 std::unique_ptr<CodecCryptoInfo> info =
1013 std::move(cryptoInfos->value[cryptoInfoIdx++]);
1014 if (info->mNumSubSamples == 1
1015 && info->mSubSamples[0].mNumBytesOfClearData == 0
1016 && info->mSubSamples[0].mNumBytesOfEncryptedData == 0) {
1017 // no data so we only populate the bufferInfo
1018 result = 0;
1019 } else {
Arun Johnson82174a12024-02-27 04:53:59 +00001020 source.offset = srcOffset;
1021 source.size = bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +00001022 result = mCrypto->decrypt(
1023 (uint8_t*)info->mKey,
1024 (uint8_t*)info->mIv,
1025 info->mMode,
1026 info->mPattern,
1027 source,
Arun Johnson82174a12024-02-27 04:53:59 +00001028 buffer->offset(),
Arun Johnson564f3a92024-02-01 19:09:45 +00001029 info->mSubSamples,
1030 info->mNumSubSamples,
1031 destination,
1032 errorDetailMsg);
Arun Johnson82174a12024-02-27 04:53:59 +00001033 srcOffset += bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +00001034 if (result < 0) {
1035 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
1036 return result;
1037 }
1038 if (destination.type == DrmBufferType::SHARED_MEMORY && mappedBlock) {
1039 mappedBlock->copyDecryptedContent(mDecryptDestination, result);
1040 }
1041 bufferInfos->value[i].mSize = result;
1042 outBufferSize += result;
1043 }
1044 }
1045 }
Arun Johnson82174a12024-02-27 04:53:59 +00001046 buffer->setRange(0, outBufferSize);
Arun Johnson564f3a92024-02-01 19:09:45 +00001047 }
1048 return queueInputBufferInternal(buffer, block, bufferSize);
1049}
1050
Pawin Vongmasa36653902018-11-15 00:10:25 -08001051void CCodecBufferChannel::feedInputBufferIfAvailable() {
1052 QueueGuard guard(mSync);
1053 if (!guard.isRunning()) {
1054 ALOGV("[%s] We're not running --- no input buffer reported", mName);
1055 return;
1056 }
1057 feedInputBufferIfAvailableInternal();
1058}
1059
1060void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +09001061 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001062 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -07001063 }
1064 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001065 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -07001066 if (!output->buffers ||
1067 output->buffers->hasPending() ||
Wonsik Kim3722abc2023-05-17 13:26:31 -07001068 (!output->bounded && output->buffers->numActiveSlots() >= output->numSlots)) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001069 return;
1070 }
1071 }
Wonsik Kim1951d932024-05-23 22:59:00 +00001072 if (android::media::codec::provider_->input_surface_throttle()
1073 && mInputSurface != nullptr) {
1074 mInputSurface->onInputBufferEmptied();
1075 }
Wonsik Kim0487b782020-10-28 11:45:50 -07001076 size_t numActiveSlots = 0;
1077 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001078 sp<MediaCodecBuffer> inBuffer;
1079 size_t index;
1080 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001081 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -07001082 numActiveSlots = input->buffers->numActiveSlots();
1083 if (numActiveSlots >= input->numSlots) {
1084 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001085 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001086 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001087 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001088 break;
1089 }
1090 }
1091 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
1092 mCallback->onInputBufferAvailable(index, inBuffer);
1093 }
Wonsik Kim0487b782020-10-28 11:45:50 -07001094 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001095}
1096
1097status_t CCodecBufferChannel::renderOutputBuffer(
1098 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001099 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001100 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001101 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001102 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001103 Mutexed<Output>::Locked output(mOutput);
1104 if (output->buffers) {
1105 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001106 }
1107 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001108 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
1109 // set to true.
1110 sendOutputBuffers();
1111 // input buffer feeding may have been gated by pending output buffers
1112 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001113 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001114 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -07001115 std::call_once(mRenderWarningFlag, [this] {
1116 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
1117 "timestamp or render=true with non-video buffers. Apps should "
1118 "call releaseOutputBuffer() with render=false for those.",
1119 mName);
1120 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001121 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001122 return INVALID_OPERATION;
1123 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001124
1125#if 0
1126 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
1127 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
1128 for (const std::shared_ptr<const C2Info> &info : infoParams) {
1129 AString res;
1130 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
1131 if (ix) res.append(", ");
1132 res.append(*((int32_t*)info.get() + (ix / 4)));
1133 }
1134 ALOGV(" [%s]", res.c_str());
1135 }
1136#endif
1137 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
1138 std::static_pointer_cast<const C2StreamRotationInfo::output>(
1139 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
1140 bool flip = rotation && (rotation->flip & 1);
1141 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +09001142
1143 {
1144 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1145 if (output->surface == nullptr) {
1146 ALOGI("[%s] cannot render buffer without surface", mName);
1147 return OK;
1148 }
1149 int64_t frameIndex;
1150 buffer->meta()->findInt64("frameIndex", &frameIndex);
1151 if (output->rotation.count(frameIndex) != 0) {
1152 auto it = output->rotation.find(frameIndex);
1153 quarters = (it->second / 90) & 3;
1154 output->rotation.erase(it);
1155 }
1156 }
1157
Pawin Vongmasa36653902018-11-15 00:10:25 -08001158 uint32_t transform = 0;
1159 switch (quarters) {
1160 case 0: // no rotation
1161 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
1162 break;
1163 case 1: // 90 degrees counter-clockwise
1164 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
1165 : HAL_TRANSFORM_ROT_270;
1166 break;
1167 case 2: // 180 degrees
1168 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
1169 break;
1170 case 3: // 90 degrees clockwise
1171 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
1172 : HAL_TRANSFORM_ROT_90;
1173 break;
1174 }
1175
1176 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
1177 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
1178 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
1179 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
1180 if (surfaceScaling) {
1181 videoScalingMode = surfaceScaling->value;
1182 }
1183
1184 // Use dataspace from format as it has the default aspects already applied
1185 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
1186 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
1187
1188 // HDR static info
1189 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
1190 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
1191 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
1192
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001193 // HDR10 plus info
1194 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
1195 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
1196 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +08001197 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
1198 hdr10PlusInfo.reset();
1199 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001200
Wonsik Kima79c5522022-01-18 16:29:24 -08001201 // HDR dynamic info
1202 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
1203 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
1204 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
1205 // TODO: make this sticky & enable unset
1206 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
1207 hdrDynamicInfo.reset();
1208 }
1209
1210 if (hdr10PlusInfo) {
1211 // C2StreamHdr10PlusInfo is deprecated; components should use
1212 // C2StreamHdrDynamicMetadataInfo
1213 // TODO: #metric
1214 if (hdrDynamicInfo) {
1215 // It is unexpected that C2StreamHdr10PlusInfo and
1216 // C2StreamHdrDynamicMetadataInfo is both present.
1217 // C2StreamHdrDynamicMetadataInfo takes priority.
1218 // TODO: #metric
1219 } else {
1220 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
1221 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
1222 hdr10PlusInfo->flexCount(),
1223 0u,
1224 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
1225 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
1226 hdrDynamicInfo = info;
1227 }
1228 }
1229
Pawin Vongmasa36653902018-11-15 00:10:25 -08001230 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
1231 if (blocks.size() != 1u) {
1232 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
1233 return UNKNOWN_ERROR;
1234 }
1235 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -07001236 C2Fence c2fence = block.fence();
1237 sp<Fence> fence = Fence::NO_FENCE;
1238 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
1239 // Once C2Fence::type() is added, check the exact C2Fence type
1240 if (c2fence.isHW()) {
1241 int fenceFd = c2fence.fd();
1242 fence = sp<Fence>::make(fenceFd);
1243 if (!fence) {
1244 ALOGE("[%s] Failed to allocate a fence", mName);
1245 close(fenceFd);
1246 return NO_MEMORY;
1247 }
1248 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001249
1250 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -07001251 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001252 timestampNs,
1253 false, // droppable
1254 dataSpace,
1255 Rect(blocks.front().crop().left,
1256 blocks.front().crop().top,
1257 blocks.front().crop().right(),
1258 blocks.front().crop().bottom()),
1259 videoScalingMode,
1260 transform,
Lubin Yin92427a52022-04-18 16:57:39 -07001261 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -08001262 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001263 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001264 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +08001265 // If mastering max and min luminance fields are 0, do not use them.
1266 // It indicates the value may not be present in the stream.
1267 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
1268 hdrStaticInfo->mastering.minLuminance > 0.0f) {
1269 struct android_smpte2086_metadata smpte2086_meta = {
1270 .displayPrimaryRed = {
1271 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
1272 },
1273 .displayPrimaryGreen = {
1274 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
1275 },
1276 .displayPrimaryBlue = {
1277 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
1278 },
1279 .whitePoint = {
1280 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
1281 },
1282 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
1283 .minLuminance = hdrStaticInfo->mastering.minLuminance,
1284 };
Yichi Chen54be23c2020-06-15 14:30:53 +08001285 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +08001286 hdr.smpte2086 = smpte2086_meta;
1287 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -07001288 // If the content light level fields are 0, do not use them, it
1289 // indicates the value may not be present in the stream.
1290 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
1291 struct android_cta861_3_metadata cta861_meta = {
1292 .maxContentLightLevel = hdrStaticInfo->maxCll,
1293 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
1294 };
1295 hdr.validTypes |= HdrMetadata::CTA861_3;
1296 hdr.cta8613 = cta861_meta;
1297 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +09001298
1299 // does not have valid info
1300 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
1301 hdrStaticInfo.reset();
1302 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001303 }
Wonsik Kima79c5522022-01-18 16:29:24 -08001304 if (hdrDynamicInfo
1305 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001306 hdr.validTypes |= HdrMetadata::HDR10PLUS;
1307 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -08001308 hdrDynamicInfo->m.data,
1309 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001310 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001311 qbi.setHdrMetadata(hdr);
1312 }
Hongguangfc1478a2022-07-20 22:56:06 -07001313 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
1314
Brian Lindahl932bf602023-03-09 11:59:48 -07001315 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
1316 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
1317 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001318 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
1319 if (result != OK) {
1320 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -08001321 if (result == NO_INIT) {
1322 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1323 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001324 return result;
1325 }
Josh Hou8eddf4b2021-02-02 16:26:53 +08001326
1327 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
1328 ALOGD("[%s] queue buffer successful", mName);
1329 } else {
1330 ALOGV("[%s] queue buffer successful", mName);
1331 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001332
1333 int64_t mediaTimeUs = 0;
1334 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahld7967a92023-08-10 10:12:49 -06001335 if (mAreRenderMetricsEnabled && mIsSurfaceToDisplay) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001336 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
1337 processRenderedFrames(qbo.frameTimestamps);
1338 } else {
1339 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
1340 // when the frame is queued to the non-display surface
1341 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1342 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001343
1344 return OK;
1345}
1346
Brian Lindahl932bf602023-03-09 11:59:48 -07001347void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001348 mTrackedFrames.clear();
1349
1350 int isSurfaceToDisplay = 0;
1351 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1352 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1353 // No frame tracking is needed if we're not sending frames to the display
1354 if (!mIsSurfaceToDisplay) {
1355 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1356 return;
1357 }
1358
Brian Lindahl932bf602023-03-09 11:59:48 -07001359 int hasPresentFenceTimes = 0;
1360 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1361 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
Brian Lindahl119e0c22023-05-19 15:42:13 -06001362 if (!mHasPresentFenceTimes) {
Brian Lindahl932bf602023-03-09 11:59:48 -07001363 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1364 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001365}
1366
1367void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1368 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1369 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1370 // so track the frame as if the desired render time is now.
1371 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1372 if (desiredRenderTimeNs < nowNs) {
1373 desiredRenderTimeNs = nowNs;
1374 }
Brian Lindahlc8bd9272023-08-28 09:42:43 -06001375
1376 // If the render time is more than a second from now, then pretend the frame is supposed to be
1377 // rendered immediately, because that's what SurfaceFlinger heuristics will do. This is a tight
1378 // coupling, but is really the only way to optimize away unnecessary present fence checks in
1379 // processRenderedFrames.
1380 if (desiredRenderTimeNs > nowNs + 1*1000*1000*1000LL) {
1381 desiredRenderTimeNs = nowNs;
1382 }
1383
Brian Lindahl932bf602023-03-09 11:59:48 -07001384 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1385 // actually rendered.
1386 TrackedFrame frame;
1387 frame.number = qbo.nextFrameNumber - 1;
1388 frame.mediaTimeUs = mediaTimeUs;
1389 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1390 frame.latchTime = -1;
1391 frame.presentFence = nullptr;
1392 mTrackedFrames.push_back(frame);
1393}
1394
1395void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1396 // Grab the latch times and present fences from the frame event deltas
1397 for (const auto& delta : deltas) {
1398 for (auto& frame : mTrackedFrames) {
1399 if (delta.getFrameNumber() == frame.number) {
1400 delta.getLatchTime(&frame.latchTime);
1401 delta.getDisplayPresentFence(&frame.presentFence);
1402 }
1403 }
1404 }
1405
1406 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1407 // in fact, been rendered.
1408 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1409 while (!mTrackedFrames.empty()) {
1410 TrackedFrame & frame = mTrackedFrames.front();
1411 // Frames that should have been rendered at least 100ms in the past are checked
1412 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1413 break;
1414 }
1415
1416 // If we don't have a render time by now, then consider the frame as dropped
1417 int64_t renderTimeNs = getRenderTimeNs(frame);
1418 if (renderTimeNs != -1) {
1419 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1420 }
1421 mTrackedFrames.pop_front();
1422 }
1423}
1424
1425int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1426 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1427 if (!mHasPresentFenceTimes) {
1428 if (frame.latchTime == -1) {
1429 ALOGD("no latch time for frame %d", (int) frame.number);
1430 return -1;
1431 }
1432 return frame.latchTime;
1433 }
1434
1435 if (frame.presentFence == nullptr) {
1436 ALOGW("no present fence for frame %d", (int) frame.number);
1437 return -1;
1438 }
1439
1440 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1441
1442 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1443 ALOGW("invalid signal time for frame %d", (int) frame.number);
1444 return -1;
1445 }
1446
1447 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1448 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1449 return -1;
1450 }
1451
1452 return actualRenderTimeNs;
1453}
1454
1455void CCodecBufferChannel::pollForRenderedBuffers() {
1456 FrameEventHistoryDelta delta;
1457 mComponent->pollForRenderedFrames(&delta);
1458 processRenderedFrames(delta);
1459}
1460
Sungtak Lee214ce612023-11-01 10:01:13 +00001461void CCodecBufferChannel::onBufferReleasedFromOutputSurface(uint32_t generation) {
Sungtak Lee6700cc92023-11-22 18:04:05 +00001462 // Note: Since this is called asynchronously from IProducerListener not
1463 // knowing the internal state of CCodec/CCodecBufferChannel,
1464 // prevent mComponent from being destroyed by holding the shared reference
1465 // during this interface being executed.
1466 std::shared_ptr<Codec2Client::Component> comp = mComponent;
1467 if (comp) {
1468 comp->onBufferReleasedFromOutputSurface(generation);
1469 }
Sungtak Lee214ce612023-11-01 10:01:13 +00001470}
1471
Sungtak Lee1720e4c2024-07-31 21:15:26 +00001472void CCodecBufferChannel::onBufferAttachedToOutputSurface(uint32_t generation) {
1473 // Note: Since this is called asynchronously from IProducerListener not
1474 // knowing the internal state of CCodec/CCodecBufferChannel,
1475 // prevent mComponent from being destroyed by holding the shared reference
1476 // during this interface being executed.
1477 std::shared_ptr<Codec2Client::Component> comp = mComponent;
1478 if (comp) {
1479 comp->onBufferAttachedToOutputSurface(generation);
1480 }
1481}
1482
Pawin Vongmasa36653902018-11-15 00:10:25 -08001483status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1484 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1485 bool released = false;
1486 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001487 Mutexed<Input>::Locked input(mInput);
1488 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001489 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001490 }
1491 }
1492 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001493 Mutexed<Output>::Locked output(mOutput);
1494 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001495 released = true;
1496 }
1497 }
1498 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001499 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001500 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001501 } else {
1502 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1503 }
1504 return OK;
1505}
1506
1507void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1508 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001509 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001510
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001511 if (!input->buffers) {
1512 ALOGE("getInputBufferArray: No Input Buffers allocated");
1513 return;
1514 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001515 if (!input->buffers->isArrayMode()) {
1516 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001517 }
1518
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001519 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001520}
1521
1522void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1523 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001524 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001525 if (!output->buffers) {
1526 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1527 return;
1528 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001529 if (!output->buffers->isArrayMode()) {
1530 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001531 }
1532
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001533 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001534}
1535
1536status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001537 const sp<AMessage> &inputFormat,
1538 const sp<AMessage> &outputFormat,
1539 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001540 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1541 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001542 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001543 C2PortReorderBufferDepthTuning::output reorderDepth;
1544 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001545 C2PortActualDelayTuning::input inputDelay(0);
1546 C2PortActualDelayTuning::output outputDelay(0);
1547 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001548 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001549
Pawin Vongmasa36653902018-11-15 00:10:25 -08001550 c2_status_t err = mComponent->query(
1551 {
1552 &iStreamFormat,
1553 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001554 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001555 &reorderDepth,
1556 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001557 &inputDelay,
1558 &pipelineDelay,
1559 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001560 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001561 },
1562 {},
1563 C2_DONT_BLOCK,
1564 nullptr);
1565 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001566 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001567 return UNKNOWN_ERROR;
1568 }
1569 } else if (err != C2_OK) {
1570 return UNKNOWN_ERROR;
1571 }
1572
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001573 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1574 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1575 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1576
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001577 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1578 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001579
Pawin Vongmasa36653902018-11-15 00:10:25 -08001580 // TODO: get this from input format
1581 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1582
Sungtak Lee04b30352020-07-27 13:57:25 -07001583 // secure mode is a static parameter (shall not change in the executing state)
1584 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1585
Pawin Vongmasa36653902018-11-15 00:10:25 -08001586 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001587 int poolMask = GetCodec2PoolMask();
1588 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001589
1590 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001591 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001592 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001593 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1594 API_REFLECTION |
1595 API_VALUES |
1596 API_CURRENT_VALUES |
1597 API_DEPENDENCY |
1598 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001599 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1600 C2StreamSampleRateInfo::input sampleRate(0u);
1601 C2StreamChannelCountInfo::input channelCount(0u);
1602 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001603 std::shared_ptr<C2BlockPool> pool;
1604 {
1605 Mutexed<BlockPools>::Locked pools(mBlockPools);
1606
1607 // set default allocator ID.
1608 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001609 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001610
1611 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1612 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1613 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001614 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001615 std::vector<C2Param *> stackParams({&featuresSetting});
1616 if (audioEncoder) {
1617 stackParams.push_back(&encoderFrameSize);
1618 stackParams.push_back(&sampleRate);
1619 stackParams.push_back(&channelCount);
1620 stackParams.push_back(&pcmEncoding);
1621 } else {
1622 encoderFrameSize.invalidate();
1623 sampleRate.invalidate();
1624 channelCount.invalidate();
1625 pcmEncoding.invalidate();
1626 }
1627 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001628 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1629 C2_DONT_BLOCK,
1630 &params);
1631 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1632 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1633 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001634 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001635 C2PortAllocatorsTuning::input *inputAllocators =
1636 C2PortAllocatorsTuning::input::From(params[0].get());
1637 if (inputAllocators && inputAllocators->flexCount() > 0) {
1638 std::shared_ptr<C2Allocator> allocator;
1639 // verify allocator IDs and resolve default allocator
1640 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1641 if (allocator) {
1642 pools->inputAllocatorId = allocator->getId();
1643 } else {
1644 ALOGD("[%s] component requested invalid input allocator ID %u",
1645 mName, inputAllocators->m.values[0]);
1646 }
1647 }
1648 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001649 if (featuresSetting) {
1650 apiFeatures = featuresSetting.value;
1651 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001652
1653 // TODO: use C2Component wrapper to associate this pool with ourselves
1654 if ((poolMask >> pools->inputAllocatorId) & 1) {
1655 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1656 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1657 mName, pools->inputAllocatorId,
1658 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1659 asString(err), err);
1660 } else {
1661 err = C2_NOT_FOUND;
1662 }
1663 if (err != C2_OK) {
1664 C2BlockPool::local_id_t inputPoolId =
1665 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1666 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1667 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1668 mName, (unsigned long long)inputPoolId,
1669 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1670 asString(err), err);
1671 if (err != C2_OK) {
1672 return NO_MEMORY;
1673 }
1674 }
1675 pools->inputPool = pool;
1676 }
1677
Wonsik Kim51051262018-11-28 13:59:05 -08001678 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001679 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001680 input->inputDelay = inputDelayValue;
1681 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001682 input->numSlots = numInputSlots;
1683 input->extraBuffers.flush();
1684 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001685 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001686 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1687 input->frameReassembler.init(
1688 pool,
1689 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1690 encoderFrameSize.value,
1691 sampleRate.value,
1692 channelCount.value,
1693 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1694 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001695 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1696 // For encrypted content, framework decrypts source buffer (ashmem) into
1697 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001698 if (!buffersBoundToCodec
1699 && !input->frameReassembler
1700 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001701 input->buffers.reset(new SlotInputBuffers(mName));
1702 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001703 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001704 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001705 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001706 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001707 // This is to ensure buffers do not get released prematurely.
1708 // TODO: handle this without going into array mode
1709 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001710 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001711 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001712 }
1713 } else {
1714 if (hasCryptoOrDescrambler()) {
1715 int32_t capacity = kLinearBufferSize;
1716 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1717 if ((size_t)capacity > kMaxLinearBufferSize) {
1718 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1719 capacity = kMaxLinearBufferSize;
1720 }
1721 if (mDealer == nullptr) {
1722 mDealer = new MemoryDealer(
1723 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001724 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001725 "EncryptedLinearInputBuffers");
1726 mDecryptDestination = mDealer->allocate((size_t)capacity);
1727 }
1728 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001729 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1730 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001731 } else {
1732 mHeapSeqNum = -1;
1733 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001734 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001735 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001736 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001737 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001738 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001739 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001740 }
1741 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001742 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001743
1744 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001745 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001746 } else {
1747 // TODO: error
1748 }
Wonsik Kim51051262018-11-28 13:59:05 -08001749
1750 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001751 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001752 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001753 }
1754
1755 if (outputFormat != nullptr) {
1756 sp<IGraphicBufferProducer> outputSurface;
1757 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001758 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001759 {
1760 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001761 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001762 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001763 outputSurface = output->surface ?
1764 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001765 if (outputSurface) {
1766 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1767 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001768 outputGeneration = output->generation;
1769 }
1770
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001771 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001772 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001773 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001774
1775 {
1776 Mutexed<BlockPools>::Locked pools(mBlockPools);
1777
David Stevensc3fbb282021-01-18 18:11:20 +09001778 prevOutputPoolId = pools->outputPoolId;
1779
Pawin Vongmasa36653902018-11-15 00:10:25 -08001780 // set default allocator ID.
1781 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001782 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001783
1784 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1785 // unsuccessful.
1786 std::vector<std::unique_ptr<C2Param>> params;
1787 err = mComponent->query({ },
1788 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1789 C2_DONT_BLOCK,
1790 &params);
1791 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1792 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1793 mName, params.size(), asString(err), err);
1794 } else if (err == C2_OK && params.size() == 1) {
1795 C2PortAllocatorsTuning::output *outputAllocators =
1796 C2PortAllocatorsTuning::output::From(params[0].get());
1797 if (outputAllocators && outputAllocators->flexCount() > 0) {
1798 std::shared_ptr<C2Allocator> allocator;
1799 // verify allocator IDs and resolve default allocator
1800 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1801 if (allocator) {
1802 pools->outputAllocatorId = allocator->getId();
1803 } else {
1804 ALOGD("[%s] component requested invalid output allocator ID %u",
1805 mName, outputAllocators->m.values[0]);
1806 }
1807 }
1808 }
1809
1810 // use bufferqueue if outputting to a surface.
1811 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1812 // if unsuccessful.
1813 if (outputSurface) {
1814 params.clear();
1815 err = mComponent->query({ },
1816 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1817 C2_DONT_BLOCK,
1818 &params);
1819 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1820 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1821 mName, params.size(), asString(err), err);
1822 } else if (err == C2_OK && params.size() == 1) {
1823 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1824 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1825 if (surfaceAllocator) {
1826 std::shared_ptr<C2Allocator> allocator;
1827 // verify allocator IDs and resolve default allocator
1828 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1829 if (allocator) {
1830 pools->outputAllocatorId = allocator->getId();
1831 } else {
1832 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1833 mName, surfaceAllocator->value);
1834 err = C2_BAD_VALUE;
1835 }
1836 }
1837 }
1838 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1839 && err != C2_OK
1840 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1841 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1842 }
1843 }
1844
1845 if ((poolMask >> pools->outputAllocatorId) & 1) {
1846 err = mComponent->createBlockPool(
1847 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1848 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1849 mName, pools->outputAllocatorId,
1850 (unsigned long long)pools->outputPoolId,
1851 asString(err));
1852 } else {
1853 err = C2_NOT_FOUND;
1854 }
1855 if (err != C2_OK) {
1856 // use basic pool instead
1857 pools->outputPoolId =
1858 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1859 }
1860
1861 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1862 // component.
1863 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1864 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1865
1866 std::vector<std::unique_ptr<C2SettingResult>> failures;
1867 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1868 ALOGD("[%s] Configured output block pool ids %llu => %s",
1869 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1870 outputPoolId_ = pools->outputPoolId;
1871 }
1872
David Stevensc3fbb282021-01-18 18:11:20 +09001873 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1874 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1875 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1876 if (err != C2_OK) {
1877 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1878 (unsigned long long) prevOutputPoolId, asString(err), err);
1879 }
1880 }
1881
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001882 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001883 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001884 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001885 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001886 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001887 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001888 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001889 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001890 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001891 }
1892 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001893 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001894 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001895 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001896
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001897 output->buffers->clearStash();
1898 if (reorderDepth) {
1899 output->buffers->setReorderDepth(reorderDepth.value);
1900 }
1901 if (reorderKey) {
1902 output->buffers->setReorderKey(reorderKey.value);
1903 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001904
1905 // Try to set output surface to created block pool if given.
1906 if (outputSurface) {
1907 mComponent->setOutputSurface(
1908 outputPoolId_,
1909 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001910 outputGeneration,
1911 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001912 } else {
1913 // configure CPU read consumer usage
1914 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1915 std::vector<std::unique_ptr<C2SettingResult>> failures;
1916 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1917 // do not print error message for now as most components may not yet
1918 // support this setting
1919 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1920 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001921 }
1922
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001923 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001924 if (buffersBoundToCodec) {
1925 // WORKAROUND: if we're using early CSD workaround we convert to
1926 // array mode, to appease apps assuming the output
1927 // buffers to be of the same size.
1928 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1929 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001930
1931 int32_t channelCount;
1932 int32_t sampleRate;
1933 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1934 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1935 int32_t delay = 0;
1936 int32_t padding = 0;;
1937 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1938 delay = 0;
1939 }
1940 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1941 padding = 0;
1942 }
1943 if (delay || padding) {
Arun Johnson52d323e2024-01-05 21:16:56 +00001944 // We need write access to the buffers, so turn them into array mode.
1945 // TODO: b/321930152 - define SkipCutOutputBuffers that takes output from
1946 // component, runs it through SkipCutBuffer and allocate local buffer to be
1947 // used by fwk. Make initSkipCutBuffer() return OutputBuffers similar to
1948 // toArrayMode().
1949 if (!output->buffers->isArrayMode()) {
1950 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1951 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001952 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001953 }
1954 }
1955 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001956
1957 int32_t tunneled = 0;
1958 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1959 tunneled = 0;
1960 }
1961 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001962 }
1963
1964 // Set up pipeline control. This has to be done after mInputBuffers and
1965 // mOutputBuffers are initialized to make sure that lingering callbacks
1966 // about buffers from the previous generation do not interfere with the
1967 // newly initialized pipeline capacity.
1968
Wonsik Kim62545252021-01-20 11:25:41 -08001969 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001970 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001971 watcher->inputDelay(inputDelayValue)
1972 .pipelineDelay(pipelineDelayValue)
1973 .outputDelay(outputDelayValue)
Houxiang Dai0b573282023-03-11 18:31:56 +08001974 .smoothnessFactor(kSmoothnessFactor)
1975 .tunneled(mTunneled);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001976 watcher->flush();
1977 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001978
1979 mInputMetEos = false;
1980 mSync.start();
1981 return OK;
1982}
1983
Wonsik Kim34b28b42022-05-20 15:49:32 -07001984status_t CCodecBufferChannel::prepareInitialInputBuffers(
Arun Johnson326166e2023-07-28 19:11:52 +00001985 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers, bool retry) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001986 if (mInputSurface) {
1987 return OK;
1988 }
1989
Wonsik Kim34b28b42022-05-20 15:49:32 -07001990 size_t numInputSlots = mInput.lock()->numSlots;
Arun Johnson326166e2023-07-28 19:11:52 +00001991 int retryCount = 1;
1992 for (; clientInputBuffers->empty() && retryCount >= 0; retryCount--) {
1993 {
1994 Mutexed<Input>::Locked input(mInput);
1995 while (clientInputBuffers->size() < numInputSlots) {
1996 size_t index;
1997 sp<MediaCodecBuffer> buffer;
1998 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1999 break;
2000 }
2001 clientInputBuffers->emplace(index, buffer);
Wonsik Kim34b28b42022-05-20 15:49:32 -07002002 }
Arun Johnson326166e2023-07-28 19:11:52 +00002003 }
2004 if (!retry || (retryCount <= 0)) {
2005 break;
2006 }
2007 if (clientInputBuffers->empty()) {
2008 // wait: buffer may be in transit from component.
2009 std::this_thread::sleep_for(std::chrono::milliseconds(4));
Wonsik Kim34b28b42022-05-20 15:49:32 -07002010 }
2011 }
2012 if (clientInputBuffers->empty()) {
2013 ALOGW("[%s] start: cannot allocate memory at all", mName);
2014 return NO_MEMORY;
2015 } else if (clientInputBuffers->size() < numInputSlots) {
2016 ALOGD("[%s] start: cannot allocate memory for all slots, "
2017 "only %zu buffers allocated",
2018 mName, clientInputBuffers->size());
2019 } else {
2020 ALOGV("[%s] %zu initial input buffers available",
2021 mName, clientInputBuffers->size());
2022 }
2023 return OK;
2024}
2025
2026status_t CCodecBufferChannel::requestInitialInputBuffers(
2027 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002028 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07002029 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
2030 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
2031 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002032 return UNKNOWN_ERROR;
2033 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002034
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002035 std::list<std::unique_ptr<C2Work>> flushedConfigs;
2036 mFlushedConfigs.lock()->swap(flushedConfigs);
2037 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07002038 {
2039 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2040 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
2041 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
2042 watcher->onWorkQueued(
2043 work->input.ordinal.frameIndex.peeku(),
2044 std::vector(work->input.buffers),
2045 now);
2046 }
2047 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002048 err = mComponent->queue(&flushedConfigs);
2049 if (err != C2_OK) {
2050 ALOGW("[%s] Error while queueing a flushed config", mName);
2051 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002052 }
2053 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002054 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07002055 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
2056 !clientInputBuffers.empty()) {
2057 size_t minIndex = clientInputBuffers.begin()->first;
2058 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
2059 for (const auto &[index, buffer] : clientInputBuffers) {
2060 if (minBuffer->capacity() > buffer->capacity()) {
2061 minIndex = index;
2062 minBuffer = buffer;
2063 }
2064 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002065 // WORKAROUND: Some apps expect CSD available without queueing
2066 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07002067 minBuffer->setRange(0, 0);
2068 minBuffer->meta()->clear();
2069 minBuffer->meta()->setInt64("timeUs", 0);
2070 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002071 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
2072 mName);
2073 return UNKNOWN_ERROR;
2074 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07002075 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002076 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002077
Wonsik Kim34b28b42022-05-20 15:49:32 -07002078 for (const auto &[index, buffer] : clientInputBuffers) {
2079 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002080 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002081
Pawin Vongmasa36653902018-11-15 00:10:25 -08002082 return OK;
2083}
2084
2085void CCodecBufferChannel::stop() {
2086 mSync.stop();
2087 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302088 mInfoBuffers.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002089}
2090
Sungtak Lee99144332023-01-26 11:03:14 +00002091void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
2092 sp<Surface> surface = mOutputSurface.lock()->surface;
2093 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00002094 C2BlockPool::local_id_t outputPoolId;
2095 {
2096 Mutexed<BlockPools>::Locked pools(mBlockPools);
2097 outputPoolId = pools->outputPoolId;
2098 }
2099 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00002100
2101 if (pushBlankBuffer) {
2102 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
2103 if (anw) {
2104 pushBlankBuffersToNativeWindow(anw.get());
2105 }
2106 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00002107 }
2108}
2109
Wonsik Kim936a89c2020-05-08 16:07:50 -07002110void CCodecBufferChannel::reset() {
2111 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08002112 if (mInputSurface != nullptr) {
2113 mInputSurface.reset();
2114 }
2115 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002116 {
2117 Mutexed<Input>::Locked input(mInput);
2118 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002119 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002120 }
2121 {
2122 Mutexed<Output>::Locked output(mOutput);
2123 output->buffers.reset();
2124 }
Brian Lindahl932bf602023-03-09 11:59:48 -07002125 // reset the frames that are being tracked for onFrameRendered callbacks
2126 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002127}
2128
2129void CCodecBufferChannel::release() {
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302130 mInfoBuffers.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002131 mComponent.reset();
2132 mInputAllocator.reset();
2133 mOutputSurface.lock()->surface.clear();
2134 {
2135 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
2136 blockPools->inputPool.reset();
2137 blockPools->outputPoolIntf.reset();
2138 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002139 setCrypto(nullptr);
2140 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002141}
2142
Pawin Vongmasa36653902018-11-15 00:10:25 -08002143void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
2144 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002145 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002146 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07002147 {
2148 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2149 for (const std::unique_ptr<C2Work> &work : flushedWork) {
2150 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
2151 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
2152 watcher->onWorkDone(frameIndex);
2153 continue;
2154 }
2155 if (work->input.buffers.empty()
2156 || work->input.buffers.front() == nullptr
2157 || work->input.buffers.front()->data().linearBlocks().empty()) {
2158 ALOGD("[%s] no linear codec config data found", mName);
2159 watcher->onWorkDone(frameIndex);
2160 continue;
2161 }
2162 std::unique_ptr<C2Work> copy(new C2Work);
2163 copy->input.flags = C2FrameData::flags_t(
2164 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
2165 copy->input.ordinal = work->input.ordinal;
2166 copy->input.ordinal.frameIndex = mFrameIndex++;
2167 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
2168 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
2169 }
2170 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
2171 copy->input.configUpdate.push_back(C2Param::Copy(*param));
2172 }
2173 copy->input.infoBuffers.insert(
2174 copy->input.infoBuffers.begin(),
2175 work->input.infoBuffers.begin(),
2176 work->input.infoBuffers.end());
2177 copy->worklets.emplace_back(new C2Worklet);
2178 configs.push_back(std::move(copy));
2179 watcher->onWorkDone(frameIndex);
2180 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002181 }
2182 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002183 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002184 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002185 Mutexed<Input>::Locked input(mInput);
2186 input->buffers->flush();
2187 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002188 }
2189 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002190 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002191 if (output->buffers) {
2192 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002193 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002194 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002195 }
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302196 mInfoBuffers.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002197}
2198
2199void CCodecBufferChannel::onWorkDone(
2200 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002201 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002202 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002203 feedInputBufferIfAvailable();
2204 }
2205}
2206
2207void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08002208 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07002209 if (mInputSurface) {
2210 return;
2211 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002212 std::shared_ptr<C2Buffer> buffer =
2213 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002214 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002215 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002216 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002217 if (input->lastFlushIndex >= frameIndex) {
2218 ALOGD("[%s] Ignoring stale input buffer done callback: "
2219 "last flush index = %lld, frameIndex = %lld",
2220 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
2221 } else {
2222 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
2223 if (!newInputSlotAvailable) {
2224 (void)input->extraBuffers.expireComponentBuffer(buffer);
2225 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002226 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002227 }
2228 if (newInputSlotAvailable) {
2229 feedInputBufferIfAvailable();
2230 }
2231}
2232
2233bool CCodecBufferChannel::handleWork(
2234 std::unique_ptr<C2Work> work,
2235 const sp<AMessage> &outputFormat,
2236 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07002237 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00002238 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002239 if (!output->buffers) {
2240 return false;
2241 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08002242 }
2243
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002244 // Whether the output buffer should be reported to the client or not.
2245 bool notifyClient = false;
2246
2247 if (work->result == C2_OK){
2248 notifyClient = true;
2249 } else if (work->result == C2_NOT_FOUND) {
2250 ALOGD("[%s] flushed work; ignored.", mName);
2251 } else {
2252 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
2253 // the config update.
2254 ALOGD("[%s] work failed to complete: %d", mName, work->result);
2255 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
2256 return false;
2257 }
2258
2259 if ((work->input.ordinal.frameIndex -
2260 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002261 // Discard frames from previous generation.
2262 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002263 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002264 }
2265
Wonsik Kim524b0582019-03-12 11:28:57 -07002266 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08002267 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002268 || !(work->worklets.front()->output.flags &
2269 C2FrameData::FLAG_INCOMPLETE))) {
2270 mPipelineWatcher.lock()->onWorkDone(
2271 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002272 }
2273
2274 // NOTE: MediaCodec usage supposedly have only one worklet
2275 if (work->worklets.size() != 1u) {
2276 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
2277 mName, work->worklets.size());
2278 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2279 return false;
2280 }
2281
2282 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
2283
2284 std::shared_ptr<C2Buffer> buffer;
2285 // NOTE: MediaCodec usage supposedly have only one output stream.
2286 if (worklet->output.buffers.size() > 1u) {
2287 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
2288 mName, worklet->output.buffers.size());
2289 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2290 return false;
2291 } else if (worklet->output.buffers.size() == 1u) {
2292 buffer = worklet->output.buffers[0];
2293 if (!buffer) {
2294 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
2295 }
2296 }
2297
Wonsik Kim3dedf682021-05-03 10:57:09 -07002298 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
2299 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002300 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002301 while (!worklet->output.configUpdate.empty()) {
2302 std::unique_ptr<C2Param> param;
2303 worklet->output.configUpdate.back().swap(param);
2304 worklet->output.configUpdate.pop_back();
2305 switch (param->coreIndex().coreIndex()) {
2306 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
2307 C2PortReorderBufferDepthTuning::output reorderDepth;
2308 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002309 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
2310 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002311 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002312 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002313 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002314 ALOGD("[%s] onWorkDone: failed to read reorder depth",
2315 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002316 }
2317 break;
2318 }
2319 case C2PortReorderKeySetting::CORE_INDEX: {
2320 C2PortReorderKeySetting::output reorderKey;
2321 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07002322 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002323 ALOGV("[%s] onWorkDone: updated reorder key to %u",
2324 mName, reorderKey.value);
2325 } else {
2326 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
2327 }
2328 break;
2329 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002330 case C2PortActualDelayTuning::CORE_INDEX: {
2331 if (param->isGlobal()) {
2332 C2ActualPipelineDelayTuning pipelineDelay;
2333 if (pipelineDelay.updateFrom(*param)) {
2334 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
2335 mName, pipelineDelay.value);
2336 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002337 (void)mPipelineWatcher.lock()->pipelineDelay(
2338 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002339 }
2340 }
2341 if (param->forInput()) {
2342 C2PortActualDelayTuning::input inputDelay;
2343 if (inputDelay.updateFrom(*param)) {
2344 ALOGV("[%s] onWorkDone: updating input delay %u",
2345 mName, inputDelay.value);
2346 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002347 (void)mPipelineWatcher.lock()->inputDelay(
2348 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002349 }
2350 }
2351 if (param->forOutput()) {
2352 C2PortActualDelayTuning::output outputDelay;
2353 if (outputDelay.updateFrom(*param)) {
2354 ALOGV("[%s] onWorkDone: updating output delay %u",
2355 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002356 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002357 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002358 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002359
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002360 }
2361 }
2362 break;
2363 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08002364 case C2PortTunnelSystemTime::CORE_INDEX: {
2365 C2PortTunnelSystemTime::output frameRenderTime;
2366 if (frameRenderTime.updateFrom(*param)) {
2367 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
2368 mName, (long long)frameRenderTime.value,
2369 (long long)worklet->output.ordinal.timestamp.peekll());
2370 mCCodecCallback->onOutputFramesRendered(
2371 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
2372 }
2373 break;
2374 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02002375 case C2StreamTunnelHoldRender::CORE_INDEX: {
2376 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
2377 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
2378 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
2379 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
2380 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
2381 mCCodecCallback->onFirstTunnelFrameReady();
2382 break;
2383 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002384 default:
2385 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2386 mName, param->index());
2387 break;
2388 }
2389 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002390 if (newInputDelay || newPipelineDelay) {
2391 Mutexed<Input>::Locked input(mInput);
2392 size_t newNumSlots =
2393 newInputDelay.value_or(input->inputDelay) +
2394 newPipelineDelay.value_or(input->pipelineDelay) +
2395 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08002396 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002397 if (input->buffers->isArrayMode()) {
2398 if (input->numSlots >= newNumSlots) {
2399 input->numExtraSlots = 0;
2400 } else {
2401 input->numExtraSlots = newNumSlots - input->numSlots;
2402 }
2403 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2404 mName, input->numExtraSlots);
2405 } else {
2406 input->numSlots = newNumSlots;
2407 }
2408 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002409 size_t numOutputSlots = 0;
2410 uint32_t reorderDepth = 0;
2411 bool outputBuffersChanged = false;
2412 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2413 Mutexed<Output>::Locked output(mOutput);
2414 if (!output->buffers) {
2415 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002416 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002417 numOutputSlots = output->numSlots;
2418 if (newReorderKey) {
2419 output->buffers->setReorderKey(newReorderKey.value());
2420 }
2421 if (newReorderDepth) {
2422 output->buffers->setReorderDepth(newReorderDepth.value());
2423 }
2424 reorderDepth = output->buffers->getReorderDepth();
2425 if (newOutputDelay) {
2426 output->outputDelay = newOutputDelay.value();
2427 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2428 if (output->numSlots < numOutputSlots) {
2429 output->numSlots = numOutputSlots;
2430 if (output->buffers->isArrayMode()) {
2431 OutputBuffersArray *array =
2432 (OutputBuffersArray *)output->buffers.get();
2433 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2434 mName, numOutputSlots);
2435 array->grow(numOutputSlots);
2436 outputBuffersChanged = true;
2437 }
2438 }
2439 }
2440 numOutputSlots = output->numSlots;
2441 }
2442 if (outputBuffersChanged) {
2443 mCCodecCallback->onOutputBuffersChanged();
2444 }
2445 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002446 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002447 {
2448 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2449 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002450 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002451 if (output->surface) {
2452 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2453 }
2454 }
2455 if (maxDequeueCount > 0) {
2456 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002457 }
2458 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002459
Pawin Vongmasa36653902018-11-15 00:10:25 -08002460 int32_t flags = 0;
2461 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002462 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002463 ALOGV("[%s] onWorkDone: output EOS", mName);
2464 }
2465
Pawin Vongmasa36653902018-11-15 00:10:25 -08002466 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2467 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2468 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2469 // shall correspond to the client input timesamp (in customOrdinal). By using the
2470 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2471 // produces multiple output.
2472 c2_cntr64_t timestamp =
2473 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2474 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002475 if (mInputSurface != nullptr) {
2476 // When using input surface we need to restore the original input timestamp.
2477 timestamp = work->input.ordinal.customOrdinal;
2478 }
My Name6bd9a7d2022-03-25 12:37:58 -07002479 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2480 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002481 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2482 mName,
2483 work->input.ordinal.customOrdinal.peekll(),
2484 work->input.ordinal.timestamp.peekll(),
2485 worklet->output.ordinal.timestamp.peekll(),
2486 timestamp.peekll());
2487
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002488 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002489 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002490 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002491 if (!output->buffers) {
2492 return false;
2493 }
2494 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002495 output->buffers->updateSkipCutBuffer(outputFormat);
2496 output->buffers->setFormat(outputFormat);
2497 }
2498 if (!notifyClient) {
2499 return false;
2500 }
2501 size_t index;
2502 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002503 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002504 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002505 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002506 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2507
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002508 // TRICKY: we want popped buffers reported in order, so sending
2509 // the callback while holding the lock here. This assumes that
2510 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2511 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002512 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002513 } else {
2514 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002515 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002516 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002517 return false;
2518 }
2519 }
2520
Wonsik Kimec585c32021-10-01 01:11:00 -07002521 bool drop = false;
2522 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2523 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2524 drop = true;
2525 }
2526
Marc Kassisec910342022-11-25 11:43:05 +01002527 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2528 // HAL, the flag is then removed in the corresponding output buffer.
2529 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2530 flags |= BUFFER_FLAG_DECODE_ONLY;
2531 }
2532
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002533 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002534 if (mTunneled && drop && outputFormat) {
Houxiang Daie74e5062022-05-19 15:32:54 +08002535 if (mOutputFormat != outputFormat) {
2536 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2537 mName, work->input.ordinal.frameIndex.peekull());
2538 mOutputFormat = outputFormat;
2539 } else {
2540 ALOGV("[%s] onWorkDone: Not reporting output buffer without format change (%lld)",
2541 mName, work->input.ordinal.frameIndex.peekull());
2542 notifyClient = false;
2543 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002544 } else {
2545 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2546 mName, work->input.ordinal.frameIndex.peekull());
2547 notifyClient = false;
2548 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002549 }
2550
2551 if (buffer) {
2552 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2553 // TODO: properly translate these to metadata
2554 switch (info->coreIndex().coreIndex()) {
2555 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002556 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002557 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002558 }
2559 break;
2560 default:
2561 break;
2562 }
2563 }
2564 }
2565
2566 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002567 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002568 if (!output->buffers) {
2569 return false;
2570 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002571 output->buffers->pushToStash(
2572 buffer,
2573 notifyClient,
2574 timestamp.peek(),
2575 flags,
2576 outputFormat,
2577 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002578 }
2579 sendOutputBuffers();
2580 return true;
2581}
2582
2583void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002584 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002585 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002586 sp<MediaCodecBuffer> outBuffer;
2587 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002588
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002589 constexpr int kMaxReallocTry = 5;
2590 int reallocTryNum = 0;
2591
Pawin Vongmasa36653902018-11-15 00:10:25 -08002592 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002593 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002594 if (!output->buffers) {
2595 return;
2596 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002597 action = output->buffers->popFromStashAndRegister(
2598 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002599 if (action != OutputBuffers::REALLOCATE) {
2600 reallocTryNum = 0;
2601 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002602 switch (action) {
2603 case OutputBuffers::SKIP:
2604 return;
2605 case OutputBuffers::DISCARD:
2606 break;
2607 case OutputBuffers::NOTIFY_CLIENT:
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002608 {
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002609 // TRICKY: we want popped buffers reported in order, so sending
2610 // the callback while holding the lock here. This assumes that
2611 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2612 // callbacks are always sent with the Output lock held.
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002613 if (c2Buffer) {
2614 std::shared_ptr<const C2AccessUnitInfos::output> bufferMetadata =
2615 std::static_pointer_cast<const C2AccessUnitInfos::output>(
2616 c2Buffer->getInfo(C2AccessUnitInfos::output::PARAM_TYPE));
2617 if (bufferMetadata && bufferMetadata->flexCount() > 0) {
2618 uint32_t flag = 0;
2619 std::vector<AccessUnitInfo> accessUnitInfos;
2620 for (int nMeta = 0; nMeta < bufferMetadata->flexCount(); nMeta++) {
2621 const C2AccessUnitInfosStruct &bufferMetadataStruct =
2622 bufferMetadata->m.values[nMeta];
2623 flag = convertFlags(bufferMetadataStruct.flags, false);
2624 accessUnitInfos.emplace_back(flag,
2625 static_cast<size_t>(bufferMetadataStruct.size),
2626 static_cast<size_t>(bufferMetadataStruct.timestamp));
2627 }
2628 sp<WrapperObject<std::vector<AccessUnitInfo>>> obj{
2629 new WrapperObject<std::vector<AccessUnitInfo>>{accessUnitInfos}};
2630 outBuffer->meta()->setObject("accessUnitInfo", obj);
2631 }
2632 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002633 mCallback->onOutputBufferAvailable(index, outBuffer);
2634 break;
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002635 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002636 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002637 if (++reallocTryNum > kMaxReallocTry) {
2638 output.unlock();
2639 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2640 mName, kMaxReallocTry);
2641 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2642 return;
2643 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002644 if (!output->buffers->isArrayMode()) {
2645 output->buffers =
2646 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002647 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002648 static_cast<OutputBuffersArray*>(output->buffers.get())->
2649 realloc(c2Buffer);
2650 output.unlock();
2651 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002652 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002653 case OutputBuffers::RETRY:
2654 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2655 mName);
2656 return;
2657 default:
2658 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2659 "corrupted BufferAction value (%d) "
2660 "returned from popFromStashAndRegister.",
2661 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002662 return;
2663 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002664 }
2665}
2666
Sungtak Lee214ce612023-11-01 10:01:13 +00002667status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface,
2668 uint32_t generation, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002669 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002670 int maxDequeueCount;
2671 sp<Surface> oldSurface;
2672 {
2673 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2674 maxDequeueCount = outputSurface->maxDequeueBuffers;
2675 oldSurface = outputSurface->surface;
2676 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002677 if (newSurface) {
2678 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002679 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002680 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002681 producer = newSurface->getIGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002682 } else {
2683 ALOGE("[%s] setting output surface to null", mName);
2684 return INVALID_OPERATION;
2685 }
2686
2687 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2688 C2BlockPool::local_id_t outputPoolId;
2689 {
2690 Mutexed<BlockPools>::Locked pools(mBlockPools);
2691 outputPoolId = pools->outputPoolId;
2692 outputPoolIntf = pools->outputPoolIntf;
2693 }
2694
2695 if (outputPoolIntf) {
2696 if (mComponent->setOutputSurface(
2697 outputPoolId,
2698 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002699 generation,
2700 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002701 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2702 return INVALID_OPERATION;
2703 }
2704 }
2705
2706 {
2707 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2708 output->surface = newSurface;
2709 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002710 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002711 }
2712
Sungtak Lee99144332023-01-26 11:03:14 +00002713 if (oldSurface && pushBlankBuffer) {
2714 // When ReleaseSurface was set from MediaCodec,
2715 // pushing a blank buffer at the end might be necessary.
2716 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2717 if (anw) {
2718 pushBlankBuffersToNativeWindow(anw.get());
2719 }
2720 }
2721
Pawin Vongmasa36653902018-11-15 00:10:25 -08002722 return OK;
2723}
2724
Wonsik Kimab34ed62019-01-31 15:28:46 -08002725PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002726 // Otherwise, component may have stalled work due to input starvation up to
2727 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002728 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2729 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002730 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002731 size_t outputDelay = mOutput.lock()->outputDelay;
2732 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002733 Mutexed<Input>::Locked input(mInput);
2734 n = input->inputDelay + input->pipelineDelay + outputDelay;
2735 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002736 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002737}
2738
Pawin Vongmasa36653902018-11-15 00:10:25 -08002739void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2740 mMetaMode = mode;
2741}
2742
Wonsik Kim596187e2019-10-25 12:44:10 -07002743void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002744 if (mCrypto != nullptr) {
2745 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2746 mCrypto->unsetHeap(entry.second);
2747 }
2748 mHeapSeqNumMap.clear();
2749 if (mHeapSeqNum >= 0) {
2750 mCrypto->unsetHeap(mHeapSeqNum);
2751 mHeapSeqNum = -1;
2752 }
2753 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002754 mCrypto = crypto;
2755}
2756
2757void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2758 mDescrambler = descrambler;
2759}
2760
Songyue Han1e6769b2023-08-30 18:09:27 +00002761uint32_t CCodecBufferChannel::getBuffersPixelFormat(bool isEncoder) {
2762 if (isEncoder) {
2763 return getInputBuffersPixelFormat();
2764 } else {
2765 return getOutputBuffersPixelFormat();
2766 }
2767}
2768
2769uint32_t CCodecBufferChannel::getInputBuffersPixelFormat() {
2770 Mutexed<Input>::Locked input(mInput);
2771 if (input->buffers == nullptr) {
2772 return PIXEL_FORMAT_UNKNOWN;
2773 }
2774 return input->buffers->getPixelFormatIfApplicable();
2775}
2776
2777uint32_t CCodecBufferChannel::getOutputBuffersPixelFormat() {
2778 Mutexed<Output>::Locked output(mOutput);
2779 if (output->buffers == nullptr) {
2780 return PIXEL_FORMAT_UNKNOWN;
2781 }
2782 return output->buffers->getPixelFormatIfApplicable();
2783}
2784
2785void CCodecBufferChannel::resetBuffersPixelFormat(bool isEncoder) {
2786 if (isEncoder) {
2787 Mutexed<Input>::Locked input(mInput);
2788 if (input->buffers == nullptr) {
2789 return;
2790 }
2791 input->buffers->resetPixelFormatIfApplicable();
2792 } else {
2793 Mutexed<Output>::Locked output(mOutput);
2794 if (output->buffers == nullptr) {
2795 return;
2796 }
2797 output->buffers->resetPixelFormatIfApplicable();
2798 }
2799}
2800
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302801void CCodecBufferChannel::setInfoBuffer(const std::shared_ptr<C2InfoBuffer> &buffer) {
Harish Mahendrakar2b095d92024-05-13 16:51:15 -07002802 if (mInputSurface == nullptr) {
2803 mInfoBuffers.push_back(buffer);
2804 } else {
2805 std::list<std::unique_ptr<C2Work>> items;
2806 std::unique_ptr<C2Work> work(new C2Work);
2807 work->input.infoBuffers.emplace_back(*buffer);
2808 work->worklets.emplace_back(new C2Worklet);
2809 items.push_back(std::move(work));
2810 c2_status_t err = mComponent->queue(&items);
2811 }
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302812}
2813
Pawin Vongmasa36653902018-11-15 00:10:25 -08002814status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2815 // C2_OK is always translated to OK.
2816 if (c2s == C2_OK) {
2817 return OK;
2818 }
2819
2820 // Operation-dependent translation
2821 // TODO: Add as necessary
2822 switch (c2op) {
2823 case C2_OPERATION_Component_start:
2824 switch (c2s) {
2825 case C2_NO_MEMORY:
2826 return NO_MEMORY;
2827 default:
2828 return UNKNOWN_ERROR;
2829 }
2830 default:
2831 break;
2832 }
2833
2834 // Backup operation-agnostic translation
2835 switch (c2s) {
2836 case C2_BAD_INDEX:
2837 return BAD_INDEX;
2838 case C2_BAD_VALUE:
2839 return BAD_VALUE;
2840 case C2_BLOCKING:
2841 return WOULD_BLOCK;
2842 case C2_DUPLICATE:
2843 return ALREADY_EXISTS;
2844 case C2_NO_INIT:
2845 return NO_INIT;
2846 case C2_NO_MEMORY:
2847 return NO_MEMORY;
2848 case C2_NOT_FOUND:
2849 return NAME_NOT_FOUND;
2850 case C2_TIMED_OUT:
2851 return TIMED_OUT;
2852 case C2_BAD_STATE:
2853 case C2_CANCELED:
2854 case C2_CANNOT_DO:
2855 case C2_CORRUPTED:
2856 case C2_OMITTED:
2857 case C2_REFUSED:
2858 return UNKNOWN_ERROR;
2859 default:
2860 return -static_cast<status_t>(c2s);
2861 }
2862}
2863
Pawin Vongmasa36653902018-11-15 00:10:25 -08002864} // namespace android