blob: c7ab82f9a61293a054d22282c2326ea25f821bb3 [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 Kim0487b782020-10-28 11:45:50 -07001072 size_t numActiveSlots = 0;
1073 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001074 sp<MediaCodecBuffer> inBuffer;
1075 size_t index;
1076 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001077 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -07001078 numActiveSlots = input->buffers->numActiveSlots();
1079 if (numActiveSlots >= input->numSlots) {
1080 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001081 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001082 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001083 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001084 break;
1085 }
1086 }
1087 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
1088 mCallback->onInputBufferAvailable(index, inBuffer);
1089 }
Wonsik Kim0487b782020-10-28 11:45:50 -07001090 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001091}
1092
1093status_t CCodecBufferChannel::renderOutputBuffer(
1094 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001095 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001096 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001097 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001098 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001099 Mutexed<Output>::Locked output(mOutput);
1100 if (output->buffers) {
1101 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001102 }
1103 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001104 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
1105 // set to true.
1106 sendOutputBuffers();
1107 // input buffer feeding may have been gated by pending output buffers
1108 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001109 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001110 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -07001111 std::call_once(mRenderWarningFlag, [this] {
1112 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
1113 "timestamp or render=true with non-video buffers. Apps should "
1114 "call releaseOutputBuffer() with render=false for those.",
1115 mName);
1116 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001117 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001118 return INVALID_OPERATION;
1119 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001120
1121#if 0
1122 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
1123 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
1124 for (const std::shared_ptr<const C2Info> &info : infoParams) {
1125 AString res;
1126 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
1127 if (ix) res.append(", ");
1128 res.append(*((int32_t*)info.get() + (ix / 4)));
1129 }
1130 ALOGV(" [%s]", res.c_str());
1131 }
1132#endif
1133 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
1134 std::static_pointer_cast<const C2StreamRotationInfo::output>(
1135 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
1136 bool flip = rotation && (rotation->flip & 1);
1137 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +09001138
1139 {
1140 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1141 if (output->surface == nullptr) {
1142 ALOGI("[%s] cannot render buffer without surface", mName);
1143 return OK;
1144 }
1145 int64_t frameIndex;
1146 buffer->meta()->findInt64("frameIndex", &frameIndex);
1147 if (output->rotation.count(frameIndex) != 0) {
1148 auto it = output->rotation.find(frameIndex);
1149 quarters = (it->second / 90) & 3;
1150 output->rotation.erase(it);
1151 }
1152 }
1153
Pawin Vongmasa36653902018-11-15 00:10:25 -08001154 uint32_t transform = 0;
1155 switch (quarters) {
1156 case 0: // no rotation
1157 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
1158 break;
1159 case 1: // 90 degrees counter-clockwise
1160 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
1161 : HAL_TRANSFORM_ROT_270;
1162 break;
1163 case 2: // 180 degrees
1164 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
1165 break;
1166 case 3: // 90 degrees clockwise
1167 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
1168 : HAL_TRANSFORM_ROT_90;
1169 break;
1170 }
1171
1172 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
1173 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
1174 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
1175 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
1176 if (surfaceScaling) {
1177 videoScalingMode = surfaceScaling->value;
1178 }
1179
1180 // Use dataspace from format as it has the default aspects already applied
1181 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
1182 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
1183
1184 // HDR static info
1185 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
1186 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
1187 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
1188
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001189 // HDR10 plus info
1190 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
1191 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
1192 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +08001193 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
1194 hdr10PlusInfo.reset();
1195 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001196
Wonsik Kima79c5522022-01-18 16:29:24 -08001197 // HDR dynamic info
1198 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
1199 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
1200 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
1201 // TODO: make this sticky & enable unset
1202 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
1203 hdrDynamicInfo.reset();
1204 }
1205
1206 if (hdr10PlusInfo) {
1207 // C2StreamHdr10PlusInfo is deprecated; components should use
1208 // C2StreamHdrDynamicMetadataInfo
1209 // TODO: #metric
1210 if (hdrDynamicInfo) {
1211 // It is unexpected that C2StreamHdr10PlusInfo and
1212 // C2StreamHdrDynamicMetadataInfo is both present.
1213 // C2StreamHdrDynamicMetadataInfo takes priority.
1214 // TODO: #metric
1215 } else {
1216 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
1217 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
1218 hdr10PlusInfo->flexCount(),
1219 0u,
1220 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
1221 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
1222 hdrDynamicInfo = info;
1223 }
1224 }
1225
Pawin Vongmasa36653902018-11-15 00:10:25 -08001226 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
1227 if (blocks.size() != 1u) {
1228 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
1229 return UNKNOWN_ERROR;
1230 }
1231 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -07001232 C2Fence c2fence = block.fence();
1233 sp<Fence> fence = Fence::NO_FENCE;
1234 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
1235 // Once C2Fence::type() is added, check the exact C2Fence type
1236 if (c2fence.isHW()) {
1237 int fenceFd = c2fence.fd();
1238 fence = sp<Fence>::make(fenceFd);
1239 if (!fence) {
1240 ALOGE("[%s] Failed to allocate a fence", mName);
1241 close(fenceFd);
1242 return NO_MEMORY;
1243 }
1244 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001245
1246 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -07001247 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001248 timestampNs,
1249 false, // droppable
1250 dataSpace,
1251 Rect(blocks.front().crop().left,
1252 blocks.front().crop().top,
1253 blocks.front().crop().right(),
1254 blocks.front().crop().bottom()),
1255 videoScalingMode,
1256 transform,
Lubin Yin92427a52022-04-18 16:57:39 -07001257 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -08001258 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001259 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001260 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +08001261 // If mastering max and min luminance fields are 0, do not use them.
1262 // It indicates the value may not be present in the stream.
1263 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
1264 hdrStaticInfo->mastering.minLuminance > 0.0f) {
1265 struct android_smpte2086_metadata smpte2086_meta = {
1266 .displayPrimaryRed = {
1267 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
1268 },
1269 .displayPrimaryGreen = {
1270 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
1271 },
1272 .displayPrimaryBlue = {
1273 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
1274 },
1275 .whitePoint = {
1276 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
1277 },
1278 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
1279 .minLuminance = hdrStaticInfo->mastering.minLuminance,
1280 };
Yichi Chen54be23c2020-06-15 14:30:53 +08001281 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +08001282 hdr.smpte2086 = smpte2086_meta;
1283 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -07001284 // If the content light level fields are 0, do not use them, it
1285 // indicates the value may not be present in the stream.
1286 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
1287 struct android_cta861_3_metadata cta861_meta = {
1288 .maxContentLightLevel = hdrStaticInfo->maxCll,
1289 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
1290 };
1291 hdr.validTypes |= HdrMetadata::CTA861_3;
1292 hdr.cta8613 = cta861_meta;
1293 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +09001294
1295 // does not have valid info
1296 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
1297 hdrStaticInfo.reset();
1298 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001299 }
Wonsik Kima79c5522022-01-18 16:29:24 -08001300 if (hdrDynamicInfo
1301 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001302 hdr.validTypes |= HdrMetadata::HDR10PLUS;
1303 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -08001304 hdrDynamicInfo->m.data,
1305 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001306 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001307 qbi.setHdrMetadata(hdr);
1308 }
Hongguangfc1478a2022-07-20 22:56:06 -07001309 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
1310
Brian Lindahl932bf602023-03-09 11:59:48 -07001311 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
1312 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
1313 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001314 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
1315 if (result != OK) {
1316 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -08001317 if (result == NO_INIT) {
1318 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1319 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001320 return result;
1321 }
Josh Hou8eddf4b2021-02-02 16:26:53 +08001322
1323 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
1324 ALOGD("[%s] queue buffer successful", mName);
1325 } else {
1326 ALOGV("[%s] queue buffer successful", mName);
1327 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001328
1329 int64_t mediaTimeUs = 0;
1330 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahld7967a92023-08-10 10:12:49 -06001331 if (mAreRenderMetricsEnabled && mIsSurfaceToDisplay) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001332 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
1333 processRenderedFrames(qbo.frameTimestamps);
1334 } else {
1335 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
1336 // when the frame is queued to the non-display surface
1337 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1338 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001339
1340 return OK;
1341}
1342
Brian Lindahl932bf602023-03-09 11:59:48 -07001343void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001344 mTrackedFrames.clear();
1345
1346 int isSurfaceToDisplay = 0;
1347 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1348 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1349 // No frame tracking is needed if we're not sending frames to the display
1350 if (!mIsSurfaceToDisplay) {
1351 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1352 return;
1353 }
1354
Brian Lindahl932bf602023-03-09 11:59:48 -07001355 int hasPresentFenceTimes = 0;
1356 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1357 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
Brian Lindahl119e0c22023-05-19 15:42:13 -06001358 if (!mHasPresentFenceTimes) {
Brian Lindahl932bf602023-03-09 11:59:48 -07001359 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1360 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001361}
1362
1363void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1364 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1365 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1366 // so track the frame as if the desired render time is now.
1367 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1368 if (desiredRenderTimeNs < nowNs) {
1369 desiredRenderTimeNs = nowNs;
1370 }
Brian Lindahlc8bd9272023-08-28 09:42:43 -06001371
1372 // If the render time is more than a second from now, then pretend the frame is supposed to be
1373 // rendered immediately, because that's what SurfaceFlinger heuristics will do. This is a tight
1374 // coupling, but is really the only way to optimize away unnecessary present fence checks in
1375 // processRenderedFrames.
1376 if (desiredRenderTimeNs > nowNs + 1*1000*1000*1000LL) {
1377 desiredRenderTimeNs = nowNs;
1378 }
1379
Brian Lindahl932bf602023-03-09 11:59:48 -07001380 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1381 // actually rendered.
1382 TrackedFrame frame;
1383 frame.number = qbo.nextFrameNumber - 1;
1384 frame.mediaTimeUs = mediaTimeUs;
1385 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1386 frame.latchTime = -1;
1387 frame.presentFence = nullptr;
1388 mTrackedFrames.push_back(frame);
1389}
1390
1391void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1392 // Grab the latch times and present fences from the frame event deltas
1393 for (const auto& delta : deltas) {
1394 for (auto& frame : mTrackedFrames) {
1395 if (delta.getFrameNumber() == frame.number) {
1396 delta.getLatchTime(&frame.latchTime);
1397 delta.getDisplayPresentFence(&frame.presentFence);
1398 }
1399 }
1400 }
1401
1402 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1403 // in fact, been rendered.
1404 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1405 while (!mTrackedFrames.empty()) {
1406 TrackedFrame & frame = mTrackedFrames.front();
1407 // Frames that should have been rendered at least 100ms in the past are checked
1408 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1409 break;
1410 }
1411
1412 // If we don't have a render time by now, then consider the frame as dropped
1413 int64_t renderTimeNs = getRenderTimeNs(frame);
1414 if (renderTimeNs != -1) {
1415 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1416 }
1417 mTrackedFrames.pop_front();
1418 }
1419}
1420
1421int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1422 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1423 if (!mHasPresentFenceTimes) {
1424 if (frame.latchTime == -1) {
1425 ALOGD("no latch time for frame %d", (int) frame.number);
1426 return -1;
1427 }
1428 return frame.latchTime;
1429 }
1430
1431 if (frame.presentFence == nullptr) {
1432 ALOGW("no present fence for frame %d", (int) frame.number);
1433 return -1;
1434 }
1435
1436 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1437
1438 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1439 ALOGW("invalid signal time for frame %d", (int) frame.number);
1440 return -1;
1441 }
1442
1443 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1444 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1445 return -1;
1446 }
1447
1448 return actualRenderTimeNs;
1449}
1450
1451void CCodecBufferChannel::pollForRenderedBuffers() {
1452 FrameEventHistoryDelta delta;
1453 mComponent->pollForRenderedFrames(&delta);
1454 processRenderedFrames(delta);
1455}
1456
Sungtak Lee214ce612023-11-01 10:01:13 +00001457void CCodecBufferChannel::onBufferReleasedFromOutputSurface(uint32_t generation) {
Sungtak Lee6700cc92023-11-22 18:04:05 +00001458 // Note: Since this is called asynchronously from IProducerListener not
1459 // knowing the internal state of CCodec/CCodecBufferChannel,
1460 // prevent mComponent from being destroyed by holding the shared reference
1461 // during this interface being executed.
1462 std::shared_ptr<Codec2Client::Component> comp = mComponent;
1463 if (comp) {
1464 comp->onBufferReleasedFromOutputSurface(generation);
1465 }
Sungtak Lee214ce612023-11-01 10:01:13 +00001466}
1467
Pawin Vongmasa36653902018-11-15 00:10:25 -08001468status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1469 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1470 bool released = false;
1471 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001472 Mutexed<Input>::Locked input(mInput);
1473 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001474 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001475 }
1476 }
1477 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001478 Mutexed<Output>::Locked output(mOutput);
1479 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001480 released = true;
1481 }
1482 }
1483 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001484 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001485 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001486 } else {
1487 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1488 }
1489 return OK;
1490}
1491
1492void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1493 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001494 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001495
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001496 if (!input->buffers) {
1497 ALOGE("getInputBufferArray: No Input Buffers allocated");
1498 return;
1499 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001500 if (!input->buffers->isArrayMode()) {
1501 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001502 }
1503
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001504 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001505}
1506
1507void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1508 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001509 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001510 if (!output->buffers) {
1511 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1512 return;
1513 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001514 if (!output->buffers->isArrayMode()) {
1515 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001516 }
1517
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001518 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001519}
1520
1521status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001522 const sp<AMessage> &inputFormat,
1523 const sp<AMessage> &outputFormat,
1524 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001525 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1526 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001527 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001528 C2PortReorderBufferDepthTuning::output reorderDepth;
1529 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001530 C2PortActualDelayTuning::input inputDelay(0);
1531 C2PortActualDelayTuning::output outputDelay(0);
1532 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001533 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001534
Pawin Vongmasa36653902018-11-15 00:10:25 -08001535 c2_status_t err = mComponent->query(
1536 {
1537 &iStreamFormat,
1538 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001539 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001540 &reorderDepth,
1541 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001542 &inputDelay,
1543 &pipelineDelay,
1544 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001545 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001546 },
1547 {},
1548 C2_DONT_BLOCK,
1549 nullptr);
1550 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001551 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001552 return UNKNOWN_ERROR;
1553 }
1554 } else if (err != C2_OK) {
1555 return UNKNOWN_ERROR;
1556 }
1557
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001558 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1559 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1560 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1561
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001562 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1563 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001564
Pawin Vongmasa36653902018-11-15 00:10:25 -08001565 // TODO: get this from input format
1566 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1567
Sungtak Lee04b30352020-07-27 13:57:25 -07001568 // secure mode is a static parameter (shall not change in the executing state)
1569 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1570
Pawin Vongmasa36653902018-11-15 00:10:25 -08001571 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001572 int poolMask = GetCodec2PoolMask();
1573 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001574
1575 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001576 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001577 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001578 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1579 API_REFLECTION |
1580 API_VALUES |
1581 API_CURRENT_VALUES |
1582 API_DEPENDENCY |
1583 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001584 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1585 C2StreamSampleRateInfo::input sampleRate(0u);
1586 C2StreamChannelCountInfo::input channelCount(0u);
1587 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001588 std::shared_ptr<C2BlockPool> pool;
1589 {
1590 Mutexed<BlockPools>::Locked pools(mBlockPools);
1591
1592 // set default allocator ID.
1593 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001594 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001595
1596 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1597 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1598 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001599 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001600 std::vector<C2Param *> stackParams({&featuresSetting});
1601 if (audioEncoder) {
1602 stackParams.push_back(&encoderFrameSize);
1603 stackParams.push_back(&sampleRate);
1604 stackParams.push_back(&channelCount);
1605 stackParams.push_back(&pcmEncoding);
1606 } else {
1607 encoderFrameSize.invalidate();
1608 sampleRate.invalidate();
1609 channelCount.invalidate();
1610 pcmEncoding.invalidate();
1611 }
1612 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001613 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1614 C2_DONT_BLOCK,
1615 &params);
1616 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1617 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1618 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001619 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001620 C2PortAllocatorsTuning::input *inputAllocators =
1621 C2PortAllocatorsTuning::input::From(params[0].get());
1622 if (inputAllocators && inputAllocators->flexCount() > 0) {
1623 std::shared_ptr<C2Allocator> allocator;
1624 // verify allocator IDs and resolve default allocator
1625 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1626 if (allocator) {
1627 pools->inputAllocatorId = allocator->getId();
1628 } else {
1629 ALOGD("[%s] component requested invalid input allocator ID %u",
1630 mName, inputAllocators->m.values[0]);
1631 }
1632 }
1633 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001634 if (featuresSetting) {
1635 apiFeatures = featuresSetting.value;
1636 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001637
1638 // TODO: use C2Component wrapper to associate this pool with ourselves
1639 if ((poolMask >> pools->inputAllocatorId) & 1) {
1640 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1641 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1642 mName, pools->inputAllocatorId,
1643 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1644 asString(err), err);
1645 } else {
1646 err = C2_NOT_FOUND;
1647 }
1648 if (err != C2_OK) {
1649 C2BlockPool::local_id_t inputPoolId =
1650 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1651 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1652 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1653 mName, (unsigned long long)inputPoolId,
1654 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1655 asString(err), err);
1656 if (err != C2_OK) {
1657 return NO_MEMORY;
1658 }
1659 }
1660 pools->inputPool = pool;
1661 }
1662
Wonsik Kim51051262018-11-28 13:59:05 -08001663 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001664 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001665 input->inputDelay = inputDelayValue;
1666 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001667 input->numSlots = numInputSlots;
1668 input->extraBuffers.flush();
1669 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001670 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001671 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1672 input->frameReassembler.init(
1673 pool,
1674 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1675 encoderFrameSize.value,
1676 sampleRate.value,
1677 channelCount.value,
1678 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1679 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001680 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1681 // For encrypted content, framework decrypts source buffer (ashmem) into
1682 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001683 if (!buffersBoundToCodec
1684 && !input->frameReassembler
1685 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001686 input->buffers.reset(new SlotInputBuffers(mName));
1687 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001688 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001689 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001690 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001691 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001692 // This is to ensure buffers do not get released prematurely.
1693 // TODO: handle this without going into array mode
1694 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001695 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001696 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001697 }
1698 } else {
1699 if (hasCryptoOrDescrambler()) {
1700 int32_t capacity = kLinearBufferSize;
1701 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1702 if ((size_t)capacity > kMaxLinearBufferSize) {
1703 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1704 capacity = kMaxLinearBufferSize;
1705 }
1706 if (mDealer == nullptr) {
1707 mDealer = new MemoryDealer(
1708 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001709 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001710 "EncryptedLinearInputBuffers");
1711 mDecryptDestination = mDealer->allocate((size_t)capacity);
1712 }
1713 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001714 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1715 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001716 } else {
1717 mHeapSeqNum = -1;
1718 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001719 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001720 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001721 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001722 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001723 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001724 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001725 }
1726 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001727 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001728
1729 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001730 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001731 } else {
1732 // TODO: error
1733 }
Wonsik Kim51051262018-11-28 13:59:05 -08001734
1735 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001736 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001737 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001738 }
1739
1740 if (outputFormat != nullptr) {
1741 sp<IGraphicBufferProducer> outputSurface;
1742 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001743 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001744 {
1745 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001746 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001747 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001748 outputSurface = output->surface ?
1749 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001750 if (outputSurface) {
1751 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1752 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001753 outputGeneration = output->generation;
1754 }
1755
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001756 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001757 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001758 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001759
1760 {
1761 Mutexed<BlockPools>::Locked pools(mBlockPools);
1762
David Stevensc3fbb282021-01-18 18:11:20 +09001763 prevOutputPoolId = pools->outputPoolId;
1764
Pawin Vongmasa36653902018-11-15 00:10:25 -08001765 // set default allocator ID.
1766 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001767 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001768
1769 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1770 // unsuccessful.
1771 std::vector<std::unique_ptr<C2Param>> params;
1772 err = mComponent->query({ },
1773 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1774 C2_DONT_BLOCK,
1775 &params);
1776 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1777 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1778 mName, params.size(), asString(err), err);
1779 } else if (err == C2_OK && params.size() == 1) {
1780 C2PortAllocatorsTuning::output *outputAllocators =
1781 C2PortAllocatorsTuning::output::From(params[0].get());
1782 if (outputAllocators && outputAllocators->flexCount() > 0) {
1783 std::shared_ptr<C2Allocator> allocator;
1784 // verify allocator IDs and resolve default allocator
1785 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1786 if (allocator) {
1787 pools->outputAllocatorId = allocator->getId();
1788 } else {
1789 ALOGD("[%s] component requested invalid output allocator ID %u",
1790 mName, outputAllocators->m.values[0]);
1791 }
1792 }
1793 }
1794
1795 // use bufferqueue if outputting to a surface.
1796 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1797 // if unsuccessful.
1798 if (outputSurface) {
1799 params.clear();
1800 err = mComponent->query({ },
1801 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1802 C2_DONT_BLOCK,
1803 &params);
1804 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1805 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1806 mName, params.size(), asString(err), err);
1807 } else if (err == C2_OK && params.size() == 1) {
1808 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1809 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1810 if (surfaceAllocator) {
1811 std::shared_ptr<C2Allocator> allocator;
1812 // verify allocator IDs and resolve default allocator
1813 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1814 if (allocator) {
1815 pools->outputAllocatorId = allocator->getId();
1816 } else {
1817 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1818 mName, surfaceAllocator->value);
1819 err = C2_BAD_VALUE;
1820 }
1821 }
1822 }
1823 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1824 && err != C2_OK
1825 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1826 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1827 }
1828 }
1829
1830 if ((poolMask >> pools->outputAllocatorId) & 1) {
1831 err = mComponent->createBlockPool(
1832 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1833 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1834 mName, pools->outputAllocatorId,
1835 (unsigned long long)pools->outputPoolId,
1836 asString(err));
1837 } else {
1838 err = C2_NOT_FOUND;
1839 }
1840 if (err != C2_OK) {
1841 // use basic pool instead
1842 pools->outputPoolId =
1843 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1844 }
1845
1846 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1847 // component.
1848 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1849 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1850
1851 std::vector<std::unique_ptr<C2SettingResult>> failures;
1852 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1853 ALOGD("[%s] Configured output block pool ids %llu => %s",
1854 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1855 outputPoolId_ = pools->outputPoolId;
1856 }
1857
David Stevensc3fbb282021-01-18 18:11:20 +09001858 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1859 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1860 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1861 if (err != C2_OK) {
1862 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1863 (unsigned long long) prevOutputPoolId, asString(err), err);
1864 }
1865 }
1866
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001867 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001868 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001869 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001870 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001871 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001872 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001873 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001874 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001875 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001876 }
1877 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001878 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001879 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001880 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001881
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001882 output->buffers->clearStash();
1883 if (reorderDepth) {
1884 output->buffers->setReorderDepth(reorderDepth.value);
1885 }
1886 if (reorderKey) {
1887 output->buffers->setReorderKey(reorderKey.value);
1888 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001889
1890 // Try to set output surface to created block pool if given.
1891 if (outputSurface) {
1892 mComponent->setOutputSurface(
1893 outputPoolId_,
1894 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001895 outputGeneration,
1896 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001897 } else {
1898 // configure CPU read consumer usage
1899 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1900 std::vector<std::unique_ptr<C2SettingResult>> failures;
1901 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1902 // do not print error message for now as most components may not yet
1903 // support this setting
1904 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1905 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001906 }
1907
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001908 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001909 if (buffersBoundToCodec) {
1910 // WORKAROUND: if we're using early CSD workaround we convert to
1911 // array mode, to appease apps assuming the output
1912 // buffers to be of the same size.
1913 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1914 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001915
1916 int32_t channelCount;
1917 int32_t sampleRate;
1918 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1919 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1920 int32_t delay = 0;
1921 int32_t padding = 0;;
1922 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1923 delay = 0;
1924 }
1925 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1926 padding = 0;
1927 }
1928 if (delay || padding) {
Arun Johnson52d323e2024-01-05 21:16:56 +00001929 // We need write access to the buffers, so turn them into array mode.
1930 // TODO: b/321930152 - define SkipCutOutputBuffers that takes output from
1931 // component, runs it through SkipCutBuffer and allocate local buffer to be
1932 // used by fwk. Make initSkipCutBuffer() return OutputBuffers similar to
1933 // toArrayMode().
1934 if (!output->buffers->isArrayMode()) {
1935 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1936 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001937 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001938 }
1939 }
1940 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001941
1942 int32_t tunneled = 0;
1943 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1944 tunneled = 0;
1945 }
1946 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001947 }
1948
1949 // Set up pipeline control. This has to be done after mInputBuffers and
1950 // mOutputBuffers are initialized to make sure that lingering callbacks
1951 // about buffers from the previous generation do not interfere with the
1952 // newly initialized pipeline capacity.
1953
Wonsik Kim62545252021-01-20 11:25:41 -08001954 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001955 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001956 watcher->inputDelay(inputDelayValue)
1957 .pipelineDelay(pipelineDelayValue)
1958 .outputDelay(outputDelayValue)
Houxiang Dai0b573282023-03-11 18:31:56 +08001959 .smoothnessFactor(kSmoothnessFactor)
1960 .tunneled(mTunneled);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001961 watcher->flush();
1962 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001963
1964 mInputMetEos = false;
1965 mSync.start();
1966 return OK;
1967}
1968
Wonsik Kim34b28b42022-05-20 15:49:32 -07001969status_t CCodecBufferChannel::prepareInitialInputBuffers(
Arun Johnson326166e2023-07-28 19:11:52 +00001970 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers, bool retry) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001971 if (mInputSurface) {
1972 return OK;
1973 }
1974
Wonsik Kim34b28b42022-05-20 15:49:32 -07001975 size_t numInputSlots = mInput.lock()->numSlots;
Arun Johnson326166e2023-07-28 19:11:52 +00001976 int retryCount = 1;
1977 for (; clientInputBuffers->empty() && retryCount >= 0; retryCount--) {
1978 {
1979 Mutexed<Input>::Locked input(mInput);
1980 while (clientInputBuffers->size() < numInputSlots) {
1981 size_t index;
1982 sp<MediaCodecBuffer> buffer;
1983 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1984 break;
1985 }
1986 clientInputBuffers->emplace(index, buffer);
Wonsik Kim34b28b42022-05-20 15:49:32 -07001987 }
Arun Johnson326166e2023-07-28 19:11:52 +00001988 }
1989 if (!retry || (retryCount <= 0)) {
1990 break;
1991 }
1992 if (clientInputBuffers->empty()) {
1993 // wait: buffer may be in transit from component.
1994 std::this_thread::sleep_for(std::chrono::milliseconds(4));
Wonsik Kim34b28b42022-05-20 15:49:32 -07001995 }
1996 }
1997 if (clientInputBuffers->empty()) {
1998 ALOGW("[%s] start: cannot allocate memory at all", mName);
1999 return NO_MEMORY;
2000 } else if (clientInputBuffers->size() < numInputSlots) {
2001 ALOGD("[%s] start: cannot allocate memory for all slots, "
2002 "only %zu buffers allocated",
2003 mName, clientInputBuffers->size());
2004 } else {
2005 ALOGV("[%s] %zu initial input buffers available",
2006 mName, clientInputBuffers->size());
2007 }
2008 return OK;
2009}
2010
2011status_t CCodecBufferChannel::requestInitialInputBuffers(
2012 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002013 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07002014 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
2015 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
2016 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002017 return UNKNOWN_ERROR;
2018 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002019
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002020 std::list<std::unique_ptr<C2Work>> flushedConfigs;
2021 mFlushedConfigs.lock()->swap(flushedConfigs);
2022 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07002023 {
2024 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2025 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
2026 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
2027 watcher->onWorkQueued(
2028 work->input.ordinal.frameIndex.peeku(),
2029 std::vector(work->input.buffers),
2030 now);
2031 }
2032 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002033 err = mComponent->queue(&flushedConfigs);
2034 if (err != C2_OK) {
2035 ALOGW("[%s] Error while queueing a flushed config", mName);
2036 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002037 }
2038 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002039 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07002040 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
2041 !clientInputBuffers.empty()) {
2042 size_t minIndex = clientInputBuffers.begin()->first;
2043 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
2044 for (const auto &[index, buffer] : clientInputBuffers) {
2045 if (minBuffer->capacity() > buffer->capacity()) {
2046 minIndex = index;
2047 minBuffer = buffer;
2048 }
2049 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002050 // WORKAROUND: Some apps expect CSD available without queueing
2051 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07002052 minBuffer->setRange(0, 0);
2053 minBuffer->meta()->clear();
2054 minBuffer->meta()->setInt64("timeUs", 0);
2055 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002056 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
2057 mName);
2058 return UNKNOWN_ERROR;
2059 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07002060 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002061 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002062
Wonsik Kim34b28b42022-05-20 15:49:32 -07002063 for (const auto &[index, buffer] : clientInputBuffers) {
2064 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002065 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002066
Pawin Vongmasa36653902018-11-15 00:10:25 -08002067 return OK;
2068}
2069
2070void CCodecBufferChannel::stop() {
2071 mSync.stop();
2072 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302073 mInfoBuffers.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002074}
2075
Sungtak Lee99144332023-01-26 11:03:14 +00002076void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
2077 sp<Surface> surface = mOutputSurface.lock()->surface;
2078 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00002079 C2BlockPool::local_id_t outputPoolId;
2080 {
2081 Mutexed<BlockPools>::Locked pools(mBlockPools);
2082 outputPoolId = pools->outputPoolId;
2083 }
2084 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00002085
2086 if (pushBlankBuffer) {
2087 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
2088 if (anw) {
2089 pushBlankBuffersToNativeWindow(anw.get());
2090 }
2091 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00002092 }
2093}
2094
Wonsik Kim936a89c2020-05-08 16:07:50 -07002095void CCodecBufferChannel::reset() {
2096 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08002097 if (mInputSurface != nullptr) {
2098 mInputSurface.reset();
2099 }
2100 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002101 {
2102 Mutexed<Input>::Locked input(mInput);
2103 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002104 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002105 }
2106 {
2107 Mutexed<Output>::Locked output(mOutput);
2108 output->buffers.reset();
2109 }
Brian Lindahl932bf602023-03-09 11:59:48 -07002110 // reset the frames that are being tracked for onFrameRendered callbacks
2111 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002112}
2113
2114void CCodecBufferChannel::release() {
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302115 mInfoBuffers.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002116 mComponent.reset();
2117 mInputAllocator.reset();
2118 mOutputSurface.lock()->surface.clear();
2119 {
2120 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
2121 blockPools->inputPool.reset();
2122 blockPools->outputPoolIntf.reset();
2123 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002124 setCrypto(nullptr);
2125 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002126}
2127
Pawin Vongmasa36653902018-11-15 00:10:25 -08002128void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
2129 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002130 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002131 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07002132 {
2133 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2134 for (const std::unique_ptr<C2Work> &work : flushedWork) {
2135 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
2136 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
2137 watcher->onWorkDone(frameIndex);
2138 continue;
2139 }
2140 if (work->input.buffers.empty()
2141 || work->input.buffers.front() == nullptr
2142 || work->input.buffers.front()->data().linearBlocks().empty()) {
2143 ALOGD("[%s] no linear codec config data found", mName);
2144 watcher->onWorkDone(frameIndex);
2145 continue;
2146 }
2147 std::unique_ptr<C2Work> copy(new C2Work);
2148 copy->input.flags = C2FrameData::flags_t(
2149 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
2150 copy->input.ordinal = work->input.ordinal;
2151 copy->input.ordinal.frameIndex = mFrameIndex++;
2152 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
2153 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
2154 }
2155 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
2156 copy->input.configUpdate.push_back(C2Param::Copy(*param));
2157 }
2158 copy->input.infoBuffers.insert(
2159 copy->input.infoBuffers.begin(),
2160 work->input.infoBuffers.begin(),
2161 work->input.infoBuffers.end());
2162 copy->worklets.emplace_back(new C2Worklet);
2163 configs.push_back(std::move(copy));
2164 watcher->onWorkDone(frameIndex);
2165 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002166 }
2167 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002168 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002169 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002170 Mutexed<Input>::Locked input(mInput);
2171 input->buffers->flush();
2172 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002173 }
2174 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002175 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002176 if (output->buffers) {
2177 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002178 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002179 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002180 }
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302181 mInfoBuffers.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002182}
2183
2184void CCodecBufferChannel::onWorkDone(
2185 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002186 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002187 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002188 feedInputBufferIfAvailable();
2189 }
2190}
2191
2192void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08002193 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07002194 if (mInputSurface) {
2195 return;
2196 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002197 std::shared_ptr<C2Buffer> buffer =
2198 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002199 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002200 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002201 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002202 if (input->lastFlushIndex >= frameIndex) {
2203 ALOGD("[%s] Ignoring stale input buffer done callback: "
2204 "last flush index = %lld, frameIndex = %lld",
2205 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
2206 } else {
2207 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
2208 if (!newInputSlotAvailable) {
2209 (void)input->extraBuffers.expireComponentBuffer(buffer);
2210 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002211 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002212 }
2213 if (newInputSlotAvailable) {
2214 feedInputBufferIfAvailable();
2215 }
2216}
2217
2218bool CCodecBufferChannel::handleWork(
2219 std::unique_ptr<C2Work> work,
2220 const sp<AMessage> &outputFormat,
2221 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07002222 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00002223 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002224 if (!output->buffers) {
2225 return false;
2226 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08002227 }
2228
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002229 // Whether the output buffer should be reported to the client or not.
2230 bool notifyClient = false;
2231
2232 if (work->result == C2_OK){
2233 notifyClient = true;
2234 } else if (work->result == C2_NOT_FOUND) {
2235 ALOGD("[%s] flushed work; ignored.", mName);
2236 } else {
2237 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
2238 // the config update.
2239 ALOGD("[%s] work failed to complete: %d", mName, work->result);
2240 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
2241 return false;
2242 }
2243
2244 if ((work->input.ordinal.frameIndex -
2245 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002246 // Discard frames from previous generation.
2247 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002248 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002249 }
2250
Wonsik Kim524b0582019-03-12 11:28:57 -07002251 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08002252 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002253 || !(work->worklets.front()->output.flags &
2254 C2FrameData::FLAG_INCOMPLETE))) {
2255 mPipelineWatcher.lock()->onWorkDone(
2256 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002257 }
2258
2259 // NOTE: MediaCodec usage supposedly have only one worklet
2260 if (work->worklets.size() != 1u) {
2261 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
2262 mName, work->worklets.size());
2263 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2264 return false;
2265 }
2266
2267 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
2268
2269 std::shared_ptr<C2Buffer> buffer;
2270 // NOTE: MediaCodec usage supposedly have only one output stream.
2271 if (worklet->output.buffers.size() > 1u) {
2272 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
2273 mName, worklet->output.buffers.size());
2274 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2275 return false;
2276 } else if (worklet->output.buffers.size() == 1u) {
2277 buffer = worklet->output.buffers[0];
2278 if (!buffer) {
2279 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
2280 }
2281 }
2282
Wonsik Kim3dedf682021-05-03 10:57:09 -07002283 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
2284 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002285 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002286 while (!worklet->output.configUpdate.empty()) {
2287 std::unique_ptr<C2Param> param;
2288 worklet->output.configUpdate.back().swap(param);
2289 worklet->output.configUpdate.pop_back();
2290 switch (param->coreIndex().coreIndex()) {
2291 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
2292 C2PortReorderBufferDepthTuning::output reorderDepth;
2293 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002294 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
2295 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002296 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002297 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002298 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002299 ALOGD("[%s] onWorkDone: failed to read reorder depth",
2300 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002301 }
2302 break;
2303 }
2304 case C2PortReorderKeySetting::CORE_INDEX: {
2305 C2PortReorderKeySetting::output reorderKey;
2306 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07002307 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002308 ALOGV("[%s] onWorkDone: updated reorder key to %u",
2309 mName, reorderKey.value);
2310 } else {
2311 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
2312 }
2313 break;
2314 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002315 case C2PortActualDelayTuning::CORE_INDEX: {
2316 if (param->isGlobal()) {
2317 C2ActualPipelineDelayTuning pipelineDelay;
2318 if (pipelineDelay.updateFrom(*param)) {
2319 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
2320 mName, pipelineDelay.value);
2321 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002322 (void)mPipelineWatcher.lock()->pipelineDelay(
2323 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002324 }
2325 }
2326 if (param->forInput()) {
2327 C2PortActualDelayTuning::input inputDelay;
2328 if (inputDelay.updateFrom(*param)) {
2329 ALOGV("[%s] onWorkDone: updating input delay %u",
2330 mName, inputDelay.value);
2331 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002332 (void)mPipelineWatcher.lock()->inputDelay(
2333 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002334 }
2335 }
2336 if (param->forOutput()) {
2337 C2PortActualDelayTuning::output outputDelay;
2338 if (outputDelay.updateFrom(*param)) {
2339 ALOGV("[%s] onWorkDone: updating output delay %u",
2340 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002341 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002342 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002343 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002344
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002345 }
2346 }
2347 break;
2348 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08002349 case C2PortTunnelSystemTime::CORE_INDEX: {
2350 C2PortTunnelSystemTime::output frameRenderTime;
2351 if (frameRenderTime.updateFrom(*param)) {
2352 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
2353 mName, (long long)frameRenderTime.value,
2354 (long long)worklet->output.ordinal.timestamp.peekll());
2355 mCCodecCallback->onOutputFramesRendered(
2356 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
2357 }
2358 break;
2359 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02002360 case C2StreamTunnelHoldRender::CORE_INDEX: {
2361 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
2362 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
2363 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
2364 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
2365 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
2366 mCCodecCallback->onFirstTunnelFrameReady();
2367 break;
2368 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002369 default:
2370 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2371 mName, param->index());
2372 break;
2373 }
2374 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002375 if (newInputDelay || newPipelineDelay) {
2376 Mutexed<Input>::Locked input(mInput);
2377 size_t newNumSlots =
2378 newInputDelay.value_or(input->inputDelay) +
2379 newPipelineDelay.value_or(input->pipelineDelay) +
2380 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08002381 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002382 if (input->buffers->isArrayMode()) {
2383 if (input->numSlots >= newNumSlots) {
2384 input->numExtraSlots = 0;
2385 } else {
2386 input->numExtraSlots = newNumSlots - input->numSlots;
2387 }
2388 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2389 mName, input->numExtraSlots);
2390 } else {
2391 input->numSlots = newNumSlots;
2392 }
2393 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002394 size_t numOutputSlots = 0;
2395 uint32_t reorderDepth = 0;
2396 bool outputBuffersChanged = false;
2397 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2398 Mutexed<Output>::Locked output(mOutput);
2399 if (!output->buffers) {
2400 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002401 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002402 numOutputSlots = output->numSlots;
2403 if (newReorderKey) {
2404 output->buffers->setReorderKey(newReorderKey.value());
2405 }
2406 if (newReorderDepth) {
2407 output->buffers->setReorderDepth(newReorderDepth.value());
2408 }
2409 reorderDepth = output->buffers->getReorderDepth();
2410 if (newOutputDelay) {
2411 output->outputDelay = newOutputDelay.value();
2412 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2413 if (output->numSlots < numOutputSlots) {
2414 output->numSlots = numOutputSlots;
2415 if (output->buffers->isArrayMode()) {
2416 OutputBuffersArray *array =
2417 (OutputBuffersArray *)output->buffers.get();
2418 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2419 mName, numOutputSlots);
2420 array->grow(numOutputSlots);
2421 outputBuffersChanged = true;
2422 }
2423 }
2424 }
2425 numOutputSlots = output->numSlots;
2426 }
2427 if (outputBuffersChanged) {
2428 mCCodecCallback->onOutputBuffersChanged();
2429 }
2430 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002431 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002432 {
2433 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2434 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002435 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002436 if (output->surface) {
2437 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2438 }
2439 }
2440 if (maxDequeueCount > 0) {
2441 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002442 }
2443 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002444
Pawin Vongmasa36653902018-11-15 00:10:25 -08002445 int32_t flags = 0;
2446 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002447 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002448 ALOGV("[%s] onWorkDone: output EOS", mName);
2449 }
2450
Pawin Vongmasa36653902018-11-15 00:10:25 -08002451 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2452 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2453 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2454 // shall correspond to the client input timesamp (in customOrdinal). By using the
2455 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2456 // produces multiple output.
2457 c2_cntr64_t timestamp =
2458 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2459 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002460 if (mInputSurface != nullptr) {
2461 // When using input surface we need to restore the original input timestamp.
2462 timestamp = work->input.ordinal.customOrdinal;
2463 }
My Name6bd9a7d2022-03-25 12:37:58 -07002464 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2465 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002466 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2467 mName,
2468 work->input.ordinal.customOrdinal.peekll(),
2469 work->input.ordinal.timestamp.peekll(),
2470 worklet->output.ordinal.timestamp.peekll(),
2471 timestamp.peekll());
2472
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002473 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002474 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002475 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002476 if (!output->buffers) {
2477 return false;
2478 }
2479 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002480 output->buffers->updateSkipCutBuffer(outputFormat);
2481 output->buffers->setFormat(outputFormat);
2482 }
2483 if (!notifyClient) {
2484 return false;
2485 }
2486 size_t index;
2487 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002488 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002489 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002490 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002491 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2492
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002493 // TRICKY: we want popped buffers reported in order, so sending
2494 // the callback while holding the lock here. This assumes that
2495 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2496 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002497 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002498 } else {
2499 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002500 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002501 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002502 return false;
2503 }
2504 }
2505
Wonsik Kimec585c32021-10-01 01:11:00 -07002506 bool drop = false;
2507 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2508 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2509 drop = true;
2510 }
2511
Marc Kassisec910342022-11-25 11:43:05 +01002512 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2513 // HAL, the flag is then removed in the corresponding output buffer.
2514 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2515 flags |= BUFFER_FLAG_DECODE_ONLY;
2516 }
2517
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002518 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002519 if (mTunneled && drop && outputFormat) {
Houxiang Daie74e5062022-05-19 15:32:54 +08002520 if (mOutputFormat != outputFormat) {
2521 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2522 mName, work->input.ordinal.frameIndex.peekull());
2523 mOutputFormat = outputFormat;
2524 } else {
2525 ALOGV("[%s] onWorkDone: Not reporting output buffer without format change (%lld)",
2526 mName, work->input.ordinal.frameIndex.peekull());
2527 notifyClient = false;
2528 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002529 } else {
2530 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2531 mName, work->input.ordinal.frameIndex.peekull());
2532 notifyClient = false;
2533 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002534 }
2535
2536 if (buffer) {
2537 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2538 // TODO: properly translate these to metadata
2539 switch (info->coreIndex().coreIndex()) {
2540 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002541 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002542 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002543 }
2544 break;
2545 default:
2546 break;
2547 }
2548 }
2549 }
2550
2551 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002552 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002553 if (!output->buffers) {
2554 return false;
2555 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002556 output->buffers->pushToStash(
2557 buffer,
2558 notifyClient,
2559 timestamp.peek(),
2560 flags,
2561 outputFormat,
2562 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002563 }
2564 sendOutputBuffers();
2565 return true;
2566}
2567
2568void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002569 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002570 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002571 sp<MediaCodecBuffer> outBuffer;
2572 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002573
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002574 constexpr int kMaxReallocTry = 5;
2575 int reallocTryNum = 0;
2576
Pawin Vongmasa36653902018-11-15 00:10:25 -08002577 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002578 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002579 if (!output->buffers) {
2580 return;
2581 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002582 action = output->buffers->popFromStashAndRegister(
2583 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002584 if (action != OutputBuffers::REALLOCATE) {
2585 reallocTryNum = 0;
2586 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002587 switch (action) {
2588 case OutputBuffers::SKIP:
2589 return;
2590 case OutputBuffers::DISCARD:
2591 break;
2592 case OutputBuffers::NOTIFY_CLIENT:
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002593 {
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002594 // TRICKY: we want popped buffers reported in order, so sending
2595 // the callback while holding the lock here. This assumes that
2596 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2597 // callbacks are always sent with the Output lock held.
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002598 if (c2Buffer) {
2599 std::shared_ptr<const C2AccessUnitInfos::output> bufferMetadata =
2600 std::static_pointer_cast<const C2AccessUnitInfos::output>(
2601 c2Buffer->getInfo(C2AccessUnitInfos::output::PARAM_TYPE));
2602 if (bufferMetadata && bufferMetadata->flexCount() > 0) {
2603 uint32_t flag = 0;
2604 std::vector<AccessUnitInfo> accessUnitInfos;
2605 for (int nMeta = 0; nMeta < bufferMetadata->flexCount(); nMeta++) {
2606 const C2AccessUnitInfosStruct &bufferMetadataStruct =
2607 bufferMetadata->m.values[nMeta];
2608 flag = convertFlags(bufferMetadataStruct.flags, false);
2609 accessUnitInfos.emplace_back(flag,
2610 static_cast<size_t>(bufferMetadataStruct.size),
2611 static_cast<size_t>(bufferMetadataStruct.timestamp));
2612 }
2613 sp<WrapperObject<std::vector<AccessUnitInfo>>> obj{
2614 new WrapperObject<std::vector<AccessUnitInfo>>{accessUnitInfos}};
2615 outBuffer->meta()->setObject("accessUnitInfo", obj);
2616 }
2617 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002618 mCallback->onOutputBufferAvailable(index, outBuffer);
2619 break;
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002620 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002621 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002622 if (++reallocTryNum > kMaxReallocTry) {
2623 output.unlock();
2624 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2625 mName, kMaxReallocTry);
2626 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2627 return;
2628 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002629 if (!output->buffers->isArrayMode()) {
2630 output->buffers =
2631 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002632 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002633 static_cast<OutputBuffersArray*>(output->buffers.get())->
2634 realloc(c2Buffer);
2635 output.unlock();
2636 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002637 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002638 case OutputBuffers::RETRY:
2639 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2640 mName);
2641 return;
2642 default:
2643 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2644 "corrupted BufferAction value (%d) "
2645 "returned from popFromStashAndRegister.",
2646 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002647 return;
2648 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002649 }
2650}
2651
Sungtak Lee214ce612023-11-01 10:01:13 +00002652status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface,
2653 uint32_t generation, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002654 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002655 int maxDequeueCount;
2656 sp<Surface> oldSurface;
2657 {
2658 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2659 maxDequeueCount = outputSurface->maxDequeueBuffers;
2660 oldSurface = outputSurface->surface;
2661 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002662 if (newSurface) {
2663 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002664 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002665 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002666 producer = newSurface->getIGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002667 } else {
2668 ALOGE("[%s] setting output surface to null", mName);
2669 return INVALID_OPERATION;
2670 }
2671
2672 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2673 C2BlockPool::local_id_t outputPoolId;
2674 {
2675 Mutexed<BlockPools>::Locked pools(mBlockPools);
2676 outputPoolId = pools->outputPoolId;
2677 outputPoolIntf = pools->outputPoolIntf;
2678 }
2679
2680 if (outputPoolIntf) {
2681 if (mComponent->setOutputSurface(
2682 outputPoolId,
2683 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002684 generation,
2685 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002686 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2687 return INVALID_OPERATION;
2688 }
2689 }
2690
2691 {
2692 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2693 output->surface = newSurface;
2694 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002695 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002696 }
2697
Sungtak Lee99144332023-01-26 11:03:14 +00002698 if (oldSurface && pushBlankBuffer) {
2699 // When ReleaseSurface was set from MediaCodec,
2700 // pushing a blank buffer at the end might be necessary.
2701 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2702 if (anw) {
2703 pushBlankBuffersToNativeWindow(anw.get());
2704 }
2705 }
2706
Pawin Vongmasa36653902018-11-15 00:10:25 -08002707 return OK;
2708}
2709
Wonsik Kimab34ed62019-01-31 15:28:46 -08002710PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002711 // Otherwise, component may have stalled work due to input starvation up to
2712 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002713 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2714 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002715 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002716 size_t outputDelay = mOutput.lock()->outputDelay;
2717 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002718 Mutexed<Input>::Locked input(mInput);
2719 n = input->inputDelay + input->pipelineDelay + outputDelay;
2720 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002721 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002722}
2723
Pawin Vongmasa36653902018-11-15 00:10:25 -08002724void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2725 mMetaMode = mode;
2726}
2727
Wonsik Kim596187e2019-10-25 12:44:10 -07002728void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002729 if (mCrypto != nullptr) {
2730 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2731 mCrypto->unsetHeap(entry.second);
2732 }
2733 mHeapSeqNumMap.clear();
2734 if (mHeapSeqNum >= 0) {
2735 mCrypto->unsetHeap(mHeapSeqNum);
2736 mHeapSeqNum = -1;
2737 }
2738 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002739 mCrypto = crypto;
2740}
2741
2742void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2743 mDescrambler = descrambler;
2744}
2745
Songyue Han1e6769b2023-08-30 18:09:27 +00002746uint32_t CCodecBufferChannel::getBuffersPixelFormat(bool isEncoder) {
2747 if (isEncoder) {
2748 return getInputBuffersPixelFormat();
2749 } else {
2750 return getOutputBuffersPixelFormat();
2751 }
2752}
2753
2754uint32_t CCodecBufferChannel::getInputBuffersPixelFormat() {
2755 Mutexed<Input>::Locked input(mInput);
2756 if (input->buffers == nullptr) {
2757 return PIXEL_FORMAT_UNKNOWN;
2758 }
2759 return input->buffers->getPixelFormatIfApplicable();
2760}
2761
2762uint32_t CCodecBufferChannel::getOutputBuffersPixelFormat() {
2763 Mutexed<Output>::Locked output(mOutput);
2764 if (output->buffers == nullptr) {
2765 return PIXEL_FORMAT_UNKNOWN;
2766 }
2767 return output->buffers->getPixelFormatIfApplicable();
2768}
2769
2770void CCodecBufferChannel::resetBuffersPixelFormat(bool isEncoder) {
2771 if (isEncoder) {
2772 Mutexed<Input>::Locked input(mInput);
2773 if (input->buffers == nullptr) {
2774 return;
2775 }
2776 input->buffers->resetPixelFormatIfApplicable();
2777 } else {
2778 Mutexed<Output>::Locked output(mOutput);
2779 if (output->buffers == nullptr) {
2780 return;
2781 }
2782 output->buffers->resetPixelFormatIfApplicable();
2783 }
2784}
2785
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302786void CCodecBufferChannel::setInfoBuffer(const std::shared_ptr<C2InfoBuffer> &buffer) {
Harish Mahendrakar2b095d92024-05-13 16:51:15 -07002787 if (mInputSurface == nullptr) {
2788 mInfoBuffers.push_back(buffer);
2789 } else {
2790 std::list<std::unique_ptr<C2Work>> items;
2791 std::unique_ptr<C2Work> work(new C2Work);
2792 work->input.infoBuffers.emplace_back(*buffer);
2793 work->worklets.emplace_back(new C2Worklet);
2794 items.push_back(std::move(work));
2795 c2_status_t err = mComponent->queue(&items);
2796 }
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302797}
2798
Pawin Vongmasa36653902018-11-15 00:10:25 -08002799status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2800 // C2_OK is always translated to OK.
2801 if (c2s == C2_OK) {
2802 return OK;
2803 }
2804
2805 // Operation-dependent translation
2806 // TODO: Add as necessary
2807 switch (c2op) {
2808 case C2_OPERATION_Component_start:
2809 switch (c2s) {
2810 case C2_NO_MEMORY:
2811 return NO_MEMORY;
2812 default:
2813 return UNKNOWN_ERROR;
2814 }
2815 default:
2816 break;
2817 }
2818
2819 // Backup operation-agnostic translation
2820 switch (c2s) {
2821 case C2_BAD_INDEX:
2822 return BAD_INDEX;
2823 case C2_BAD_VALUE:
2824 return BAD_VALUE;
2825 case C2_BLOCKING:
2826 return WOULD_BLOCK;
2827 case C2_DUPLICATE:
2828 return ALREADY_EXISTS;
2829 case C2_NO_INIT:
2830 return NO_INIT;
2831 case C2_NO_MEMORY:
2832 return NO_MEMORY;
2833 case C2_NOT_FOUND:
2834 return NAME_NOT_FOUND;
2835 case C2_TIMED_OUT:
2836 return TIMED_OUT;
2837 case C2_BAD_STATE:
2838 case C2_CANCELED:
2839 case C2_CANNOT_DO:
2840 case C2_CORRUPTED:
2841 case C2_OMITTED:
2842 case C2_REFUSED:
2843 return UNKNOWN_ERROR;
2844 default:
2845 return -static_cast<status_t>(c2s);
2846 }
2847}
2848
Pawin Vongmasa36653902018-11-15 00:10:25 -08002849} // namespace android