blob: 0db3eec7df9470c68eadb6b4a0f3df02524c04a3 [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>
28
29#include <C2AllocatorGralloc.h>
30#include <C2PlatformSupport.h>
31#include <C2BlockInternal.h>
32#include <C2Config.h>
33#include <C2Debug.h>
34
35#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070036#include <android/hardware/drm/1.0/types.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070037#include <android-base/parseint.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080038#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080039#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080040#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080041#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070042#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080043#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070044#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080045#include <media/openmax/OMX_Core.h>
46#include <media/stagefright/foundation/ABuffer.h>
47#include <media/stagefright/foundation/ALookup.h>
48#include <media/stagefright/foundation/AMessage.h>
49#include <media/stagefright/foundation/AUtils.h>
50#include <media/stagefright/foundation/hexdump.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080051#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070052#include <media/stagefright/SkipCutBuffer.h>
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010053#include <media/stagefright/SurfaceUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080054#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070055#include <mediadrm/ICrypto.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070056#include <server_configurable_flags/get_flags.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080057#include <system/window.h>
58
59#include "CCodecBufferChannel.h"
60#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080061
62namespace android {
63
64using android::base::StringPrintf;
65using hardware::hidl_handle;
66using hardware::hidl_string;
67using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070068using hardware::fromHeap;
69using hardware::HidlMemory;
Brian Lindahl83931482023-08-10 10:12:49 -060070using server_configurable_flags::GetServerConfigurableFlag;
Robert Shih895fba92019-07-16 16:29:44 -070071
Pawin Vongmasa36653902018-11-15 00:10:25 -080072using namespace hardware::cas::V1_0;
73using namespace hardware::cas::native::V1_0;
74
75using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070076using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080077
Pawin Vongmasa36653902018-11-15 00:10:25 -080078namespace {
79
Wonsik Kim469c8342019-04-11 16:46:09 -070080constexpr size_t kSmoothnessFactor = 4;
Pawin Vongmasa36653902018-11-15 00:10:25 -080081
Sungtak Leeab6f2f32019-02-15 14:43:51 -080082// This is for keeping IGBP's buffer dropping logic in legacy mode other
83// than making it non-blocking. Do not change this value.
84const static size_t kDequeueTimeoutNs = 0;
85
Brian Lindahl83931482023-08-10 10:12:49 -060086static bool areRenderMetricsEnabled() {
87 std::string v = GetServerConfigurableFlag("media_native", "render_metrics_enabled", "false");
88 return v == "true";
89}
90
Pawin Vongmasa36653902018-11-15 00:10:25 -080091} // namespace
92
93CCodecBufferChannel::QueueGuard::QueueGuard(
94 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
95 Mutex::Autolock l(mSync.mGuardLock);
96 // At this point it's guaranteed that mSync is not under state transition,
97 // as we are holding its mutex.
98
99 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
100 if (count->value == -1) {
101 mRunning = false;
102 } else {
103 ++count->value;
104 mRunning = true;
105 }
106}
107
108CCodecBufferChannel::QueueGuard::~QueueGuard() {
109 if (mRunning) {
110 // We are not holding mGuardLock at this point so that QueueSync::stop() can
111 // keep holding the lock until mCount reaches zero.
112 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
113 --count->value;
114 count->cond.broadcast();
115 }
116}
117
118void CCodecBufferChannel::QueueSync::start() {
119 Mutex::Autolock l(mGuardLock);
120 // If stopped, it goes to running state; otherwise no-op.
121 Mutexed<Counter>::Locked count(mCount);
122 if (count->value == -1) {
123 count->value = 0;
124 }
125}
126
127void CCodecBufferChannel::QueueSync::stop() {
128 Mutex::Autolock l(mGuardLock);
129 Mutexed<Counter>::Locked count(mCount);
130 if (count->value == -1) {
131 // no-op
132 return;
133 }
134 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
135 // mCount can only decrement. In other words, threads that acquired the lock
136 // are allowed to finish execution but additional threads trying to acquire
137 // the lock at this point will block, and then get QueueGuard at STOPPED
138 // state.
139 while (count->value != 0) {
140 count.waitForCondition(count->cond);
141 }
142 count->value = -1;
143}
144
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700145// Input
146
147CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
148
Pawin Vongmasa36653902018-11-15 00:10:25 -0800149// CCodecBufferChannel
150
151CCodecBufferChannel::CCodecBufferChannel(
152 const std::shared_ptr<CCodecCallback> &callback)
153 : mHeapSeqNum(-1),
154 mCCodecCallback(callback),
155 mFrameIndex(0u),
156 mFirstValidFrameIndex(0u),
Brian Lindahl83931482023-08-10 10:12:49 -0600157 mAreRenderMetricsEnabled(areRenderMetricsEnabled()),
Brian Lindahl2048d492023-04-05 08:49:23 -0600158 mIsSurfaceToDisplay(false),
159 mHasPresentFenceTimes(false),
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700160 mRenderingDepth(3u),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800161 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700162 mInputMetEos(false),
163 mSendEncryptedInfoBuffer(false) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700164 {
165 Mutexed<Input>::Locked input(mInput);
166 input->buffers.reset(new DummyInputBuffers(""));
167 input->extraBuffers.flush();
168 input->inputDelay = 0u;
169 input->pipelineDelay = 0u;
170 input->numSlots = kSmoothnessFactor;
171 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700172 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700173 }
174 {
175 Mutexed<Output>::Locked output(mOutput);
176 output->outputDelay = 0u;
177 output->numSlots = kSmoothnessFactor;
Wonsik Kim3722abc2023-05-17 13:26:31 -0700178 output->bounded = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700179 }
David Stevensc3fbb282021-01-18 18:11:20 +0900180 {
181 Mutexed<BlockPools>::Locked pools(mBlockPools);
182 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
183 }
Brian Lindahl83931482023-08-10 10:12:49 -0600184 std::string value = GetServerConfigurableFlag("media_native", "ccodec_rendering_depth", "3");
Wonsik Kim3a692e62023-05-19 15:37:22 -0700185 android::base::ParseInt(value, &mRenderingDepth);
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700186 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800187}
188
189CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800190 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800191 mCrypto->unsetHeap(mHeapSeqNum);
192 }
193}
194
195void CCodecBufferChannel::setComponent(
196 const std::shared_ptr<Codec2Client::Component> &component) {
197 mComponent = component;
198 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
199 mName = mComponentName.c_str();
200}
201
202status_t CCodecBufferChannel::setInputSurface(
203 const std::shared_ptr<InputSurfaceWrapper> &surface) {
204 ALOGV("[%s] setInputSurface", mName);
205 mInputSurface = surface;
206 return mInputSurface->connect(mComponent);
207}
208
209status_t CCodecBufferChannel::signalEndOfInputStream() {
210 if (mInputSurface == nullptr) {
211 return INVALID_OPERATION;
212 }
213 return mInputSurface->signalEndOfInputStream();
214}
215
Sungtak Lee04b30352020-07-27 13:57:25 -0700216status_t CCodecBufferChannel::queueInputBufferInternal(
217 sp<MediaCodecBuffer> buffer,
218 std::shared_ptr<C2LinearBlock> encryptedBlock,
219 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800220 int64_t timeUs;
221 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
222
223 if (mInputMetEos) {
224 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
225 return OK;
226 }
227
228 int32_t flags = 0;
229 int32_t tmp = 0;
230 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200231 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800232 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
233 eos = true;
234 mInputMetEos = true;
235 ALOGV("[%s] input EOS", mName);
236 }
237 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
238 flags |= C2FrameData::FLAG_CODEC_CONFIG;
239 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200240 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
241 tunnelFirstFrame = true;
242 }
Marc Kassis96343b42022-12-09 11:49:44 +0100243 if (buffer->meta()->findInt32("decode-only", &tmp) && tmp) {
244 flags |= C2FrameData::FLAG_DROP_FRAME;
245 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800246 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800247 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800248 std::unique_ptr<C2Work> work(new C2Work);
249 work->input.ordinal.timestamp = timeUs;
250 work->input.ordinal.frameIndex = mFrameIndex++;
251 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
252 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
253 // Keep client timestamp in customOrdinal
254 work->input.ordinal.customOrdinal = timeUs;
255 work->input.buffers.clear();
256
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700257 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800258 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800259
Pawin Vongmasa36653902018-11-15 00:10:25 -0800260 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700261 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800262 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700263 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800264 return -ENOENT;
265 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700266 // TODO: we want to delay copying buffers.
267 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
268 copy = input->buffers->cloneAndReleaseBuffer(buffer);
269 if (copy != nullptr) {
270 (void)input->extraBuffers.assignSlot(copy);
271 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
272 return UNKNOWN_ERROR;
273 }
274 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
275 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
276 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700277 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700278 } else {
279 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
280 "buffer starvation on component.", mName);
281 }
282 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800283 if (input->frameReassembler) {
284 usesFrameReassembler = true;
285 input->frameReassembler.process(buffer, &items);
286 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900287 int32_t cvo = 0;
288 if (buffer->meta()->findInt32("cvo", &cvo)) {
289 int32_t rotation = cvo % 360;
290 // change rotation to counter-clock wise.
291 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
292
293 Mutexed<OutputSurface>::Locked output(mOutputSurface);
294 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
295 output->rotation[frameIndex] = rotation;
296 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800297 work->input.buffers.push_back(c2buffer);
298 if (encryptedBlock) {
299 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
300 kParamIndexEncryptedBuffer,
301 encryptedBlock->share(0, blockSize, C2Fence())));
302 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700303 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800304 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700305 Mutexed<Input>::Locked input(mInput);
306 if (input->frameReassembler) {
307 usesFrameReassembler = true;
308 // drain any pending items with eos
309 input->frameReassembler.process(buffer, &items);
310 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800311 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800312 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800313 if (usesFrameReassembler) {
314 if (!items.empty()) {
315 items.front()->input.configUpdate = std::move(mParamsToBeSet);
316 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
317 }
318 } else {
319 work->input.flags = (C2FrameData::flags_t)flags;
320 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800321
Wonsik Kime1104ca2020-11-24 15:01:33 -0800322 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200323 if (tunnelFirstFrame) {
324 C2StreamTunnelHoldRender::input tunnelHoldRender{
325 0u /* stream */,
326 C2_TRUE /* value */
327 };
328 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
329 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800330 work->worklets.clear();
331 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800332
Wonsik Kime1104ca2020-11-24 15:01:33 -0800333 items.push_back(std::move(work));
334
335 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800336 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800337 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800338 work.reset(new C2Work);
339 work->input.ordinal.timestamp = timeUs;
340 work->input.ordinal.frameIndex = mFrameIndex++;
341 // WORKAROUND: keep client timestamp in customOrdinal
342 work->input.ordinal.customOrdinal = timeUs;
343 work->input.buffers.clear();
344 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800345 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800346 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800347 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800348 c2_status_t err = C2_OK;
349 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700350 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
351 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800352 {
353 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
354 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
355 for (const std::unique_ptr<C2Work> &work : items) {
356 watcher->onWorkQueued(
357 work->input.ordinal.frameIndex.peeku(),
358 std::vector(work->input.buffers),
359 now);
360 }
361 }
362 err = mComponent->queue(&items);
363 }
364 if (err != C2_OK) {
365 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
366 for (const std::unique_ptr<C2Work> &work : items) {
367 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
368 }
369 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700370 Mutexed<Input>::Locked input(mInput);
371 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700372 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700373 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700374 } else if (buffer) {
375 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700376 }
377 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
378 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800379 }
380
381 feedInputBufferIfAvailableInternal();
382 return err;
383}
384
385status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
386 QueueGuard guard(mSync);
387 if (!guard.isRunning()) {
388 ALOGD("[%s] setParameters is only supported in the running state.", mName);
389 return -ENOSYS;
390 }
391 mParamsToBeSet.insert(mParamsToBeSet.end(),
392 std::make_move_iterator(params.begin()),
393 std::make_move_iterator(params.end()));
394 params.clear();
395 return OK;
396}
397
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800398status_t CCodecBufferChannel::attachBuffer(
399 const std::shared_ptr<C2Buffer> &c2Buffer,
400 const sp<MediaCodecBuffer> &buffer) {
401 if (!buffer->copy(c2Buffer)) {
402 return -ENOSYS;
403 }
404 return OK;
405}
406
407void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
408 if (!mDecryptDestination || mDecryptDestination->size() < size) {
409 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
410 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
411 mCrypto->unsetHeap(mHeapSeqNum);
412 }
413 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
414 if (mCrypto) {
415 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
416 }
417 }
418}
419
420int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
421 CHECK(mCrypto);
422 auto it = mHeapSeqNumMap.find(memory);
423 int32_t heapSeqNum = -1;
424 if (it == mHeapSeqNumMap.end()) {
425 heapSeqNum = mCrypto->setHeap(memory);
426 mHeapSeqNumMap.emplace(memory, heapSeqNum);
427 } else {
428 heapSeqNum = it->second;
429 }
430 return heapSeqNum;
431}
432
433status_t CCodecBufferChannel::attachEncryptedBuffer(
434 const sp<hardware::HidlMemory> &memory,
435 bool secure,
436 const uint8_t *key,
437 const uint8_t *iv,
438 CryptoPlugin::Mode mode,
439 CryptoPlugin::Pattern pattern,
440 size_t offset,
441 const CryptoPlugin::SubSample *subSamples,
442 size_t numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000443 const sp<MediaCodecBuffer> &buffer,
444 AString* errorDetailMsg) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800445 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
446 static const C2MemoryUsage kDefaultReadWriteUsage{
447 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
448
449 size_t size = 0;
450 for (size_t i = 0; i < numSubSamples; ++i) {
451 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
452 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700453 if (size == 0) {
454 buffer->setRange(0, 0);
455 return OK;
456 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800457 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
458 std::shared_ptr<C2LinearBlock> block;
459 c2_status_t err = pool->fetchLinearBlock(
460 size,
461 secure ? kSecureUsage : kDefaultReadWriteUsage,
462 &block);
463 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700464 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
465 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800466 return NO_MEMORY;
467 }
468 if (!secure) {
469 ensureDecryptDestination(size);
470 }
471 ssize_t result = -1;
472 ssize_t codecDataOffset = 0;
473 if (mCrypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800474 int32_t heapSeqNum = getHeapSeqNum(memory);
475 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
476 hardware::drm::V1_0::DestinationBuffer dst;
477 if (secure) {
478 dst.type = DrmBufferType::NATIVE_HANDLE;
479 dst.secureMemory = hardware::hidl_handle(block->handle());
480 } else {
481 dst.type = DrmBufferType::SHARED_MEMORY;
482 IMemoryToSharedBuffer(
483 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
484 }
485 result = mCrypto->decrypt(
486 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000487 dst, errorDetailMsg);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800488 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700489 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800490 return result;
491 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800492 } else {
493 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
494 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
495 hidl_vec<SubSample> hidlSubSamples;
496 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
497
498 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
499 hardware::cas::native::V1_0::DestinationBuffer dst;
500 if (secure) {
501 dst.type = BufferType::NATIVE_HANDLE;
502 dst.secureMemory = hardware::hidl_handle(block->handle());
503 } else {
504 dst.type = BufferType::SHARED_MEMORY;
505 dst.nonsecureMemory = src;
506 }
507
508 CasStatus status = CasStatus::OK;
509 hidl_string detailedError;
510 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
511
512 if (key != nullptr) {
513 sctrl = (ScramblingControl)key[0];
514 // Adjust for the PES offset
515 codecDataOffset = key[2] | (key[3] << 8);
516 }
517
518 auto returnVoid = mDescrambler->descramble(
519 sctrl,
520 hidlSubSamples,
521 src,
522 0,
523 dst,
524 0,
525 [&status, &result, &detailedError] (
526 CasStatus _status, uint32_t _bytesWritten,
527 const hidl_string& _detailedError) {
528 status = _status;
529 result = (ssize_t)_bytesWritten;
530 detailedError = _detailedError;
531 });
Arun Johnson634d0802023-02-14 22:07:51 +0000532 if (errorDetailMsg) {
533 errorDetailMsg->setTo(detailedError.c_str(), detailedError.size());
534 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800535 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
536 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
537 mName, returnVoid.description().c_str(), status, result);
538 return UNKNOWN_ERROR;
539 }
540
541 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700542 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
543 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800544 return BAD_VALUE;
545 }
546 }
547 if (!secure) {
548 C2WriteView view = block->map().get();
549 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700550 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
551 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800552 return UNKNOWN_ERROR;
553 }
554 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700555 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
556 "(non-secure)",
557 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800558 return UNKNOWN_ERROR;
559 }
560 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
561 }
562 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
563 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
564 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700565 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800566 return -ENOSYS;
567 }
568 return OK;
569}
570
Pawin Vongmasa36653902018-11-15 00:10:25 -0800571status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
572 QueueGuard guard(mSync);
573 if (!guard.isRunning()) {
574 ALOGD("[%s] No more buffers should be queued at current state.", mName);
575 return -ENOSYS;
576 }
577 return queueInputBufferInternal(buffer);
578}
579
580status_t CCodecBufferChannel::queueSecureInputBuffer(
581 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
582 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
583 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
584 AString *errorDetailMsg) {
585 QueueGuard guard(mSync);
586 if (!guard.isRunning()) {
587 ALOGD("[%s] No more buffers should be queued at current state.", mName);
588 return -ENOSYS;
589 }
590
591 if (!hasCryptoOrDescrambler()) {
592 return -ENOSYS;
593 }
594 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
595
Sungtak Lee04b30352020-07-27 13:57:25 -0700596 std::shared_ptr<C2LinearBlock> block;
597 size_t allocSize = buffer->size();
598 size_t bufferSize = 0;
599 c2_status_t blockRes = C2_OK;
600 bool copied = false;
Arun Johnson7ba67072023-11-06 22:23:04 +0000601 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
602 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
Sungtak Lee04b30352020-07-27 13:57:25 -0700603 if (mSendEncryptedInfoBuffer) {
604 static const C2MemoryUsage kDefaultReadWriteUsage{
605 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
606 constexpr int kAllocGranule0 = 1024 * 64;
607 constexpr int kAllocGranule1 = 1024 * 1024;
608 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
609 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
610 if (allocSize <= kAllocGranule1) {
611 bufferSize = align(allocSize, kAllocGranule0);
612 } else {
613 bufferSize = align(allocSize, kAllocGranule1);
614 }
615 blockRes = pool->fetchLinearBlock(
616 bufferSize, kDefaultReadWriteUsage, &block);
617
618 if (blockRes == C2_OK) {
619 C2WriteView view = block->map().get();
620 if (view.error() == C2_OK && view.size() == bufferSize) {
621 copied = true;
622 // TODO: only copy clear sections
623 memcpy(view.data(), buffer->data(), allocSize);
624 }
625 }
626 }
627
628 if (!copied) {
629 block.reset();
630 }
631
Pawin Vongmasa36653902018-11-15 00:10:25 -0800632 ssize_t result = -1;
633 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700634 if (numSubSamples == 1
635 && subSamples[0].mNumBytesOfClearData == 0
636 && subSamples[0].mNumBytesOfEncryptedData == 0) {
637 // We don't need to go through crypto or descrambler if the input is empty.
638 result = 0;
639 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700640 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800641 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700642 destination.type = DrmBufferType::NATIVE_HANDLE;
643 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800644 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700645 destination.type = DrmBufferType::SHARED_MEMORY;
646 IMemoryToSharedBuffer(
647 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800648 }
Robert Shih895fba92019-07-16 16:29:44 -0700649 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800650 encryptedBuffer->fillSourceBuffer(&source);
651 result = mCrypto->decrypt(
652 key, iv, mode, pattern, source, buffer->offset(),
653 subSamples, numSubSamples, destination, errorDetailMsg);
654 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700655 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800656 return result;
657 }
Robert Shih895fba92019-07-16 16:29:44 -0700658 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800659 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
660 }
661 } else {
662 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
663 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
664 hidl_vec<SubSample> hidlSubSamples;
665 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
666
667 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
668 encryptedBuffer->fillSourceBuffer(&srcBuffer);
669
670 DestinationBuffer dstBuffer;
671 if (secure) {
672 dstBuffer.type = BufferType::NATIVE_HANDLE;
673 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
674 } else {
675 dstBuffer.type = BufferType::SHARED_MEMORY;
676 dstBuffer.nonsecureMemory = srcBuffer;
677 }
678
679 CasStatus status = CasStatus::OK;
680 hidl_string detailedError;
681 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
682
683 if (key != nullptr) {
684 sctrl = (ScramblingControl)key[0];
685 // Adjust for the PES offset
686 codecDataOffset = key[2] | (key[3] << 8);
687 }
688
689 auto returnVoid = mDescrambler->descramble(
690 sctrl,
691 hidlSubSamples,
692 srcBuffer,
693 0,
694 dstBuffer,
695 0,
696 [&status, &result, &detailedError] (
697 CasStatus _status, uint32_t _bytesWritten,
698 const hidl_string& _detailedError) {
699 status = _status;
700 result = (ssize_t)_bytesWritten;
701 detailedError = _detailedError;
702 });
703
704 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
705 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
706 mName, returnVoid.description().c_str(), status, result);
707 return UNKNOWN_ERROR;
708 }
709
710 if (result < codecDataOffset) {
711 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
712 return BAD_VALUE;
713 }
714
715 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
716
717 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
718 encryptedBuffer->copyDecryptedContentFromMemory(result);
719 }
720 }
721
722 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700723
724 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800725}
726
727void CCodecBufferChannel::feedInputBufferIfAvailable() {
728 QueueGuard guard(mSync);
729 if (!guard.isRunning()) {
730 ALOGV("[%s] We're not running --- no input buffer reported", mName);
731 return;
732 }
733 feedInputBufferIfAvailableInternal();
734}
735
736void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900737 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800738 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700739 }
740 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700741 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700742 if (!output->buffers ||
743 output->buffers->hasPending() ||
Wonsik Kim3722abc2023-05-17 13:26:31 -0700744 (!output->bounded && output->buffers->numActiveSlots() >= output->numSlots)) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800745 return;
746 }
747 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700748 size_t numActiveSlots = 0;
749 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800750 sp<MediaCodecBuffer> inBuffer;
751 size_t index;
752 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700753 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700754 numActiveSlots = input->buffers->numActiveSlots();
755 if (numActiveSlots >= input->numSlots) {
756 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800757 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700758 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800760 break;
761 }
762 }
763 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
764 mCallback->onInputBufferAvailable(index, inBuffer);
765 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700766 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800767}
768
769status_t CCodecBufferChannel::renderOutputBuffer(
770 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800771 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800772 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800773 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800774 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700775 Mutexed<Output>::Locked output(mOutput);
776 if (output->buffers) {
777 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800778 }
779 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800780 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
781 // set to true.
782 sendOutputBuffers();
783 // input buffer feeding may have been gated by pending output buffers
784 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800785 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800786 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700787 std::call_once(mRenderWarningFlag, [this] {
788 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
789 "timestamp or render=true with non-video buffers. Apps should "
790 "call releaseOutputBuffer() with render=false for those.",
791 mName);
792 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800793 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800794 return INVALID_OPERATION;
795 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800796
797#if 0
798 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
799 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
800 for (const std::shared_ptr<const C2Info> &info : infoParams) {
801 AString res;
802 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
803 if (ix) res.append(", ");
804 res.append(*((int32_t*)info.get() + (ix / 4)));
805 }
806 ALOGV(" [%s]", res.c_str());
807 }
808#endif
809 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
810 std::static_pointer_cast<const C2StreamRotationInfo::output>(
811 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
812 bool flip = rotation && (rotation->flip & 1);
813 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900814
815 {
816 Mutexed<OutputSurface>::Locked output(mOutputSurface);
817 if (output->surface == nullptr) {
818 ALOGI("[%s] cannot render buffer without surface", mName);
819 return OK;
820 }
821 int64_t frameIndex;
822 buffer->meta()->findInt64("frameIndex", &frameIndex);
823 if (output->rotation.count(frameIndex) != 0) {
824 auto it = output->rotation.find(frameIndex);
825 quarters = (it->second / 90) & 3;
826 output->rotation.erase(it);
827 }
828 }
829
Pawin Vongmasa36653902018-11-15 00:10:25 -0800830 uint32_t transform = 0;
831 switch (quarters) {
832 case 0: // no rotation
833 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
834 break;
835 case 1: // 90 degrees counter-clockwise
836 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
837 : HAL_TRANSFORM_ROT_270;
838 break;
839 case 2: // 180 degrees
840 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
841 break;
842 case 3: // 90 degrees clockwise
843 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
844 : HAL_TRANSFORM_ROT_90;
845 break;
846 }
847
848 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
849 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
850 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
851 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
852 if (surfaceScaling) {
853 videoScalingMode = surfaceScaling->value;
854 }
855
856 // Use dataspace from format as it has the default aspects already applied
857 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
858 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
859
860 // HDR static info
861 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
862 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
863 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
864
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800865 // HDR10 plus info
866 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
867 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
868 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800869 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
870 hdr10PlusInfo.reset();
871 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800872
Wonsik Kima79c5522022-01-18 16:29:24 -0800873 // HDR dynamic info
874 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
875 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
876 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
877 // TODO: make this sticky & enable unset
878 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
879 hdrDynamicInfo.reset();
880 }
881
882 if (hdr10PlusInfo) {
883 // C2StreamHdr10PlusInfo is deprecated; components should use
884 // C2StreamHdrDynamicMetadataInfo
885 // TODO: #metric
886 if (hdrDynamicInfo) {
887 // It is unexpected that C2StreamHdr10PlusInfo and
888 // C2StreamHdrDynamicMetadataInfo is both present.
889 // C2StreamHdrDynamicMetadataInfo takes priority.
890 // TODO: #metric
891 } else {
892 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
893 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
894 hdr10PlusInfo->flexCount(),
895 0u,
896 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
897 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
898 hdrDynamicInfo = info;
899 }
900 }
901
Pawin Vongmasa36653902018-11-15 00:10:25 -0800902 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
903 if (blocks.size() != 1u) {
904 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
905 return UNKNOWN_ERROR;
906 }
907 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700908 C2Fence c2fence = block.fence();
909 sp<Fence> fence = Fence::NO_FENCE;
910 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
911 // Once C2Fence::type() is added, check the exact C2Fence type
912 if (c2fence.isHW()) {
913 int fenceFd = c2fence.fd();
914 fence = sp<Fence>::make(fenceFd);
915 if (!fence) {
916 ALOGE("[%s] Failed to allocate a fence", mName);
917 close(fenceFd);
918 return NO_MEMORY;
919 }
920 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800921
922 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -0700923 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800924 timestampNs,
925 false, // droppable
926 dataSpace,
927 Rect(blocks.front().crop().left,
928 blocks.front().crop().top,
929 blocks.front().crop().right(),
930 blocks.front().crop().bottom()),
931 videoScalingMode,
932 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700933 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800934 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800935 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800936 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800937 // If mastering max and min luminance fields are 0, do not use them.
938 // It indicates the value may not be present in the stream.
939 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
940 hdrStaticInfo->mastering.minLuminance > 0.0f) {
941 struct android_smpte2086_metadata smpte2086_meta = {
942 .displayPrimaryRed = {
943 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
944 },
945 .displayPrimaryGreen = {
946 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
947 },
948 .displayPrimaryBlue = {
949 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
950 },
951 .whitePoint = {
952 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
953 },
954 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
955 .minLuminance = hdrStaticInfo->mastering.minLuminance,
956 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800957 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800958 hdr.smpte2086 = smpte2086_meta;
959 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700960 // If the content light level fields are 0, do not use them, it
961 // indicates the value may not be present in the stream.
962 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
963 struct android_cta861_3_metadata cta861_meta = {
964 .maxContentLightLevel = hdrStaticInfo->maxCll,
965 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
966 };
967 hdr.validTypes |= HdrMetadata::CTA861_3;
968 hdr.cta8613 = cta861_meta;
969 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900970
971 // does not have valid info
972 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
973 hdrStaticInfo.reset();
974 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800975 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800976 if (hdrDynamicInfo
977 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800978 hdr.validTypes |= HdrMetadata::HDR10PLUS;
979 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800980 hdrDynamicInfo->m.data,
981 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800982 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800983 qbi.setHdrMetadata(hdr);
984 }
Hongguangfc1478a2022-07-20 22:56:06 -0700985 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
986
Brian Lindahl932bf602023-03-09 11:59:48 -0700987 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
988 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
989 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800990 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
991 if (result != OK) {
992 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800993 if (result == NO_INIT) {
994 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
995 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800996 return result;
997 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800998
999 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
1000 ALOGD("[%s] queue buffer successful", mName);
1001 } else {
1002 ALOGV("[%s] queue buffer successful", mName);
1003 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001004
1005 int64_t mediaTimeUs = 0;
1006 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahl83931482023-08-10 10:12:49 -06001007 if (mAreRenderMetricsEnabled && mIsSurfaceToDisplay) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001008 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
1009 processRenderedFrames(qbo.frameTimestamps);
1010 } else {
1011 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
1012 // when the frame is queued to the non-display surface
1013 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1014 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001015
1016 return OK;
1017}
1018
Brian Lindahl932bf602023-03-09 11:59:48 -07001019void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001020 mTrackedFrames.clear();
1021
1022 int isSurfaceToDisplay = 0;
1023 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1024 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1025 // No frame tracking is needed if we're not sending frames to the display
1026 if (!mIsSurfaceToDisplay) {
1027 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1028 return;
1029 }
1030
Brian Lindahl932bf602023-03-09 11:59:48 -07001031 int hasPresentFenceTimes = 0;
1032 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1033 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
Brian Lindahl119e0c22023-05-19 15:42:13 -06001034 if (!mHasPresentFenceTimes) {
Brian Lindahl932bf602023-03-09 11:59:48 -07001035 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1036 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001037}
1038
1039void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1040 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1041 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1042 // so track the frame as if the desired render time is now.
1043 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1044 if (desiredRenderTimeNs < nowNs) {
1045 desiredRenderTimeNs = nowNs;
1046 }
Brian Lindahl87acc502023-11-15 10:10:51 -07001047
1048 // If the render time is more than a second from now, then pretend the frame is supposed to be
1049 // rendered immediately, because that's what SurfaceFlinger heuristics will do. This is a tight
1050 // coupling, but is really the only way to optimize away unnecessary present fence checks in
1051 // processRenderedFrames.
1052 if (desiredRenderTimeNs > nowNs + 1*1000*1000*1000LL) {
1053 desiredRenderTimeNs = nowNs;
1054 }
1055
Brian Lindahl932bf602023-03-09 11:59:48 -07001056 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1057 // actually rendered.
1058 TrackedFrame frame;
1059 frame.number = qbo.nextFrameNumber - 1;
1060 frame.mediaTimeUs = mediaTimeUs;
1061 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1062 frame.latchTime = -1;
1063 frame.presentFence = nullptr;
1064 mTrackedFrames.push_back(frame);
1065}
1066
1067void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1068 // Grab the latch times and present fences from the frame event deltas
1069 for (const auto& delta : deltas) {
1070 for (auto& frame : mTrackedFrames) {
1071 if (delta.getFrameNumber() == frame.number) {
1072 delta.getLatchTime(&frame.latchTime);
1073 delta.getDisplayPresentFence(&frame.presentFence);
1074 }
1075 }
1076 }
1077
1078 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1079 // in fact, been rendered.
1080 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1081 while (!mTrackedFrames.empty()) {
1082 TrackedFrame & frame = mTrackedFrames.front();
1083 // Frames that should have been rendered at least 100ms in the past are checked
1084 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1085 break;
1086 }
1087
1088 // If we don't have a render time by now, then consider the frame as dropped
1089 int64_t renderTimeNs = getRenderTimeNs(frame);
1090 if (renderTimeNs != -1) {
1091 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1092 }
1093 mTrackedFrames.pop_front();
1094 }
1095}
1096
1097int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1098 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1099 if (!mHasPresentFenceTimes) {
1100 if (frame.latchTime == -1) {
1101 ALOGD("no latch time for frame %d", (int) frame.number);
1102 return -1;
1103 }
1104 return frame.latchTime;
1105 }
1106
1107 if (frame.presentFence == nullptr) {
1108 ALOGW("no present fence for frame %d", (int) frame.number);
1109 return -1;
1110 }
1111
1112 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1113
1114 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1115 ALOGW("invalid signal time for frame %d", (int) frame.number);
1116 return -1;
1117 }
1118
1119 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1120 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1121 return -1;
1122 }
1123
1124 return actualRenderTimeNs;
1125}
1126
1127void CCodecBufferChannel::pollForRenderedBuffers() {
1128 FrameEventHistoryDelta delta;
1129 mComponent->pollForRenderedFrames(&delta);
1130 processRenderedFrames(delta);
1131}
1132
Sungtak Lee214ce612023-11-01 10:01:13 +00001133void CCodecBufferChannel::onBufferReleasedFromOutputSurface(uint32_t generation) {
1134 mComponent->onBufferReleasedFromOutputSurface(generation);
1135}
1136
Pawin Vongmasa36653902018-11-15 00:10:25 -08001137status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1138 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1139 bool released = false;
1140 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001141 Mutexed<Input>::Locked input(mInput);
1142 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001143 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001144 }
1145 }
1146 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001147 Mutexed<Output>::Locked output(mOutput);
1148 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001149 released = true;
1150 }
1151 }
1152 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001153 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001154 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001155 } else {
1156 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1157 }
1158 return OK;
1159}
1160
1161void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1162 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001163 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001164
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001165 if (!input->buffers) {
1166 ALOGE("getInputBufferArray: No Input Buffers allocated");
1167 return;
1168 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001169 if (!input->buffers->isArrayMode()) {
1170 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001171 }
1172
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001173 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001174}
1175
1176void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1177 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001178 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001179 if (!output->buffers) {
1180 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1181 return;
1182 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001183 if (!output->buffers->isArrayMode()) {
1184 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001185 }
1186
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001187 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001188}
1189
1190status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001191 const sp<AMessage> &inputFormat,
1192 const sp<AMessage> &outputFormat,
1193 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001194 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1195 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001196 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001197 C2PortReorderBufferDepthTuning::output reorderDepth;
1198 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001199 C2PortActualDelayTuning::input inputDelay(0);
1200 C2PortActualDelayTuning::output outputDelay(0);
1201 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001202 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001203
Pawin Vongmasa36653902018-11-15 00:10:25 -08001204 c2_status_t err = mComponent->query(
1205 {
1206 &iStreamFormat,
1207 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001208 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001209 &reorderDepth,
1210 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001211 &inputDelay,
1212 &pipelineDelay,
1213 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001214 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001215 },
1216 {},
1217 C2_DONT_BLOCK,
1218 nullptr);
1219 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001220 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001221 return UNKNOWN_ERROR;
1222 }
1223 } else if (err != C2_OK) {
1224 return UNKNOWN_ERROR;
1225 }
1226
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001227 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1228 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1229 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1230
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001231 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1232 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001233
Pawin Vongmasa36653902018-11-15 00:10:25 -08001234 // TODO: get this from input format
1235 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1236
Sungtak Lee04b30352020-07-27 13:57:25 -07001237 // secure mode is a static parameter (shall not change in the executing state)
1238 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1239
Pawin Vongmasa36653902018-11-15 00:10:25 -08001240 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001241 int poolMask = GetCodec2PoolMask();
1242 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001243
1244 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001245 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001246 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001247 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1248 API_REFLECTION |
1249 API_VALUES |
1250 API_CURRENT_VALUES |
1251 API_DEPENDENCY |
1252 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001253 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1254 C2StreamSampleRateInfo::input sampleRate(0u);
1255 C2StreamChannelCountInfo::input channelCount(0u);
1256 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001257 std::shared_ptr<C2BlockPool> pool;
1258 {
1259 Mutexed<BlockPools>::Locked pools(mBlockPools);
1260
1261 // set default allocator ID.
1262 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001263 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001264
1265 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1266 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1267 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001268 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001269 std::vector<C2Param *> stackParams({&featuresSetting});
1270 if (audioEncoder) {
1271 stackParams.push_back(&encoderFrameSize);
1272 stackParams.push_back(&sampleRate);
1273 stackParams.push_back(&channelCount);
1274 stackParams.push_back(&pcmEncoding);
1275 } else {
1276 encoderFrameSize.invalidate();
1277 sampleRate.invalidate();
1278 channelCount.invalidate();
1279 pcmEncoding.invalidate();
1280 }
1281 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001282 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1283 C2_DONT_BLOCK,
1284 &params);
1285 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1286 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1287 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001288 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001289 C2PortAllocatorsTuning::input *inputAllocators =
1290 C2PortAllocatorsTuning::input::From(params[0].get());
1291 if (inputAllocators && inputAllocators->flexCount() > 0) {
1292 std::shared_ptr<C2Allocator> allocator;
1293 // verify allocator IDs and resolve default allocator
1294 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1295 if (allocator) {
1296 pools->inputAllocatorId = allocator->getId();
1297 } else {
1298 ALOGD("[%s] component requested invalid input allocator ID %u",
1299 mName, inputAllocators->m.values[0]);
1300 }
1301 }
1302 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001303 if (featuresSetting) {
1304 apiFeatures = featuresSetting.value;
1305 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001306
1307 // TODO: use C2Component wrapper to associate this pool with ourselves
1308 if ((poolMask >> pools->inputAllocatorId) & 1) {
1309 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1310 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1311 mName, pools->inputAllocatorId,
1312 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1313 asString(err), err);
1314 } else {
1315 err = C2_NOT_FOUND;
1316 }
1317 if (err != C2_OK) {
1318 C2BlockPool::local_id_t inputPoolId =
1319 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1320 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1321 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1322 mName, (unsigned long long)inputPoolId,
1323 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1324 asString(err), err);
1325 if (err != C2_OK) {
1326 return NO_MEMORY;
1327 }
1328 }
1329 pools->inputPool = pool;
1330 }
1331
Wonsik Kim51051262018-11-28 13:59:05 -08001332 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001333 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001334 input->inputDelay = inputDelayValue;
1335 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001336 input->numSlots = numInputSlots;
1337 input->extraBuffers.flush();
1338 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001339 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001340 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1341 input->frameReassembler.init(
1342 pool,
1343 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1344 encoderFrameSize.value,
1345 sampleRate.value,
1346 channelCount.value,
1347 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1348 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001349 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1350 // For encrypted content, framework decrypts source buffer (ashmem) into
1351 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001352 if (!buffersBoundToCodec
1353 && !input->frameReassembler
1354 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001355 input->buffers.reset(new SlotInputBuffers(mName));
1356 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001357 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001358 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001359 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001360 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001361 // This is to ensure buffers do not get released prematurely.
1362 // TODO: handle this without going into array mode
1363 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001364 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001365 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001366 }
1367 } else {
1368 if (hasCryptoOrDescrambler()) {
1369 int32_t capacity = kLinearBufferSize;
1370 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1371 if ((size_t)capacity > kMaxLinearBufferSize) {
1372 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1373 capacity = kMaxLinearBufferSize;
1374 }
1375 if (mDealer == nullptr) {
1376 mDealer = new MemoryDealer(
1377 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001378 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001379 "EncryptedLinearInputBuffers");
1380 mDecryptDestination = mDealer->allocate((size_t)capacity);
1381 }
1382 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001383 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1384 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001385 } else {
1386 mHeapSeqNum = -1;
1387 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001388 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001389 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001390 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001391 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001392 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001393 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 }
1395 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001396 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001397
1398 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001399 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001400 } else {
1401 // TODO: error
1402 }
Wonsik Kim51051262018-11-28 13:59:05 -08001403
1404 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001405 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001406 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001407 }
1408
1409 if (outputFormat != nullptr) {
1410 sp<IGraphicBufferProducer> outputSurface;
1411 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001412 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001413 {
1414 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001415 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001416 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001417 outputSurface = output->surface ?
1418 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001419 if (outputSurface) {
1420 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1421 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001422 outputGeneration = output->generation;
1423 }
1424
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001425 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001426 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001427 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001428
1429 {
1430 Mutexed<BlockPools>::Locked pools(mBlockPools);
1431
David Stevensc3fbb282021-01-18 18:11:20 +09001432 prevOutputPoolId = pools->outputPoolId;
1433
Pawin Vongmasa36653902018-11-15 00:10:25 -08001434 // set default allocator ID.
1435 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001436 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001437
1438 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1439 // unsuccessful.
1440 std::vector<std::unique_ptr<C2Param>> params;
1441 err = mComponent->query({ },
1442 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1443 C2_DONT_BLOCK,
1444 &params);
1445 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1446 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1447 mName, params.size(), asString(err), err);
1448 } else if (err == C2_OK && params.size() == 1) {
1449 C2PortAllocatorsTuning::output *outputAllocators =
1450 C2PortAllocatorsTuning::output::From(params[0].get());
1451 if (outputAllocators && outputAllocators->flexCount() > 0) {
1452 std::shared_ptr<C2Allocator> allocator;
1453 // verify allocator IDs and resolve default allocator
1454 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1455 if (allocator) {
1456 pools->outputAllocatorId = allocator->getId();
1457 } else {
1458 ALOGD("[%s] component requested invalid output allocator ID %u",
1459 mName, outputAllocators->m.values[0]);
1460 }
1461 }
1462 }
1463
1464 // use bufferqueue if outputting to a surface.
1465 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1466 // if unsuccessful.
1467 if (outputSurface) {
1468 params.clear();
1469 err = mComponent->query({ },
1470 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1471 C2_DONT_BLOCK,
1472 &params);
1473 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1474 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1475 mName, params.size(), asString(err), err);
1476 } else if (err == C2_OK && params.size() == 1) {
1477 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1478 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1479 if (surfaceAllocator) {
1480 std::shared_ptr<C2Allocator> allocator;
1481 // verify allocator IDs and resolve default allocator
1482 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1483 if (allocator) {
1484 pools->outputAllocatorId = allocator->getId();
1485 } else {
1486 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1487 mName, surfaceAllocator->value);
1488 err = C2_BAD_VALUE;
1489 }
1490 }
1491 }
1492 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1493 && err != C2_OK
1494 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1495 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1496 }
1497 }
1498
1499 if ((poolMask >> pools->outputAllocatorId) & 1) {
1500 err = mComponent->createBlockPool(
1501 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1502 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1503 mName, pools->outputAllocatorId,
1504 (unsigned long long)pools->outputPoolId,
1505 asString(err));
1506 } else {
1507 err = C2_NOT_FOUND;
1508 }
1509 if (err != C2_OK) {
1510 // use basic pool instead
1511 pools->outputPoolId =
1512 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1513 }
1514
1515 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1516 // component.
1517 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1518 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1519
1520 std::vector<std::unique_ptr<C2SettingResult>> failures;
1521 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1522 ALOGD("[%s] Configured output block pool ids %llu => %s",
1523 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1524 outputPoolId_ = pools->outputPoolId;
1525 }
1526
David Stevensc3fbb282021-01-18 18:11:20 +09001527 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1528 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1529 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1530 if (err != C2_OK) {
1531 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1532 (unsigned long long) prevOutputPoolId, asString(err), err);
1533 }
1534 }
1535
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001536 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001537 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001538 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001539 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001540 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001541 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001542 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001543 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001544 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001545 }
1546 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001547 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001548 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001549 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001550
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001551 output->buffers->clearStash();
1552 if (reorderDepth) {
1553 output->buffers->setReorderDepth(reorderDepth.value);
1554 }
1555 if (reorderKey) {
1556 output->buffers->setReorderKey(reorderKey.value);
1557 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001558
1559 // Try to set output surface to created block pool if given.
1560 if (outputSurface) {
1561 mComponent->setOutputSurface(
1562 outputPoolId_,
1563 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001564 outputGeneration,
1565 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001566 } else {
1567 // configure CPU read consumer usage
1568 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1569 std::vector<std::unique_ptr<C2SettingResult>> failures;
1570 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1571 // do not print error message for now as most components may not yet
1572 // support this setting
1573 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1574 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001575 }
1576
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001577 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001578 if (buffersBoundToCodec) {
1579 // WORKAROUND: if we're using early CSD workaround we convert to
1580 // array mode, to appease apps assuming the output
1581 // buffers to be of the same size.
1582 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1583 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001584
1585 int32_t channelCount;
1586 int32_t sampleRate;
1587 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1588 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1589 int32_t delay = 0;
1590 int32_t padding = 0;;
1591 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1592 delay = 0;
1593 }
1594 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1595 padding = 0;
1596 }
1597 if (delay || padding) {
1598 // We need write access to the buffers, and we're already in
1599 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001600 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001601 }
1602 }
1603 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001604
1605 int32_t tunneled = 0;
1606 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1607 tunneled = 0;
1608 }
1609 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001610 }
1611
1612 // Set up pipeline control. This has to be done after mInputBuffers and
1613 // mOutputBuffers are initialized to make sure that lingering callbacks
1614 // about buffers from the previous generation do not interfere with the
1615 // newly initialized pipeline capacity.
1616
Wonsik Kim62545252021-01-20 11:25:41 -08001617 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001618 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001619 watcher->inputDelay(inputDelayValue)
1620 .pipelineDelay(pipelineDelayValue)
1621 .outputDelay(outputDelayValue)
Houxiang Dai0b573282023-03-11 18:31:56 +08001622 .smoothnessFactor(kSmoothnessFactor)
1623 .tunneled(mTunneled);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001624 watcher->flush();
1625 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001626
1627 mInputMetEos = false;
1628 mSync.start();
1629 return OK;
1630}
1631
Wonsik Kim34b28b42022-05-20 15:49:32 -07001632status_t CCodecBufferChannel::prepareInitialInputBuffers(
1633 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001634 if (mInputSurface) {
1635 return OK;
1636 }
1637
Wonsik Kim34b28b42022-05-20 15:49:32 -07001638 size_t numInputSlots = mInput.lock()->numSlots;
1639
1640 {
1641 Mutexed<Input>::Locked input(mInput);
1642 while (clientInputBuffers->size() < numInputSlots) {
1643 size_t index;
1644 sp<MediaCodecBuffer> buffer;
1645 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1646 break;
1647 }
1648 clientInputBuffers->emplace(index, buffer);
1649 }
1650 }
1651 if (clientInputBuffers->empty()) {
1652 ALOGW("[%s] start: cannot allocate memory at all", mName);
1653 return NO_MEMORY;
1654 } else if (clientInputBuffers->size() < numInputSlots) {
1655 ALOGD("[%s] start: cannot allocate memory for all slots, "
1656 "only %zu buffers allocated",
1657 mName, clientInputBuffers->size());
1658 } else {
1659 ALOGV("[%s] %zu initial input buffers available",
1660 mName, clientInputBuffers->size());
1661 }
1662 return OK;
1663}
1664
1665status_t CCodecBufferChannel::requestInitialInputBuffers(
1666 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001667 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001668 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1669 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1670 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001671 return UNKNOWN_ERROR;
1672 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001673
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001674 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1675 mFlushedConfigs.lock()->swap(flushedConfigs);
1676 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001677 {
1678 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1679 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1680 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1681 watcher->onWorkQueued(
1682 work->input.ordinal.frameIndex.peeku(),
1683 std::vector(work->input.buffers),
1684 now);
1685 }
1686 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001687 err = mComponent->queue(&flushedConfigs);
1688 if (err != C2_OK) {
1689 ALOGW("[%s] Error while queueing a flushed config", mName);
1690 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001691 }
1692 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001693 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001694 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1695 !clientInputBuffers.empty()) {
1696 size_t minIndex = clientInputBuffers.begin()->first;
1697 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1698 for (const auto &[index, buffer] : clientInputBuffers) {
1699 if (minBuffer->capacity() > buffer->capacity()) {
1700 minIndex = index;
1701 minBuffer = buffer;
1702 }
1703 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001704 // WORKAROUND: Some apps expect CSD available without queueing
1705 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001706 minBuffer->setRange(0, 0);
1707 minBuffer->meta()->clear();
1708 minBuffer->meta()->setInt64("timeUs", 0);
1709 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001710 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1711 mName);
1712 return UNKNOWN_ERROR;
1713 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001714 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001715 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001716
Wonsik Kim34b28b42022-05-20 15:49:32 -07001717 for (const auto &[index, buffer] : clientInputBuffers) {
1718 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001719 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001720
Pawin Vongmasa36653902018-11-15 00:10:25 -08001721 return OK;
1722}
1723
1724void CCodecBufferChannel::stop() {
1725 mSync.stop();
1726 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001727}
1728
Sungtak Lee99144332023-01-26 11:03:14 +00001729void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
1730 sp<Surface> surface = mOutputSurface.lock()->surface;
1731 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00001732 C2BlockPool::local_id_t outputPoolId;
1733 {
1734 Mutexed<BlockPools>::Locked pools(mBlockPools);
1735 outputPoolId = pools->outputPoolId;
1736 }
1737 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00001738
1739 if (pushBlankBuffer) {
1740 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
1741 if (anw) {
1742 pushBlankBuffersToNativeWindow(anw.get());
1743 }
1744 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00001745 }
1746}
1747
Wonsik Kim936a89c2020-05-08 16:07:50 -07001748void CCodecBufferChannel::reset() {
1749 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001750 if (mInputSurface != nullptr) {
1751 mInputSurface.reset();
1752 }
1753 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001754 {
1755 Mutexed<Input>::Locked input(mInput);
1756 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001757 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001758 }
1759 {
1760 Mutexed<Output>::Locked output(mOutput);
1761 output->buffers.reset();
1762 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001763 // reset the frames that are being tracked for onFrameRendered callbacks
1764 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001765}
1766
1767void CCodecBufferChannel::release() {
1768 mComponent.reset();
1769 mInputAllocator.reset();
1770 mOutputSurface.lock()->surface.clear();
1771 {
1772 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1773 blockPools->inputPool.reset();
1774 blockPools->outputPoolIntf.reset();
1775 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001776 setCrypto(nullptr);
1777 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001778}
1779
Pawin Vongmasa36653902018-11-15 00:10:25 -08001780void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1781 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001782 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001783 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001784 {
1785 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1786 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1787 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1788 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1789 watcher->onWorkDone(frameIndex);
1790 continue;
1791 }
1792 if (work->input.buffers.empty()
1793 || work->input.buffers.front() == nullptr
1794 || work->input.buffers.front()->data().linearBlocks().empty()) {
1795 ALOGD("[%s] no linear codec config data found", mName);
1796 watcher->onWorkDone(frameIndex);
1797 continue;
1798 }
1799 std::unique_ptr<C2Work> copy(new C2Work);
1800 copy->input.flags = C2FrameData::flags_t(
1801 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1802 copy->input.ordinal = work->input.ordinal;
1803 copy->input.ordinal.frameIndex = mFrameIndex++;
1804 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1805 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1806 }
1807 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1808 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1809 }
1810 copy->input.infoBuffers.insert(
1811 copy->input.infoBuffers.begin(),
1812 work->input.infoBuffers.begin(),
1813 work->input.infoBuffers.end());
1814 copy->worklets.emplace_back(new C2Worklet);
1815 configs.push_back(std::move(copy));
1816 watcher->onWorkDone(frameIndex);
1817 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001818 }
1819 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001820 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001821 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001822 Mutexed<Input>::Locked input(mInput);
1823 input->buffers->flush();
1824 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001825 }
1826 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001827 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001828 if (output->buffers) {
1829 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001830 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001831 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001832 }
1833}
1834
1835void CCodecBufferChannel::onWorkDone(
1836 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001837 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001838 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001839 feedInputBufferIfAvailable();
1840 }
1841}
1842
1843void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001844 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001845 if (mInputSurface) {
1846 return;
1847 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001848 std::shared_ptr<C2Buffer> buffer =
1849 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001850 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001851 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001852 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001853 if (input->lastFlushIndex >= frameIndex) {
1854 ALOGD("[%s] Ignoring stale input buffer done callback: "
1855 "last flush index = %lld, frameIndex = %lld",
1856 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1857 } else {
1858 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1859 if (!newInputSlotAvailable) {
1860 (void)input->extraBuffers.expireComponentBuffer(buffer);
1861 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001862 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001863 }
1864 if (newInputSlotAvailable) {
1865 feedInputBufferIfAvailable();
1866 }
1867}
1868
1869bool CCodecBufferChannel::handleWork(
1870 std::unique_ptr<C2Work> work,
1871 const sp<AMessage> &outputFormat,
1872 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001873 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001874 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001875 if (!output->buffers) {
1876 return false;
1877 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001878 }
1879
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001880 // Whether the output buffer should be reported to the client or not.
1881 bool notifyClient = false;
1882
1883 if (work->result == C2_OK){
1884 notifyClient = true;
1885 } else if (work->result == C2_NOT_FOUND) {
1886 ALOGD("[%s] flushed work; ignored.", mName);
1887 } else {
1888 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1889 // the config update.
1890 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1891 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1892 return false;
1893 }
1894
1895 if ((work->input.ordinal.frameIndex -
1896 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001897 // Discard frames from previous generation.
1898 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001899 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001900 }
1901
Wonsik Kim524b0582019-03-12 11:28:57 -07001902 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001903 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001904 || !(work->worklets.front()->output.flags &
1905 C2FrameData::FLAG_INCOMPLETE))) {
1906 mPipelineWatcher.lock()->onWorkDone(
1907 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001908 }
1909
1910 // NOTE: MediaCodec usage supposedly have only one worklet
1911 if (work->worklets.size() != 1u) {
1912 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1913 mName, work->worklets.size());
1914 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1915 return false;
1916 }
1917
1918 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1919
1920 std::shared_ptr<C2Buffer> buffer;
1921 // NOTE: MediaCodec usage supposedly have only one output stream.
1922 if (worklet->output.buffers.size() > 1u) {
1923 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1924 mName, worklet->output.buffers.size());
1925 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1926 return false;
1927 } else if (worklet->output.buffers.size() == 1u) {
1928 buffer = worklet->output.buffers[0];
1929 if (!buffer) {
1930 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1931 }
1932 }
1933
Wonsik Kim3dedf682021-05-03 10:57:09 -07001934 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1935 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001936 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001937 while (!worklet->output.configUpdate.empty()) {
1938 std::unique_ptr<C2Param> param;
1939 worklet->output.configUpdate.back().swap(param);
1940 worklet->output.configUpdate.pop_back();
1941 switch (param->coreIndex().coreIndex()) {
1942 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1943 C2PortReorderBufferDepthTuning::output reorderDepth;
1944 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001945 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1946 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001947 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001948 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001949 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001950 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1951 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001952 }
1953 break;
1954 }
1955 case C2PortReorderKeySetting::CORE_INDEX: {
1956 C2PortReorderKeySetting::output reorderKey;
1957 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001958 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001959 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1960 mName, reorderKey.value);
1961 } else {
1962 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1963 }
1964 break;
1965 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001966 case C2PortActualDelayTuning::CORE_INDEX: {
1967 if (param->isGlobal()) {
1968 C2ActualPipelineDelayTuning pipelineDelay;
1969 if (pipelineDelay.updateFrom(*param)) {
1970 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1971 mName, pipelineDelay.value);
1972 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001973 (void)mPipelineWatcher.lock()->pipelineDelay(
1974 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001975 }
1976 }
1977 if (param->forInput()) {
1978 C2PortActualDelayTuning::input inputDelay;
1979 if (inputDelay.updateFrom(*param)) {
1980 ALOGV("[%s] onWorkDone: updating input delay %u",
1981 mName, inputDelay.value);
1982 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001983 (void)mPipelineWatcher.lock()->inputDelay(
1984 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001985 }
1986 }
1987 if (param->forOutput()) {
1988 C2PortActualDelayTuning::output outputDelay;
1989 if (outputDelay.updateFrom(*param)) {
1990 ALOGV("[%s] onWorkDone: updating output delay %u",
1991 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001992 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001993 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001994 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001995
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001996 }
1997 }
1998 break;
1999 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08002000 case C2PortTunnelSystemTime::CORE_INDEX: {
2001 C2PortTunnelSystemTime::output frameRenderTime;
2002 if (frameRenderTime.updateFrom(*param)) {
2003 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
2004 mName, (long long)frameRenderTime.value,
2005 (long long)worklet->output.ordinal.timestamp.peekll());
2006 mCCodecCallback->onOutputFramesRendered(
2007 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
2008 }
2009 break;
2010 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02002011 case C2StreamTunnelHoldRender::CORE_INDEX: {
2012 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
2013 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
2014 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
2015 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
2016 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
2017 mCCodecCallback->onFirstTunnelFrameReady();
2018 break;
2019 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002020 default:
2021 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2022 mName, param->index());
2023 break;
2024 }
2025 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002026 if (newInputDelay || newPipelineDelay) {
2027 Mutexed<Input>::Locked input(mInput);
2028 size_t newNumSlots =
2029 newInputDelay.value_or(input->inputDelay) +
2030 newPipelineDelay.value_or(input->pipelineDelay) +
2031 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08002032 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002033 if (input->buffers->isArrayMode()) {
2034 if (input->numSlots >= newNumSlots) {
2035 input->numExtraSlots = 0;
2036 } else {
2037 input->numExtraSlots = newNumSlots - input->numSlots;
2038 }
2039 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2040 mName, input->numExtraSlots);
2041 } else {
2042 input->numSlots = newNumSlots;
2043 }
2044 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002045 size_t numOutputSlots = 0;
2046 uint32_t reorderDepth = 0;
2047 bool outputBuffersChanged = false;
2048 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2049 Mutexed<Output>::Locked output(mOutput);
2050 if (!output->buffers) {
2051 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002052 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002053 numOutputSlots = output->numSlots;
2054 if (newReorderKey) {
2055 output->buffers->setReorderKey(newReorderKey.value());
2056 }
2057 if (newReorderDepth) {
2058 output->buffers->setReorderDepth(newReorderDepth.value());
2059 }
2060 reorderDepth = output->buffers->getReorderDepth();
2061 if (newOutputDelay) {
2062 output->outputDelay = newOutputDelay.value();
2063 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2064 if (output->numSlots < numOutputSlots) {
2065 output->numSlots = numOutputSlots;
2066 if (output->buffers->isArrayMode()) {
2067 OutputBuffersArray *array =
2068 (OutputBuffersArray *)output->buffers.get();
2069 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2070 mName, numOutputSlots);
2071 array->grow(numOutputSlots);
2072 outputBuffersChanged = true;
2073 }
2074 }
2075 }
2076 numOutputSlots = output->numSlots;
2077 }
2078 if (outputBuffersChanged) {
2079 mCCodecCallback->onOutputBuffersChanged();
2080 }
2081 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002082 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002083 {
2084 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2085 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002086 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002087 if (output->surface) {
2088 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2089 }
2090 }
2091 if (maxDequeueCount > 0) {
2092 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002093 }
2094 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002095
Pawin Vongmasa36653902018-11-15 00:10:25 -08002096 int32_t flags = 0;
2097 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002098 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002099 ALOGV("[%s] onWorkDone: output EOS", mName);
2100 }
2101
Pawin Vongmasa36653902018-11-15 00:10:25 -08002102 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2103 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2104 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2105 // shall correspond to the client input timesamp (in customOrdinal). By using the
2106 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2107 // produces multiple output.
2108 c2_cntr64_t timestamp =
2109 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2110 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002111 if (mInputSurface != nullptr) {
2112 // When using input surface we need to restore the original input timestamp.
2113 timestamp = work->input.ordinal.customOrdinal;
2114 }
My Name6bd9a7d2022-03-25 12:37:58 -07002115 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2116 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002117 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2118 mName,
2119 work->input.ordinal.customOrdinal.peekll(),
2120 work->input.ordinal.timestamp.peekll(),
2121 worklet->output.ordinal.timestamp.peekll(),
2122 timestamp.peekll());
2123
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002124 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002125 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002126 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002127 if (!output->buffers) {
2128 return false;
2129 }
2130 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002131 output->buffers->updateSkipCutBuffer(outputFormat);
2132 output->buffers->setFormat(outputFormat);
2133 }
2134 if (!notifyClient) {
2135 return false;
2136 }
2137 size_t index;
2138 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002139 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002140 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002141 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002142 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2143
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002144 // TRICKY: we want popped buffers reported in order, so sending
2145 // the callback while holding the lock here. This assumes that
2146 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2147 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002148 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002149 } else {
2150 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002151 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002152 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002153 return false;
2154 }
2155 }
2156
Wonsik Kimec585c32021-10-01 01:11:00 -07002157 bool drop = false;
2158 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2159 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2160 drop = true;
2161 }
2162
Marc Kassisec910342022-11-25 11:43:05 +01002163 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2164 // HAL, the flag is then removed in the corresponding output buffer.
2165 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2166 flags |= BUFFER_FLAG_DECODE_ONLY;
2167 }
2168
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002169 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002170 if (mTunneled && drop && outputFormat) {
Houxiang Daie74e5062022-05-19 15:32:54 +08002171 if (mOutputFormat != outputFormat) {
2172 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2173 mName, work->input.ordinal.frameIndex.peekull());
2174 mOutputFormat = outputFormat;
2175 } else {
2176 ALOGV("[%s] onWorkDone: Not reporting output buffer without format change (%lld)",
2177 mName, work->input.ordinal.frameIndex.peekull());
2178 notifyClient = false;
2179 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002180 } else {
2181 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2182 mName, work->input.ordinal.frameIndex.peekull());
2183 notifyClient = false;
2184 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002185 }
2186
2187 if (buffer) {
2188 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2189 // TODO: properly translate these to metadata
2190 switch (info->coreIndex().coreIndex()) {
2191 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002192 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002193 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002194 }
2195 break;
2196 default:
2197 break;
2198 }
2199 }
2200 }
2201
2202 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002203 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002204 if (!output->buffers) {
2205 return false;
2206 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002207 output->buffers->pushToStash(
2208 buffer,
2209 notifyClient,
2210 timestamp.peek(),
2211 flags,
2212 outputFormat,
2213 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002214 }
2215 sendOutputBuffers();
2216 return true;
2217}
2218
2219void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002220 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002221 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002222 sp<MediaCodecBuffer> outBuffer;
2223 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002224
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002225 constexpr int kMaxReallocTry = 5;
2226 int reallocTryNum = 0;
2227
Pawin Vongmasa36653902018-11-15 00:10:25 -08002228 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002229 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002230 if (!output->buffers) {
2231 return;
2232 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002233 action = output->buffers->popFromStashAndRegister(
2234 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002235 if (action != OutputBuffers::REALLOCATE) {
2236 reallocTryNum = 0;
2237 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002238 switch (action) {
2239 case OutputBuffers::SKIP:
2240 return;
2241 case OutputBuffers::DISCARD:
2242 break;
2243 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002244 // TRICKY: we want popped buffers reported in order, so sending
2245 // the callback while holding the lock here. This assumes that
2246 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2247 // callbacks are always sent with the Output lock held.
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002248 mCallback->onOutputBufferAvailable(index, outBuffer);
2249 break;
2250 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002251 if (++reallocTryNum > kMaxReallocTry) {
2252 output.unlock();
2253 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2254 mName, kMaxReallocTry);
2255 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2256 return;
2257 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002258 if (!output->buffers->isArrayMode()) {
2259 output->buffers =
2260 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002261 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002262 static_cast<OutputBuffersArray*>(output->buffers.get())->
2263 realloc(c2Buffer);
2264 output.unlock();
2265 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002266 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002267 case OutputBuffers::RETRY:
2268 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2269 mName);
2270 return;
2271 default:
2272 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2273 "corrupted BufferAction value (%d) "
2274 "returned from popFromStashAndRegister.",
2275 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002276 return;
2277 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002278 }
2279}
2280
Sungtak Lee214ce612023-11-01 10:01:13 +00002281status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface,
2282 uint32_t generation, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002283 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002284 int maxDequeueCount;
2285 sp<Surface> oldSurface;
2286 {
2287 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2288 maxDequeueCount = outputSurface->maxDequeueBuffers;
2289 oldSurface = outputSurface->surface;
2290 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002291 if (newSurface) {
2292 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002293 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002294 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002295 producer = newSurface->getIGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002296 } else {
2297 ALOGE("[%s] setting output surface to null", mName);
2298 return INVALID_OPERATION;
2299 }
2300
2301 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2302 C2BlockPool::local_id_t outputPoolId;
2303 {
2304 Mutexed<BlockPools>::Locked pools(mBlockPools);
2305 outputPoolId = pools->outputPoolId;
2306 outputPoolIntf = pools->outputPoolIntf;
2307 }
2308
2309 if (outputPoolIntf) {
2310 if (mComponent->setOutputSurface(
2311 outputPoolId,
2312 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002313 generation,
2314 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002315 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2316 return INVALID_OPERATION;
2317 }
2318 }
2319
2320 {
2321 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2322 output->surface = newSurface;
2323 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002324 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002325 }
2326
Sungtak Lee99144332023-01-26 11:03:14 +00002327 if (oldSurface && pushBlankBuffer) {
2328 // When ReleaseSurface was set from MediaCodec,
2329 // pushing a blank buffer at the end might be necessary.
2330 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2331 if (anw) {
2332 pushBlankBuffersToNativeWindow(anw.get());
2333 }
2334 }
2335
Pawin Vongmasa36653902018-11-15 00:10:25 -08002336 return OK;
2337}
2338
Wonsik Kimab34ed62019-01-31 15:28:46 -08002339PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002340 // Otherwise, component may have stalled work due to input starvation up to
2341 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002342 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2343 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002344 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002345 size_t outputDelay = mOutput.lock()->outputDelay;
2346 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002347 Mutexed<Input>::Locked input(mInput);
2348 n = input->inputDelay + input->pipelineDelay + outputDelay;
2349 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002350 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002351}
2352
Pawin Vongmasa36653902018-11-15 00:10:25 -08002353void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2354 mMetaMode = mode;
2355}
2356
Wonsik Kim596187e2019-10-25 12:44:10 -07002357void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002358 if (mCrypto != nullptr) {
2359 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2360 mCrypto->unsetHeap(entry.second);
2361 }
2362 mHeapSeqNumMap.clear();
2363 if (mHeapSeqNum >= 0) {
2364 mCrypto->unsetHeap(mHeapSeqNum);
2365 mHeapSeqNum = -1;
2366 }
2367 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002368 mCrypto = crypto;
2369}
2370
2371void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2372 mDescrambler = descrambler;
2373}
2374
Pawin Vongmasa36653902018-11-15 00:10:25 -08002375status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2376 // C2_OK is always translated to OK.
2377 if (c2s == C2_OK) {
2378 return OK;
2379 }
2380
2381 // Operation-dependent translation
2382 // TODO: Add as necessary
2383 switch (c2op) {
2384 case C2_OPERATION_Component_start:
2385 switch (c2s) {
2386 case C2_NO_MEMORY:
2387 return NO_MEMORY;
2388 default:
2389 return UNKNOWN_ERROR;
2390 }
2391 default:
2392 break;
2393 }
2394
2395 // Backup operation-agnostic translation
2396 switch (c2s) {
2397 case C2_BAD_INDEX:
2398 return BAD_INDEX;
2399 case C2_BAD_VALUE:
2400 return BAD_VALUE;
2401 case C2_BLOCKING:
2402 return WOULD_BLOCK;
2403 case C2_DUPLICATE:
2404 return ALREADY_EXISTS;
2405 case C2_NO_INIT:
2406 return NO_INIT;
2407 case C2_NO_MEMORY:
2408 return NO_MEMORY;
2409 case C2_NOT_FOUND:
2410 return NAME_NOT_FOUND;
2411 case C2_TIMED_OUT:
2412 return TIMED_OUT;
2413 case C2_BAD_STATE:
2414 case C2_CANCELED:
2415 case C2_CANNOT_DO:
2416 case C2_CORRUPTED:
2417 case C2_OMITTED:
2418 case C2_REFUSED:
2419 return UNKNOWN_ERROR;
2420 default:
2421 return -static_cast<status_t>(c2s);
2422 }
2423}
2424
Pawin Vongmasa36653902018-11-15 00:10:25 -08002425} // namespace android