blob: 8d70c394fd78d3936319a24ae442f94cbc462dae [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 Lindahld7967a92023-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 Lindahld7967a92023-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 Lindahld7967a92023-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 Lindahld7967a92023-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;
601 if (mSendEncryptedInfoBuffer) {
602 static const C2MemoryUsage kDefaultReadWriteUsage{
603 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
604 constexpr int kAllocGranule0 = 1024 * 64;
605 constexpr int kAllocGranule1 = 1024 * 1024;
606 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
607 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
608 if (allocSize <= kAllocGranule1) {
609 bufferSize = align(allocSize, kAllocGranule0);
610 } else {
611 bufferSize = align(allocSize, kAllocGranule1);
612 }
613 blockRes = pool->fetchLinearBlock(
614 bufferSize, kDefaultReadWriteUsage, &block);
615
616 if (blockRes == C2_OK) {
617 C2WriteView view = block->map().get();
618 if (view.error() == C2_OK && view.size() == bufferSize) {
619 copied = true;
620 // TODO: only copy clear sections
621 memcpy(view.data(), buffer->data(), allocSize);
622 }
623 }
624 }
625
626 if (!copied) {
627 block.reset();
628 }
629
Pawin Vongmasa36653902018-11-15 00:10:25 -0800630 ssize_t result = -1;
631 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700632 if (numSubSamples == 1
633 && subSamples[0].mNumBytesOfClearData == 0
634 && subSamples[0].mNumBytesOfEncryptedData == 0) {
635 // We don't need to go through crypto or descrambler if the input is empty.
636 result = 0;
637 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700638 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800639 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700640 destination.type = DrmBufferType::NATIVE_HANDLE;
641 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800642 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700643 destination.type = DrmBufferType::SHARED_MEMORY;
644 IMemoryToSharedBuffer(
645 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800646 }
Robert Shih895fba92019-07-16 16:29:44 -0700647 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800648 encryptedBuffer->fillSourceBuffer(&source);
649 result = mCrypto->decrypt(
650 key, iv, mode, pattern, source, buffer->offset(),
651 subSamples, numSubSamples, destination, errorDetailMsg);
652 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700653 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800654 return result;
655 }
Robert Shih895fba92019-07-16 16:29:44 -0700656 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800657 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
658 }
659 } else {
660 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
661 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
662 hidl_vec<SubSample> hidlSubSamples;
663 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
664
665 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
666 encryptedBuffer->fillSourceBuffer(&srcBuffer);
667
668 DestinationBuffer dstBuffer;
669 if (secure) {
670 dstBuffer.type = BufferType::NATIVE_HANDLE;
671 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
672 } else {
673 dstBuffer.type = BufferType::SHARED_MEMORY;
674 dstBuffer.nonsecureMemory = srcBuffer;
675 }
676
677 CasStatus status = CasStatus::OK;
678 hidl_string detailedError;
679 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
680
681 if (key != nullptr) {
682 sctrl = (ScramblingControl)key[0];
683 // Adjust for the PES offset
684 codecDataOffset = key[2] | (key[3] << 8);
685 }
686
687 auto returnVoid = mDescrambler->descramble(
688 sctrl,
689 hidlSubSamples,
690 srcBuffer,
691 0,
692 dstBuffer,
693 0,
694 [&status, &result, &detailedError] (
695 CasStatus _status, uint32_t _bytesWritten,
696 const hidl_string& _detailedError) {
697 status = _status;
698 result = (ssize_t)_bytesWritten;
699 detailedError = _detailedError;
700 });
701
702 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
703 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
704 mName, returnVoid.description().c_str(), status, result);
705 return UNKNOWN_ERROR;
706 }
707
708 if (result < codecDataOffset) {
709 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
710 return BAD_VALUE;
711 }
712
713 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
714
715 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
716 encryptedBuffer->copyDecryptedContentFromMemory(result);
717 }
718 }
719
720 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700721
722 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800723}
724
725void CCodecBufferChannel::feedInputBufferIfAvailable() {
726 QueueGuard guard(mSync);
727 if (!guard.isRunning()) {
728 ALOGV("[%s] We're not running --- no input buffer reported", mName);
729 return;
730 }
731 feedInputBufferIfAvailableInternal();
732}
733
734void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900735 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800736 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700737 }
738 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700739 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700740 if (!output->buffers ||
741 output->buffers->hasPending() ||
Wonsik Kim3722abc2023-05-17 13:26:31 -0700742 (!output->bounded && output->buffers->numActiveSlots() >= output->numSlots)) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800743 return;
744 }
745 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700746 size_t numActiveSlots = 0;
747 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748 sp<MediaCodecBuffer> inBuffer;
749 size_t index;
750 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700751 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700752 numActiveSlots = input->buffers->numActiveSlots();
753 if (numActiveSlots >= input->numSlots) {
754 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800755 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700756 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800757 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800758 break;
759 }
760 }
761 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
762 mCallback->onInputBufferAvailable(index, inBuffer);
763 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700764 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800765}
766
767status_t CCodecBufferChannel::renderOutputBuffer(
768 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800769 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800770 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800771 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800772 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700773 Mutexed<Output>::Locked output(mOutput);
774 if (output->buffers) {
775 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800776 }
777 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800778 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
779 // set to true.
780 sendOutputBuffers();
781 // input buffer feeding may have been gated by pending output buffers
782 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800783 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800784 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700785 std::call_once(mRenderWarningFlag, [this] {
786 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
787 "timestamp or render=true with non-video buffers. Apps should "
788 "call releaseOutputBuffer() with render=false for those.",
789 mName);
790 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800791 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800792 return INVALID_OPERATION;
793 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800794
795#if 0
796 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
797 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
798 for (const std::shared_ptr<const C2Info> &info : infoParams) {
799 AString res;
800 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
801 if (ix) res.append(", ");
802 res.append(*((int32_t*)info.get() + (ix / 4)));
803 }
804 ALOGV(" [%s]", res.c_str());
805 }
806#endif
807 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
808 std::static_pointer_cast<const C2StreamRotationInfo::output>(
809 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
810 bool flip = rotation && (rotation->flip & 1);
811 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900812
813 {
814 Mutexed<OutputSurface>::Locked output(mOutputSurface);
815 if (output->surface == nullptr) {
816 ALOGI("[%s] cannot render buffer without surface", mName);
817 return OK;
818 }
819 int64_t frameIndex;
820 buffer->meta()->findInt64("frameIndex", &frameIndex);
821 if (output->rotation.count(frameIndex) != 0) {
822 auto it = output->rotation.find(frameIndex);
823 quarters = (it->second / 90) & 3;
824 output->rotation.erase(it);
825 }
826 }
827
Pawin Vongmasa36653902018-11-15 00:10:25 -0800828 uint32_t transform = 0;
829 switch (quarters) {
830 case 0: // no rotation
831 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
832 break;
833 case 1: // 90 degrees counter-clockwise
834 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
835 : HAL_TRANSFORM_ROT_270;
836 break;
837 case 2: // 180 degrees
838 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
839 break;
840 case 3: // 90 degrees clockwise
841 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
842 : HAL_TRANSFORM_ROT_90;
843 break;
844 }
845
846 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
847 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
848 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
849 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
850 if (surfaceScaling) {
851 videoScalingMode = surfaceScaling->value;
852 }
853
854 // Use dataspace from format as it has the default aspects already applied
855 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
856 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
857
858 // HDR static info
859 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
860 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
861 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
862
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800863 // HDR10 plus info
864 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
865 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
866 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800867 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
868 hdr10PlusInfo.reset();
869 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800870
Wonsik Kima79c5522022-01-18 16:29:24 -0800871 // HDR dynamic info
872 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
873 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
874 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
875 // TODO: make this sticky & enable unset
876 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
877 hdrDynamicInfo.reset();
878 }
879
880 if (hdr10PlusInfo) {
881 // C2StreamHdr10PlusInfo is deprecated; components should use
882 // C2StreamHdrDynamicMetadataInfo
883 // TODO: #metric
884 if (hdrDynamicInfo) {
885 // It is unexpected that C2StreamHdr10PlusInfo and
886 // C2StreamHdrDynamicMetadataInfo is both present.
887 // C2StreamHdrDynamicMetadataInfo takes priority.
888 // TODO: #metric
889 } else {
890 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
891 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
892 hdr10PlusInfo->flexCount(),
893 0u,
894 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
895 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
896 hdrDynamicInfo = info;
897 }
898 }
899
Pawin Vongmasa36653902018-11-15 00:10:25 -0800900 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
901 if (blocks.size() != 1u) {
902 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
903 return UNKNOWN_ERROR;
904 }
905 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700906 C2Fence c2fence = block.fence();
907 sp<Fence> fence = Fence::NO_FENCE;
908 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
909 // Once C2Fence::type() is added, check the exact C2Fence type
910 if (c2fence.isHW()) {
911 int fenceFd = c2fence.fd();
912 fence = sp<Fence>::make(fenceFd);
913 if (!fence) {
914 ALOGE("[%s] Failed to allocate a fence", mName);
915 close(fenceFd);
916 return NO_MEMORY;
917 }
918 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800919
920 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -0700921 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800922 timestampNs,
923 false, // droppable
924 dataSpace,
925 Rect(blocks.front().crop().left,
926 blocks.front().crop().top,
927 blocks.front().crop().right(),
928 blocks.front().crop().bottom()),
929 videoScalingMode,
930 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700931 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800932 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800933 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800934 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800935 // If mastering max and min luminance fields are 0, do not use them.
936 // It indicates the value may not be present in the stream.
937 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
938 hdrStaticInfo->mastering.minLuminance > 0.0f) {
939 struct android_smpte2086_metadata smpte2086_meta = {
940 .displayPrimaryRed = {
941 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
942 },
943 .displayPrimaryGreen = {
944 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
945 },
946 .displayPrimaryBlue = {
947 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
948 },
949 .whitePoint = {
950 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
951 },
952 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
953 .minLuminance = hdrStaticInfo->mastering.minLuminance,
954 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800955 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800956 hdr.smpte2086 = smpte2086_meta;
957 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700958 // If the content light level fields are 0, do not use them, it
959 // indicates the value may not be present in the stream.
960 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
961 struct android_cta861_3_metadata cta861_meta = {
962 .maxContentLightLevel = hdrStaticInfo->maxCll,
963 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
964 };
965 hdr.validTypes |= HdrMetadata::CTA861_3;
966 hdr.cta8613 = cta861_meta;
967 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900968
969 // does not have valid info
970 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
971 hdrStaticInfo.reset();
972 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800973 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800974 if (hdrDynamicInfo
975 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800976 hdr.validTypes |= HdrMetadata::HDR10PLUS;
977 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800978 hdrDynamicInfo->m.data,
979 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800980 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800981 qbi.setHdrMetadata(hdr);
982 }
Hongguangfc1478a2022-07-20 22:56:06 -0700983 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
984
Brian Lindahl932bf602023-03-09 11:59:48 -0700985 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
986 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
987 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800988 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
989 if (result != OK) {
990 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800991 if (result == NO_INIT) {
992 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
993 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800994 return result;
995 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800996
997 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
998 ALOGD("[%s] queue buffer successful", mName);
999 } else {
1000 ALOGV("[%s] queue buffer successful", mName);
1001 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001002
1003 int64_t mediaTimeUs = 0;
1004 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahld7967a92023-08-10 10:12:49 -06001005 if (mAreRenderMetricsEnabled && mIsSurfaceToDisplay) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001006 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
1007 processRenderedFrames(qbo.frameTimestamps);
1008 } else {
1009 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
1010 // when the frame is queued to the non-display surface
1011 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1012 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001013
1014 return OK;
1015}
1016
Brian Lindahl932bf602023-03-09 11:59:48 -07001017void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001018 mTrackedFrames.clear();
1019
1020 int isSurfaceToDisplay = 0;
1021 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1022 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1023 // No frame tracking is needed if we're not sending frames to the display
1024 if (!mIsSurfaceToDisplay) {
1025 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1026 return;
1027 }
1028
Brian Lindahl932bf602023-03-09 11:59:48 -07001029 int hasPresentFenceTimes = 0;
1030 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1031 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
Brian Lindahl119e0c22023-05-19 15:42:13 -06001032 if (!mHasPresentFenceTimes) {
Brian Lindahl932bf602023-03-09 11:59:48 -07001033 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1034 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001035}
1036
1037void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1038 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1039 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1040 // so track the frame as if the desired render time is now.
1041 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1042 if (desiredRenderTimeNs < nowNs) {
1043 desiredRenderTimeNs = nowNs;
1044 }
Brian Lindahlc8bd9272023-08-28 09:42:43 -06001045
1046 // If the render time is more than a second from now, then pretend the frame is supposed to be
1047 // rendered immediately, because that's what SurfaceFlinger heuristics will do. This is a tight
1048 // coupling, but is really the only way to optimize away unnecessary present fence checks in
1049 // processRenderedFrames.
1050 if (desiredRenderTimeNs > nowNs + 1*1000*1000*1000LL) {
1051 desiredRenderTimeNs = nowNs;
1052 }
1053
Brian Lindahl932bf602023-03-09 11:59:48 -07001054 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1055 // actually rendered.
1056 TrackedFrame frame;
1057 frame.number = qbo.nextFrameNumber - 1;
1058 frame.mediaTimeUs = mediaTimeUs;
1059 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1060 frame.latchTime = -1;
1061 frame.presentFence = nullptr;
1062 mTrackedFrames.push_back(frame);
1063}
1064
1065void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1066 // Grab the latch times and present fences from the frame event deltas
1067 for (const auto& delta : deltas) {
1068 for (auto& frame : mTrackedFrames) {
1069 if (delta.getFrameNumber() == frame.number) {
1070 delta.getLatchTime(&frame.latchTime);
1071 delta.getDisplayPresentFence(&frame.presentFence);
1072 }
1073 }
1074 }
1075
1076 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1077 // in fact, been rendered.
1078 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1079 while (!mTrackedFrames.empty()) {
1080 TrackedFrame & frame = mTrackedFrames.front();
1081 // Frames that should have been rendered at least 100ms in the past are checked
1082 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1083 break;
1084 }
1085
1086 // If we don't have a render time by now, then consider the frame as dropped
1087 int64_t renderTimeNs = getRenderTimeNs(frame);
1088 if (renderTimeNs != -1) {
1089 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1090 }
1091 mTrackedFrames.pop_front();
1092 }
1093}
1094
1095int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1096 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1097 if (!mHasPresentFenceTimes) {
1098 if (frame.latchTime == -1) {
1099 ALOGD("no latch time for frame %d", (int) frame.number);
1100 return -1;
1101 }
1102 return frame.latchTime;
1103 }
1104
1105 if (frame.presentFence == nullptr) {
1106 ALOGW("no present fence for frame %d", (int) frame.number);
1107 return -1;
1108 }
1109
1110 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1111
1112 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1113 ALOGW("invalid signal time for frame %d", (int) frame.number);
1114 return -1;
1115 }
1116
1117 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1118 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1119 return -1;
1120 }
1121
1122 return actualRenderTimeNs;
1123}
1124
1125void CCodecBufferChannel::pollForRenderedBuffers() {
1126 FrameEventHistoryDelta delta;
1127 mComponent->pollForRenderedFrames(&delta);
1128 processRenderedFrames(delta);
1129}
1130
Pawin Vongmasa36653902018-11-15 00:10:25 -08001131status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1132 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1133 bool released = false;
1134 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001135 Mutexed<Input>::Locked input(mInput);
1136 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001137 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001138 }
1139 }
1140 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001141 Mutexed<Output>::Locked output(mOutput);
1142 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001143 released = true;
1144 }
1145 }
1146 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001147 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001148 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001149 } else {
1150 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1151 }
1152 return OK;
1153}
1154
1155void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1156 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001157 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001158
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001159 if (!input->buffers) {
1160 ALOGE("getInputBufferArray: No Input Buffers allocated");
1161 return;
1162 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001163 if (!input->buffers->isArrayMode()) {
1164 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001165 }
1166
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001167 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001168}
1169
1170void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1171 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001172 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001173 if (!output->buffers) {
1174 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1175 return;
1176 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001177 if (!output->buffers->isArrayMode()) {
1178 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001179 }
1180
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001181 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001182}
1183
1184status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001185 const sp<AMessage> &inputFormat,
1186 const sp<AMessage> &outputFormat,
1187 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001188 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1189 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001190 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001191 C2PortReorderBufferDepthTuning::output reorderDepth;
1192 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001193 C2PortActualDelayTuning::input inputDelay(0);
1194 C2PortActualDelayTuning::output outputDelay(0);
1195 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001196 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001197
Pawin Vongmasa36653902018-11-15 00:10:25 -08001198 c2_status_t err = mComponent->query(
1199 {
1200 &iStreamFormat,
1201 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001202 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001203 &reorderDepth,
1204 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001205 &inputDelay,
1206 &pipelineDelay,
1207 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001208 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001209 },
1210 {},
1211 C2_DONT_BLOCK,
1212 nullptr);
1213 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001214 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001215 return UNKNOWN_ERROR;
1216 }
1217 } else if (err != C2_OK) {
1218 return UNKNOWN_ERROR;
1219 }
1220
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001221 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1222 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1223 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1224
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001225 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1226 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001227
Pawin Vongmasa36653902018-11-15 00:10:25 -08001228 // TODO: get this from input format
1229 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1230
Sungtak Lee04b30352020-07-27 13:57:25 -07001231 // secure mode is a static parameter (shall not change in the executing state)
1232 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1233
Pawin Vongmasa36653902018-11-15 00:10:25 -08001234 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001235 int poolMask = GetCodec2PoolMask();
1236 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001237
1238 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001239 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001240 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001241 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1242 API_REFLECTION |
1243 API_VALUES |
1244 API_CURRENT_VALUES |
1245 API_DEPENDENCY |
1246 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001247 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1248 C2StreamSampleRateInfo::input sampleRate(0u);
1249 C2StreamChannelCountInfo::input channelCount(0u);
1250 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001251 std::shared_ptr<C2BlockPool> pool;
1252 {
1253 Mutexed<BlockPools>::Locked pools(mBlockPools);
1254
1255 // set default allocator ID.
1256 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001257 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001258
1259 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1260 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1261 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001262 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001263 std::vector<C2Param *> stackParams({&featuresSetting});
1264 if (audioEncoder) {
1265 stackParams.push_back(&encoderFrameSize);
1266 stackParams.push_back(&sampleRate);
1267 stackParams.push_back(&channelCount);
1268 stackParams.push_back(&pcmEncoding);
1269 } else {
1270 encoderFrameSize.invalidate();
1271 sampleRate.invalidate();
1272 channelCount.invalidate();
1273 pcmEncoding.invalidate();
1274 }
1275 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001276 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1277 C2_DONT_BLOCK,
1278 &params);
1279 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1280 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1281 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001282 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001283 C2PortAllocatorsTuning::input *inputAllocators =
1284 C2PortAllocatorsTuning::input::From(params[0].get());
1285 if (inputAllocators && inputAllocators->flexCount() > 0) {
1286 std::shared_ptr<C2Allocator> allocator;
1287 // verify allocator IDs and resolve default allocator
1288 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1289 if (allocator) {
1290 pools->inputAllocatorId = allocator->getId();
1291 } else {
1292 ALOGD("[%s] component requested invalid input allocator ID %u",
1293 mName, inputAllocators->m.values[0]);
1294 }
1295 }
1296 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001297 if (featuresSetting) {
1298 apiFeatures = featuresSetting.value;
1299 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001300
1301 // TODO: use C2Component wrapper to associate this pool with ourselves
1302 if ((poolMask >> pools->inputAllocatorId) & 1) {
1303 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1304 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1305 mName, pools->inputAllocatorId,
1306 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1307 asString(err), err);
1308 } else {
1309 err = C2_NOT_FOUND;
1310 }
1311 if (err != C2_OK) {
1312 C2BlockPool::local_id_t inputPoolId =
1313 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1314 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1315 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1316 mName, (unsigned long long)inputPoolId,
1317 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1318 asString(err), err);
1319 if (err != C2_OK) {
1320 return NO_MEMORY;
1321 }
1322 }
1323 pools->inputPool = pool;
1324 }
1325
Wonsik Kim51051262018-11-28 13:59:05 -08001326 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001327 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001328 input->inputDelay = inputDelayValue;
1329 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001330 input->numSlots = numInputSlots;
1331 input->extraBuffers.flush();
1332 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001333 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001334 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1335 input->frameReassembler.init(
1336 pool,
1337 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1338 encoderFrameSize.value,
1339 sampleRate.value,
1340 channelCount.value,
1341 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1342 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001343 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1344 // For encrypted content, framework decrypts source buffer (ashmem) into
1345 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001346 if (!buffersBoundToCodec
1347 && !input->frameReassembler
1348 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001349 input->buffers.reset(new SlotInputBuffers(mName));
1350 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001351 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001352 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001353 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001354 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001355 // This is to ensure buffers do not get released prematurely.
1356 // TODO: handle this without going into array mode
1357 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001358 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001359 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001360 }
1361 } else {
1362 if (hasCryptoOrDescrambler()) {
1363 int32_t capacity = kLinearBufferSize;
1364 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1365 if ((size_t)capacity > kMaxLinearBufferSize) {
1366 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1367 capacity = kMaxLinearBufferSize;
1368 }
1369 if (mDealer == nullptr) {
1370 mDealer = new MemoryDealer(
1371 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001372 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001373 "EncryptedLinearInputBuffers");
1374 mDecryptDestination = mDealer->allocate((size_t)capacity);
1375 }
1376 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001377 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1378 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001379 } else {
1380 mHeapSeqNum = -1;
1381 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001382 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001383 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001384 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001385 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001386 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001387 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001388 }
1389 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001390 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001391
1392 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001393 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 } else {
1395 // TODO: error
1396 }
Wonsik Kim51051262018-11-28 13:59:05 -08001397
1398 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001399 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001400 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001401 }
1402
1403 if (outputFormat != nullptr) {
1404 sp<IGraphicBufferProducer> outputSurface;
1405 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001406 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001407 {
1408 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001409 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001410 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001411 outputSurface = output->surface ?
1412 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001413 if (outputSurface) {
1414 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1415 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001416 outputGeneration = output->generation;
1417 }
1418
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001419 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001420 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001421 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001422
1423 {
1424 Mutexed<BlockPools>::Locked pools(mBlockPools);
1425
David Stevensc3fbb282021-01-18 18:11:20 +09001426 prevOutputPoolId = pools->outputPoolId;
1427
Pawin Vongmasa36653902018-11-15 00:10:25 -08001428 // set default allocator ID.
1429 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001430 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001431
1432 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1433 // unsuccessful.
1434 std::vector<std::unique_ptr<C2Param>> params;
1435 err = mComponent->query({ },
1436 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1437 C2_DONT_BLOCK,
1438 &params);
1439 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1440 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1441 mName, params.size(), asString(err), err);
1442 } else if (err == C2_OK && params.size() == 1) {
1443 C2PortAllocatorsTuning::output *outputAllocators =
1444 C2PortAllocatorsTuning::output::From(params[0].get());
1445 if (outputAllocators && outputAllocators->flexCount() > 0) {
1446 std::shared_ptr<C2Allocator> allocator;
1447 // verify allocator IDs and resolve default allocator
1448 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1449 if (allocator) {
1450 pools->outputAllocatorId = allocator->getId();
1451 } else {
1452 ALOGD("[%s] component requested invalid output allocator ID %u",
1453 mName, outputAllocators->m.values[0]);
1454 }
1455 }
1456 }
1457
1458 // use bufferqueue if outputting to a surface.
1459 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1460 // if unsuccessful.
1461 if (outputSurface) {
1462 params.clear();
1463 err = mComponent->query({ },
1464 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1465 C2_DONT_BLOCK,
1466 &params);
1467 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1468 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1469 mName, params.size(), asString(err), err);
1470 } else if (err == C2_OK && params.size() == 1) {
1471 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1472 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1473 if (surfaceAllocator) {
1474 std::shared_ptr<C2Allocator> allocator;
1475 // verify allocator IDs and resolve default allocator
1476 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1477 if (allocator) {
1478 pools->outputAllocatorId = allocator->getId();
1479 } else {
1480 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1481 mName, surfaceAllocator->value);
1482 err = C2_BAD_VALUE;
1483 }
1484 }
1485 }
1486 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1487 && err != C2_OK
1488 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1489 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1490 }
1491 }
1492
1493 if ((poolMask >> pools->outputAllocatorId) & 1) {
1494 err = mComponent->createBlockPool(
1495 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1496 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1497 mName, pools->outputAllocatorId,
1498 (unsigned long long)pools->outputPoolId,
1499 asString(err));
1500 } else {
1501 err = C2_NOT_FOUND;
1502 }
1503 if (err != C2_OK) {
1504 // use basic pool instead
1505 pools->outputPoolId =
1506 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1507 }
1508
1509 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1510 // component.
1511 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1512 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1513
1514 std::vector<std::unique_ptr<C2SettingResult>> failures;
1515 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1516 ALOGD("[%s] Configured output block pool ids %llu => %s",
1517 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1518 outputPoolId_ = pools->outputPoolId;
1519 }
1520
David Stevensc3fbb282021-01-18 18:11:20 +09001521 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1522 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1523 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1524 if (err != C2_OK) {
1525 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1526 (unsigned long long) prevOutputPoolId, asString(err), err);
1527 }
1528 }
1529
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001530 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001531 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001532 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001533 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001534 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001535 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001536 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001537 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001538 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001539 }
1540 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001541 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001542 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001543 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001544
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001545 output->buffers->clearStash();
1546 if (reorderDepth) {
1547 output->buffers->setReorderDepth(reorderDepth.value);
1548 }
1549 if (reorderKey) {
1550 output->buffers->setReorderKey(reorderKey.value);
1551 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001552
1553 // Try to set output surface to created block pool if given.
1554 if (outputSurface) {
1555 mComponent->setOutputSurface(
1556 outputPoolId_,
1557 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001558 outputGeneration,
1559 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001560 } else {
1561 // configure CPU read consumer usage
1562 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1563 std::vector<std::unique_ptr<C2SettingResult>> failures;
1564 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1565 // do not print error message for now as most components may not yet
1566 // support this setting
1567 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1568 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001569 }
1570
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001571 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001572 if (buffersBoundToCodec) {
1573 // WORKAROUND: if we're using early CSD workaround we convert to
1574 // array mode, to appease apps assuming the output
1575 // buffers to be of the same size.
1576 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1577 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001578
1579 int32_t channelCount;
1580 int32_t sampleRate;
1581 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1582 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1583 int32_t delay = 0;
1584 int32_t padding = 0;;
1585 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1586 delay = 0;
1587 }
1588 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1589 padding = 0;
1590 }
1591 if (delay || padding) {
1592 // We need write access to the buffers, and we're already in
1593 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001594 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001595 }
1596 }
1597 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001598
1599 int32_t tunneled = 0;
1600 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1601 tunneled = 0;
1602 }
1603 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001604 }
1605
1606 // Set up pipeline control. This has to be done after mInputBuffers and
1607 // mOutputBuffers are initialized to make sure that lingering callbacks
1608 // about buffers from the previous generation do not interfere with the
1609 // newly initialized pipeline capacity.
1610
Wonsik Kim62545252021-01-20 11:25:41 -08001611 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001612 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001613 watcher->inputDelay(inputDelayValue)
1614 .pipelineDelay(pipelineDelayValue)
1615 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001616 .smoothnessFactor(kSmoothnessFactor);
1617 watcher->flush();
1618 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001619
1620 mInputMetEos = false;
1621 mSync.start();
1622 return OK;
1623}
1624
Wonsik Kim34b28b42022-05-20 15:49:32 -07001625status_t CCodecBufferChannel::prepareInitialInputBuffers(
1626 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001627 if (mInputSurface) {
1628 return OK;
1629 }
1630
Wonsik Kim34b28b42022-05-20 15:49:32 -07001631 size_t numInputSlots = mInput.lock()->numSlots;
1632
1633 {
1634 Mutexed<Input>::Locked input(mInput);
1635 while (clientInputBuffers->size() < numInputSlots) {
1636 size_t index;
1637 sp<MediaCodecBuffer> buffer;
1638 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1639 break;
1640 }
1641 clientInputBuffers->emplace(index, buffer);
1642 }
1643 }
1644 if (clientInputBuffers->empty()) {
1645 ALOGW("[%s] start: cannot allocate memory at all", mName);
1646 return NO_MEMORY;
1647 } else if (clientInputBuffers->size() < numInputSlots) {
1648 ALOGD("[%s] start: cannot allocate memory for all slots, "
1649 "only %zu buffers allocated",
1650 mName, clientInputBuffers->size());
1651 } else {
1652 ALOGV("[%s] %zu initial input buffers available",
1653 mName, clientInputBuffers->size());
1654 }
1655 return OK;
1656}
1657
1658status_t CCodecBufferChannel::requestInitialInputBuffers(
1659 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001660 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001661 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1662 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1663 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001664 return UNKNOWN_ERROR;
1665 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001666
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001667 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1668 mFlushedConfigs.lock()->swap(flushedConfigs);
1669 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001670 {
1671 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1672 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1673 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1674 watcher->onWorkQueued(
1675 work->input.ordinal.frameIndex.peeku(),
1676 std::vector(work->input.buffers),
1677 now);
1678 }
1679 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001680 err = mComponent->queue(&flushedConfigs);
1681 if (err != C2_OK) {
1682 ALOGW("[%s] Error while queueing a flushed config", mName);
1683 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001684 }
1685 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001686 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001687 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1688 !clientInputBuffers.empty()) {
1689 size_t minIndex = clientInputBuffers.begin()->first;
1690 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1691 for (const auto &[index, buffer] : clientInputBuffers) {
1692 if (minBuffer->capacity() > buffer->capacity()) {
1693 minIndex = index;
1694 minBuffer = buffer;
1695 }
1696 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001697 // WORKAROUND: Some apps expect CSD available without queueing
1698 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001699 minBuffer->setRange(0, 0);
1700 minBuffer->meta()->clear();
1701 minBuffer->meta()->setInt64("timeUs", 0);
1702 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001703 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1704 mName);
1705 return UNKNOWN_ERROR;
1706 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001707 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001708 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001709
Wonsik Kim34b28b42022-05-20 15:49:32 -07001710 for (const auto &[index, buffer] : clientInputBuffers) {
1711 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001712 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001713
Pawin Vongmasa36653902018-11-15 00:10:25 -08001714 return OK;
1715}
1716
1717void CCodecBufferChannel::stop() {
1718 mSync.stop();
1719 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001720}
1721
Sungtak Lee99144332023-01-26 11:03:14 +00001722void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
1723 sp<Surface> surface = mOutputSurface.lock()->surface;
1724 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00001725 C2BlockPool::local_id_t outputPoolId;
1726 {
1727 Mutexed<BlockPools>::Locked pools(mBlockPools);
1728 outputPoolId = pools->outputPoolId;
1729 }
1730 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00001731
1732 if (pushBlankBuffer) {
1733 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
1734 if (anw) {
1735 pushBlankBuffersToNativeWindow(anw.get());
1736 }
1737 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00001738 }
1739}
1740
Wonsik Kim936a89c2020-05-08 16:07:50 -07001741void CCodecBufferChannel::reset() {
1742 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001743 if (mInputSurface != nullptr) {
1744 mInputSurface.reset();
1745 }
1746 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001747 {
1748 Mutexed<Input>::Locked input(mInput);
1749 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001750 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001751 }
1752 {
1753 Mutexed<Output>::Locked output(mOutput);
1754 output->buffers.reset();
1755 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001756 // reset the frames that are being tracked for onFrameRendered callbacks
1757 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001758}
1759
1760void CCodecBufferChannel::release() {
1761 mComponent.reset();
1762 mInputAllocator.reset();
1763 mOutputSurface.lock()->surface.clear();
1764 {
1765 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1766 blockPools->inputPool.reset();
1767 blockPools->outputPoolIntf.reset();
1768 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001769 setCrypto(nullptr);
1770 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001771}
1772
Pawin Vongmasa36653902018-11-15 00:10:25 -08001773void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1774 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001775 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001776 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001777 {
1778 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1779 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1780 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1781 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1782 watcher->onWorkDone(frameIndex);
1783 continue;
1784 }
1785 if (work->input.buffers.empty()
1786 || work->input.buffers.front() == nullptr
1787 || work->input.buffers.front()->data().linearBlocks().empty()) {
1788 ALOGD("[%s] no linear codec config data found", mName);
1789 watcher->onWorkDone(frameIndex);
1790 continue;
1791 }
1792 std::unique_ptr<C2Work> copy(new C2Work);
1793 copy->input.flags = C2FrameData::flags_t(
1794 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1795 copy->input.ordinal = work->input.ordinal;
1796 copy->input.ordinal.frameIndex = mFrameIndex++;
1797 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1798 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1799 }
1800 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1801 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1802 }
1803 copy->input.infoBuffers.insert(
1804 copy->input.infoBuffers.begin(),
1805 work->input.infoBuffers.begin(),
1806 work->input.infoBuffers.end());
1807 copy->worklets.emplace_back(new C2Worklet);
1808 configs.push_back(std::move(copy));
1809 watcher->onWorkDone(frameIndex);
1810 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001811 }
1812 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001813 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001814 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001815 Mutexed<Input>::Locked input(mInput);
1816 input->buffers->flush();
1817 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001818 }
1819 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001820 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001821 if (output->buffers) {
1822 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001823 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001824 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001825 }
1826}
1827
1828void CCodecBufferChannel::onWorkDone(
1829 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001830 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001831 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001832 feedInputBufferIfAvailable();
1833 }
1834}
1835
1836void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001837 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001838 if (mInputSurface) {
1839 return;
1840 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001841 std::shared_ptr<C2Buffer> buffer =
1842 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001843 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001844 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001845 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001846 if (input->lastFlushIndex >= frameIndex) {
1847 ALOGD("[%s] Ignoring stale input buffer done callback: "
1848 "last flush index = %lld, frameIndex = %lld",
1849 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1850 } else {
1851 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1852 if (!newInputSlotAvailable) {
1853 (void)input->extraBuffers.expireComponentBuffer(buffer);
1854 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001855 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001856 }
1857 if (newInputSlotAvailable) {
1858 feedInputBufferIfAvailable();
1859 }
1860}
1861
1862bool CCodecBufferChannel::handleWork(
1863 std::unique_ptr<C2Work> work,
1864 const sp<AMessage> &outputFormat,
1865 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001866 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001867 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001868 if (!output->buffers) {
1869 return false;
1870 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001871 }
1872
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001873 // Whether the output buffer should be reported to the client or not.
1874 bool notifyClient = false;
1875
1876 if (work->result == C2_OK){
1877 notifyClient = true;
1878 } else if (work->result == C2_NOT_FOUND) {
1879 ALOGD("[%s] flushed work; ignored.", mName);
1880 } else {
1881 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1882 // the config update.
1883 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1884 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1885 return false;
1886 }
1887
1888 if ((work->input.ordinal.frameIndex -
1889 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001890 // Discard frames from previous generation.
1891 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001892 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001893 }
1894
Wonsik Kim524b0582019-03-12 11:28:57 -07001895 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001896 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001897 || !(work->worklets.front()->output.flags &
1898 C2FrameData::FLAG_INCOMPLETE))) {
1899 mPipelineWatcher.lock()->onWorkDone(
1900 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001901 }
1902
1903 // NOTE: MediaCodec usage supposedly have only one worklet
1904 if (work->worklets.size() != 1u) {
1905 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1906 mName, work->worklets.size());
1907 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1908 return false;
1909 }
1910
1911 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1912
1913 std::shared_ptr<C2Buffer> buffer;
1914 // NOTE: MediaCodec usage supposedly have only one output stream.
1915 if (worklet->output.buffers.size() > 1u) {
1916 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1917 mName, worklet->output.buffers.size());
1918 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1919 return false;
1920 } else if (worklet->output.buffers.size() == 1u) {
1921 buffer = worklet->output.buffers[0];
1922 if (!buffer) {
1923 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1924 }
1925 }
1926
Wonsik Kim3dedf682021-05-03 10:57:09 -07001927 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1928 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001929 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001930 while (!worklet->output.configUpdate.empty()) {
1931 std::unique_ptr<C2Param> param;
1932 worklet->output.configUpdate.back().swap(param);
1933 worklet->output.configUpdate.pop_back();
1934 switch (param->coreIndex().coreIndex()) {
1935 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1936 C2PortReorderBufferDepthTuning::output reorderDepth;
1937 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001938 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1939 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001940 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001941 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001942 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001943 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1944 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001945 }
1946 break;
1947 }
1948 case C2PortReorderKeySetting::CORE_INDEX: {
1949 C2PortReorderKeySetting::output reorderKey;
1950 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001951 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001952 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1953 mName, reorderKey.value);
1954 } else {
1955 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1956 }
1957 break;
1958 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001959 case C2PortActualDelayTuning::CORE_INDEX: {
1960 if (param->isGlobal()) {
1961 C2ActualPipelineDelayTuning pipelineDelay;
1962 if (pipelineDelay.updateFrom(*param)) {
1963 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1964 mName, pipelineDelay.value);
1965 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001966 (void)mPipelineWatcher.lock()->pipelineDelay(
1967 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001968 }
1969 }
1970 if (param->forInput()) {
1971 C2PortActualDelayTuning::input inputDelay;
1972 if (inputDelay.updateFrom(*param)) {
1973 ALOGV("[%s] onWorkDone: updating input delay %u",
1974 mName, inputDelay.value);
1975 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001976 (void)mPipelineWatcher.lock()->inputDelay(
1977 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001978 }
1979 }
1980 if (param->forOutput()) {
1981 C2PortActualDelayTuning::output outputDelay;
1982 if (outputDelay.updateFrom(*param)) {
1983 ALOGV("[%s] onWorkDone: updating output delay %u",
1984 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001985 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001986 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001987 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001988
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001989 }
1990 }
1991 break;
1992 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001993 case C2PortTunnelSystemTime::CORE_INDEX: {
1994 C2PortTunnelSystemTime::output frameRenderTime;
1995 if (frameRenderTime.updateFrom(*param)) {
1996 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1997 mName, (long long)frameRenderTime.value,
1998 (long long)worklet->output.ordinal.timestamp.peekll());
1999 mCCodecCallback->onOutputFramesRendered(
2000 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
2001 }
2002 break;
2003 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02002004 case C2StreamTunnelHoldRender::CORE_INDEX: {
2005 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
2006 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
2007 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
2008 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
2009 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
2010 mCCodecCallback->onFirstTunnelFrameReady();
2011 break;
2012 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002013 default:
2014 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2015 mName, param->index());
2016 break;
2017 }
2018 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002019 if (newInputDelay || newPipelineDelay) {
2020 Mutexed<Input>::Locked input(mInput);
2021 size_t newNumSlots =
2022 newInputDelay.value_or(input->inputDelay) +
2023 newPipelineDelay.value_or(input->pipelineDelay) +
2024 kSmoothnessFactor;
2025 if (input->buffers->isArrayMode()) {
2026 if (input->numSlots >= newNumSlots) {
2027 input->numExtraSlots = 0;
2028 } else {
2029 input->numExtraSlots = newNumSlots - input->numSlots;
2030 }
2031 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2032 mName, input->numExtraSlots);
2033 } else {
2034 input->numSlots = newNumSlots;
2035 }
2036 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002037 size_t numOutputSlots = 0;
2038 uint32_t reorderDepth = 0;
2039 bool outputBuffersChanged = false;
2040 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2041 Mutexed<Output>::Locked output(mOutput);
2042 if (!output->buffers) {
2043 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002044 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002045 numOutputSlots = output->numSlots;
2046 if (newReorderKey) {
2047 output->buffers->setReorderKey(newReorderKey.value());
2048 }
2049 if (newReorderDepth) {
2050 output->buffers->setReorderDepth(newReorderDepth.value());
2051 }
2052 reorderDepth = output->buffers->getReorderDepth();
2053 if (newOutputDelay) {
2054 output->outputDelay = newOutputDelay.value();
2055 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2056 if (output->numSlots < numOutputSlots) {
2057 output->numSlots = numOutputSlots;
2058 if (output->buffers->isArrayMode()) {
2059 OutputBuffersArray *array =
2060 (OutputBuffersArray *)output->buffers.get();
2061 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2062 mName, numOutputSlots);
2063 array->grow(numOutputSlots);
2064 outputBuffersChanged = true;
2065 }
2066 }
2067 }
2068 numOutputSlots = output->numSlots;
2069 }
2070 if (outputBuffersChanged) {
2071 mCCodecCallback->onOutputBuffersChanged();
2072 }
2073 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002074 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002075 {
2076 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2077 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002078 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002079 if (output->surface) {
2080 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2081 }
2082 }
2083 if (maxDequeueCount > 0) {
2084 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002085 }
2086 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002087
Pawin Vongmasa36653902018-11-15 00:10:25 -08002088 int32_t flags = 0;
2089 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002090 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002091 ALOGV("[%s] onWorkDone: output EOS", mName);
2092 }
2093
Pawin Vongmasa36653902018-11-15 00:10:25 -08002094 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2095 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2096 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2097 // shall correspond to the client input timesamp (in customOrdinal). By using the
2098 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2099 // produces multiple output.
2100 c2_cntr64_t timestamp =
2101 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2102 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002103 if (mInputSurface != nullptr) {
2104 // When using input surface we need to restore the original input timestamp.
2105 timestamp = work->input.ordinal.customOrdinal;
2106 }
My Name6bd9a7d2022-03-25 12:37:58 -07002107 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2108 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002109 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2110 mName,
2111 work->input.ordinal.customOrdinal.peekll(),
2112 work->input.ordinal.timestamp.peekll(),
2113 worklet->output.ordinal.timestamp.peekll(),
2114 timestamp.peekll());
2115
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002116 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002117 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002118 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002119 if (!output->buffers) {
2120 return false;
2121 }
2122 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002123 output->buffers->updateSkipCutBuffer(outputFormat);
2124 output->buffers->setFormat(outputFormat);
2125 }
2126 if (!notifyClient) {
2127 return false;
2128 }
2129 size_t index;
2130 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002131 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002132 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002133 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002134 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2135
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002136 // TRICKY: we want popped buffers reported in order, so sending
2137 // the callback while holding the lock here. This assumes that
2138 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2139 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002140 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002141 } else {
2142 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002143 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002144 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002145 return false;
2146 }
2147 }
2148
Wonsik Kimec585c32021-10-01 01:11:00 -07002149 bool drop = false;
2150 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2151 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2152 drop = true;
2153 }
2154
Marc Kassisec910342022-11-25 11:43:05 +01002155 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2156 // HAL, the flag is then removed in the corresponding output buffer.
2157 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2158 flags |= BUFFER_FLAG_DECODE_ONLY;
2159 }
2160
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002161 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002162 if (mTunneled && drop && outputFormat) {
2163 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2164 mName, work->input.ordinal.frameIndex.peekull());
2165 } else {
2166 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2167 mName, work->input.ordinal.frameIndex.peekull());
2168 notifyClient = false;
2169 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002170 }
2171
2172 if (buffer) {
2173 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2174 // TODO: properly translate these to metadata
2175 switch (info->coreIndex().coreIndex()) {
2176 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002177 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002178 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002179 }
2180 break;
2181 default:
2182 break;
2183 }
2184 }
2185 }
2186
2187 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002188 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002189 if (!output->buffers) {
2190 return false;
2191 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002192 output->buffers->pushToStash(
2193 buffer,
2194 notifyClient,
2195 timestamp.peek(),
2196 flags,
2197 outputFormat,
2198 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002199 }
2200 sendOutputBuffers();
2201 return true;
2202}
2203
2204void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002205 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002206 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002207 sp<MediaCodecBuffer> outBuffer;
2208 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002209
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002210 constexpr int kMaxReallocTry = 5;
2211 int reallocTryNum = 0;
2212
Pawin Vongmasa36653902018-11-15 00:10:25 -08002213 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002214 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002215 if (!output->buffers) {
2216 return;
2217 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002218 action = output->buffers->popFromStashAndRegister(
2219 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002220 if (action != OutputBuffers::REALLOCATE) {
2221 reallocTryNum = 0;
2222 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002223 switch (action) {
2224 case OutputBuffers::SKIP:
2225 return;
2226 case OutputBuffers::DISCARD:
2227 break;
2228 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002229 // TRICKY: we want popped buffers reported in order, so sending
2230 // the callback while holding the lock here. This assumes that
2231 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2232 // callbacks are always sent with the Output lock held.
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002233 mCallback->onOutputBufferAvailable(index, outBuffer);
2234 break;
2235 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002236 if (++reallocTryNum > kMaxReallocTry) {
2237 output.unlock();
2238 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2239 mName, kMaxReallocTry);
2240 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2241 return;
2242 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002243 if (!output->buffers->isArrayMode()) {
2244 output->buffers =
2245 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002246 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002247 static_cast<OutputBuffersArray*>(output->buffers.get())->
2248 realloc(c2Buffer);
2249 output.unlock();
2250 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002251 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002252 case OutputBuffers::RETRY:
2253 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2254 mName);
2255 return;
2256 default:
2257 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2258 "corrupted BufferAction value (%d) "
2259 "returned from popFromStashAndRegister.",
2260 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002261 return;
2262 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002263 }
2264}
2265
Sungtak Lee99144332023-01-26 11:03:14 +00002266status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002267 static std::atomic_uint32_t surfaceGeneration{0};
2268 uint32_t generation = (getpid() << 10) |
2269 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2270 & ((1 << 10) - 1));
2271
2272 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002273 int maxDequeueCount;
2274 sp<Surface> oldSurface;
2275 {
2276 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2277 maxDequeueCount = outputSurface->maxDequeueBuffers;
2278 oldSurface = outputSurface->surface;
2279 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002280 if (newSurface) {
2281 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002282 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002283 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002284 producer = newSurface->getIGraphicBufferProducer();
2285 producer->setGenerationNumber(generation);
2286 } else {
2287 ALOGE("[%s] setting output surface to null", mName);
2288 return INVALID_OPERATION;
2289 }
2290
2291 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2292 C2BlockPool::local_id_t outputPoolId;
2293 {
2294 Mutexed<BlockPools>::Locked pools(mBlockPools);
2295 outputPoolId = pools->outputPoolId;
2296 outputPoolIntf = pools->outputPoolIntf;
2297 }
2298
2299 if (outputPoolIntf) {
2300 if (mComponent->setOutputSurface(
2301 outputPoolId,
2302 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002303 generation,
2304 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002305 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2306 return INVALID_OPERATION;
2307 }
2308 }
2309
2310 {
2311 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2312 output->surface = newSurface;
2313 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002314 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002315 }
2316
Sungtak Lee99144332023-01-26 11:03:14 +00002317 if (oldSurface && pushBlankBuffer) {
2318 // When ReleaseSurface was set from MediaCodec,
2319 // pushing a blank buffer at the end might be necessary.
2320 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2321 if (anw) {
2322 pushBlankBuffersToNativeWindow(anw.get());
2323 }
2324 }
2325
Pawin Vongmasa36653902018-11-15 00:10:25 -08002326 return OK;
2327}
2328
Wonsik Kimab34ed62019-01-31 15:28:46 -08002329PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002330 // Otherwise, component may have stalled work due to input starvation up to
2331 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002332 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2333 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002334 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002335 size_t outputDelay = mOutput.lock()->outputDelay;
2336 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002337 Mutexed<Input>::Locked input(mInput);
2338 n = input->inputDelay + input->pipelineDelay + outputDelay;
2339 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002340 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002341}
2342
Pawin Vongmasa36653902018-11-15 00:10:25 -08002343void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2344 mMetaMode = mode;
2345}
2346
Wonsik Kim596187e2019-10-25 12:44:10 -07002347void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002348 if (mCrypto != nullptr) {
2349 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2350 mCrypto->unsetHeap(entry.second);
2351 }
2352 mHeapSeqNumMap.clear();
2353 if (mHeapSeqNum >= 0) {
2354 mCrypto->unsetHeap(mHeapSeqNum);
2355 mHeapSeqNum = -1;
2356 }
2357 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002358 mCrypto = crypto;
2359}
2360
2361void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2362 mDescrambler = descrambler;
2363}
2364
Pawin Vongmasa36653902018-11-15 00:10:25 -08002365status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2366 // C2_OK is always translated to OK.
2367 if (c2s == C2_OK) {
2368 return OK;
2369 }
2370
2371 // Operation-dependent translation
2372 // TODO: Add as necessary
2373 switch (c2op) {
2374 case C2_OPERATION_Component_start:
2375 switch (c2s) {
2376 case C2_NO_MEMORY:
2377 return NO_MEMORY;
2378 default:
2379 return UNKNOWN_ERROR;
2380 }
2381 default:
2382 break;
2383 }
2384
2385 // Backup operation-agnostic translation
2386 switch (c2s) {
2387 case C2_BAD_INDEX:
2388 return BAD_INDEX;
2389 case C2_BAD_VALUE:
2390 return BAD_VALUE;
2391 case C2_BLOCKING:
2392 return WOULD_BLOCK;
2393 case C2_DUPLICATE:
2394 return ALREADY_EXISTS;
2395 case C2_NO_INIT:
2396 return NO_INIT;
2397 case C2_NO_MEMORY:
2398 return NO_MEMORY;
2399 case C2_NOT_FOUND:
2400 return NAME_NOT_FOUND;
2401 case C2_TIMED_OUT:
2402 return TIMED_OUT;
2403 case C2_BAD_STATE:
2404 case C2_CANCELED:
2405 case C2_CANNOT_DO:
2406 case C2_CORRUPTED:
2407 case C2_OMITTED:
2408 case C2_REFUSED:
2409 return UNKNOWN_ERROR;
2410 default:
2411 return -static_cast<status_t>(c2s);
2412 }
2413}
2414
Pawin Vongmasa36653902018-11-15 00:10:25 -08002415} // namespace android