blob: feca03dde937c46cb37bf0b9290aea932636c61b [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 }
1045 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1046 // actually rendered.
1047 TrackedFrame frame;
1048 frame.number = qbo.nextFrameNumber - 1;
1049 frame.mediaTimeUs = mediaTimeUs;
1050 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1051 frame.latchTime = -1;
1052 frame.presentFence = nullptr;
1053 mTrackedFrames.push_back(frame);
1054}
1055
1056void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1057 // Grab the latch times and present fences from the frame event deltas
1058 for (const auto& delta : deltas) {
1059 for (auto& frame : mTrackedFrames) {
1060 if (delta.getFrameNumber() == frame.number) {
1061 delta.getLatchTime(&frame.latchTime);
1062 delta.getDisplayPresentFence(&frame.presentFence);
1063 }
1064 }
1065 }
1066
1067 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1068 // in fact, been rendered.
1069 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1070 while (!mTrackedFrames.empty()) {
1071 TrackedFrame & frame = mTrackedFrames.front();
1072 // Frames that should have been rendered at least 100ms in the past are checked
1073 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1074 break;
1075 }
1076
1077 // If we don't have a render time by now, then consider the frame as dropped
1078 int64_t renderTimeNs = getRenderTimeNs(frame);
1079 if (renderTimeNs != -1) {
1080 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1081 }
1082 mTrackedFrames.pop_front();
1083 }
1084}
1085
1086int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1087 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1088 if (!mHasPresentFenceTimes) {
1089 if (frame.latchTime == -1) {
1090 ALOGD("no latch time for frame %d", (int) frame.number);
1091 return -1;
1092 }
1093 return frame.latchTime;
1094 }
1095
1096 if (frame.presentFence == nullptr) {
1097 ALOGW("no present fence for frame %d", (int) frame.number);
1098 return -1;
1099 }
1100
1101 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1102
1103 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1104 ALOGW("invalid signal time for frame %d", (int) frame.number);
1105 return -1;
1106 }
1107
1108 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1109 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1110 return -1;
1111 }
1112
1113 return actualRenderTimeNs;
1114}
1115
1116void CCodecBufferChannel::pollForRenderedBuffers() {
1117 FrameEventHistoryDelta delta;
1118 mComponent->pollForRenderedFrames(&delta);
1119 processRenderedFrames(delta);
1120}
1121
Pawin Vongmasa36653902018-11-15 00:10:25 -08001122status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1123 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1124 bool released = false;
1125 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001126 Mutexed<Input>::Locked input(mInput);
1127 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001128 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001129 }
1130 }
1131 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001132 Mutexed<Output>::Locked output(mOutput);
1133 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001134 released = true;
1135 }
1136 }
1137 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001138 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001139 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001140 } else {
1141 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1142 }
1143 return OK;
1144}
1145
1146void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1147 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001148 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001149
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001150 if (!input->buffers) {
1151 ALOGE("getInputBufferArray: No Input Buffers allocated");
1152 return;
1153 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001154 if (!input->buffers->isArrayMode()) {
1155 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001156 }
1157
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001158 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001159}
1160
1161void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1162 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001163 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001164 if (!output->buffers) {
1165 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1166 return;
1167 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001168 if (!output->buffers->isArrayMode()) {
1169 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001170 }
1171
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001172 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001173}
1174
1175status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001176 const sp<AMessage> &inputFormat,
1177 const sp<AMessage> &outputFormat,
1178 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001179 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1180 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001181 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001182 C2PortReorderBufferDepthTuning::output reorderDepth;
1183 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001184 C2PortActualDelayTuning::input inputDelay(0);
1185 C2PortActualDelayTuning::output outputDelay(0);
1186 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001187 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001188
Pawin Vongmasa36653902018-11-15 00:10:25 -08001189 c2_status_t err = mComponent->query(
1190 {
1191 &iStreamFormat,
1192 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001193 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001194 &reorderDepth,
1195 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001196 &inputDelay,
1197 &pipelineDelay,
1198 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001199 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001200 },
1201 {},
1202 C2_DONT_BLOCK,
1203 nullptr);
1204 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001205 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001206 return UNKNOWN_ERROR;
1207 }
1208 } else if (err != C2_OK) {
1209 return UNKNOWN_ERROR;
1210 }
1211
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001212 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1213 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1214 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1215
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001216 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1217 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001218
Pawin Vongmasa36653902018-11-15 00:10:25 -08001219 // TODO: get this from input format
1220 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1221
Sungtak Lee04b30352020-07-27 13:57:25 -07001222 // secure mode is a static parameter (shall not change in the executing state)
1223 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1224
Pawin Vongmasa36653902018-11-15 00:10:25 -08001225 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001226 int poolMask = GetCodec2PoolMask();
1227 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001228
1229 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001230 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001231 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001232 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1233 API_REFLECTION |
1234 API_VALUES |
1235 API_CURRENT_VALUES |
1236 API_DEPENDENCY |
1237 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001238 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1239 C2StreamSampleRateInfo::input sampleRate(0u);
1240 C2StreamChannelCountInfo::input channelCount(0u);
1241 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001242 std::shared_ptr<C2BlockPool> pool;
1243 {
1244 Mutexed<BlockPools>::Locked pools(mBlockPools);
1245
1246 // set default allocator ID.
1247 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001248 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001249
1250 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1251 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1252 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001253 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001254 std::vector<C2Param *> stackParams({&featuresSetting});
1255 if (audioEncoder) {
1256 stackParams.push_back(&encoderFrameSize);
1257 stackParams.push_back(&sampleRate);
1258 stackParams.push_back(&channelCount);
1259 stackParams.push_back(&pcmEncoding);
1260 } else {
1261 encoderFrameSize.invalidate();
1262 sampleRate.invalidate();
1263 channelCount.invalidate();
1264 pcmEncoding.invalidate();
1265 }
1266 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001267 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1268 C2_DONT_BLOCK,
1269 &params);
1270 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1271 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1272 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001273 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001274 C2PortAllocatorsTuning::input *inputAllocators =
1275 C2PortAllocatorsTuning::input::From(params[0].get());
1276 if (inputAllocators && inputAllocators->flexCount() > 0) {
1277 std::shared_ptr<C2Allocator> allocator;
1278 // verify allocator IDs and resolve default allocator
1279 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1280 if (allocator) {
1281 pools->inputAllocatorId = allocator->getId();
1282 } else {
1283 ALOGD("[%s] component requested invalid input allocator ID %u",
1284 mName, inputAllocators->m.values[0]);
1285 }
1286 }
1287 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001288 if (featuresSetting) {
1289 apiFeatures = featuresSetting.value;
1290 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001291
1292 // TODO: use C2Component wrapper to associate this pool with ourselves
1293 if ((poolMask >> pools->inputAllocatorId) & 1) {
1294 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1295 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1296 mName, pools->inputAllocatorId,
1297 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1298 asString(err), err);
1299 } else {
1300 err = C2_NOT_FOUND;
1301 }
1302 if (err != C2_OK) {
1303 C2BlockPool::local_id_t inputPoolId =
1304 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1305 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1306 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1307 mName, (unsigned long long)inputPoolId,
1308 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1309 asString(err), err);
1310 if (err != C2_OK) {
1311 return NO_MEMORY;
1312 }
1313 }
1314 pools->inputPool = pool;
1315 }
1316
Wonsik Kim51051262018-11-28 13:59:05 -08001317 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001318 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001319 input->inputDelay = inputDelayValue;
1320 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001321 input->numSlots = numInputSlots;
1322 input->extraBuffers.flush();
1323 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001324 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001325 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1326 input->frameReassembler.init(
1327 pool,
1328 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1329 encoderFrameSize.value,
1330 sampleRate.value,
1331 channelCount.value,
1332 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1333 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001334 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1335 // For encrypted content, framework decrypts source buffer (ashmem) into
1336 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001337 if (!buffersBoundToCodec
1338 && !input->frameReassembler
1339 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001340 input->buffers.reset(new SlotInputBuffers(mName));
1341 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001342 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001343 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001344 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001345 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001346 // This is to ensure buffers do not get released prematurely.
1347 // TODO: handle this without going into array mode
1348 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001349 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001350 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001351 }
1352 } else {
1353 if (hasCryptoOrDescrambler()) {
1354 int32_t capacity = kLinearBufferSize;
1355 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1356 if ((size_t)capacity > kMaxLinearBufferSize) {
1357 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1358 capacity = kMaxLinearBufferSize;
1359 }
1360 if (mDealer == nullptr) {
1361 mDealer = new MemoryDealer(
1362 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001363 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001364 "EncryptedLinearInputBuffers");
1365 mDecryptDestination = mDealer->allocate((size_t)capacity);
1366 }
1367 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001368 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1369 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001370 } else {
1371 mHeapSeqNum = -1;
1372 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001373 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001374 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001375 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001376 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001377 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001378 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001379 }
1380 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001381 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001382
1383 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001384 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001385 } else {
1386 // TODO: error
1387 }
Wonsik Kim51051262018-11-28 13:59:05 -08001388
1389 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001390 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001391 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001392 }
1393
1394 if (outputFormat != nullptr) {
1395 sp<IGraphicBufferProducer> outputSurface;
1396 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001397 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001398 {
1399 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001400 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001401 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001402 outputSurface = output->surface ?
1403 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001404 if (outputSurface) {
1405 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1406 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001407 outputGeneration = output->generation;
1408 }
1409
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001410 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001411 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001412 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001413
1414 {
1415 Mutexed<BlockPools>::Locked pools(mBlockPools);
1416
David Stevensc3fbb282021-01-18 18:11:20 +09001417 prevOutputPoolId = pools->outputPoolId;
1418
Pawin Vongmasa36653902018-11-15 00:10:25 -08001419 // set default allocator ID.
1420 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001421 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001422
1423 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1424 // unsuccessful.
1425 std::vector<std::unique_ptr<C2Param>> params;
1426 err = mComponent->query({ },
1427 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1428 C2_DONT_BLOCK,
1429 &params);
1430 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1431 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1432 mName, params.size(), asString(err), err);
1433 } else if (err == C2_OK && params.size() == 1) {
1434 C2PortAllocatorsTuning::output *outputAllocators =
1435 C2PortAllocatorsTuning::output::From(params[0].get());
1436 if (outputAllocators && outputAllocators->flexCount() > 0) {
1437 std::shared_ptr<C2Allocator> allocator;
1438 // verify allocator IDs and resolve default allocator
1439 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1440 if (allocator) {
1441 pools->outputAllocatorId = allocator->getId();
1442 } else {
1443 ALOGD("[%s] component requested invalid output allocator ID %u",
1444 mName, outputAllocators->m.values[0]);
1445 }
1446 }
1447 }
1448
1449 // use bufferqueue if outputting to a surface.
1450 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1451 // if unsuccessful.
1452 if (outputSurface) {
1453 params.clear();
1454 err = mComponent->query({ },
1455 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1456 C2_DONT_BLOCK,
1457 &params);
1458 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1459 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1460 mName, params.size(), asString(err), err);
1461 } else if (err == C2_OK && params.size() == 1) {
1462 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1463 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1464 if (surfaceAllocator) {
1465 std::shared_ptr<C2Allocator> allocator;
1466 // verify allocator IDs and resolve default allocator
1467 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1468 if (allocator) {
1469 pools->outputAllocatorId = allocator->getId();
1470 } else {
1471 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1472 mName, surfaceAllocator->value);
1473 err = C2_BAD_VALUE;
1474 }
1475 }
1476 }
1477 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1478 && err != C2_OK
1479 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1480 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1481 }
1482 }
1483
1484 if ((poolMask >> pools->outputAllocatorId) & 1) {
1485 err = mComponent->createBlockPool(
1486 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1487 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1488 mName, pools->outputAllocatorId,
1489 (unsigned long long)pools->outputPoolId,
1490 asString(err));
1491 } else {
1492 err = C2_NOT_FOUND;
1493 }
1494 if (err != C2_OK) {
1495 // use basic pool instead
1496 pools->outputPoolId =
1497 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1498 }
1499
1500 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1501 // component.
1502 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1503 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1504
1505 std::vector<std::unique_ptr<C2SettingResult>> failures;
1506 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1507 ALOGD("[%s] Configured output block pool ids %llu => %s",
1508 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1509 outputPoolId_ = pools->outputPoolId;
1510 }
1511
David Stevensc3fbb282021-01-18 18:11:20 +09001512 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1513 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1514 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1515 if (err != C2_OK) {
1516 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1517 (unsigned long long) prevOutputPoolId, asString(err), err);
1518 }
1519 }
1520
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001521 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001522 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001523 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001524 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001525 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001526 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001527 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001528 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001529 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001530 }
1531 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001532 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001533 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001534 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001535
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001536 output->buffers->clearStash();
1537 if (reorderDepth) {
1538 output->buffers->setReorderDepth(reorderDepth.value);
1539 }
1540 if (reorderKey) {
1541 output->buffers->setReorderKey(reorderKey.value);
1542 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001543
1544 // Try to set output surface to created block pool if given.
1545 if (outputSurface) {
1546 mComponent->setOutputSurface(
1547 outputPoolId_,
1548 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001549 outputGeneration,
1550 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001551 } else {
1552 // configure CPU read consumer usage
1553 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1554 std::vector<std::unique_ptr<C2SettingResult>> failures;
1555 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1556 // do not print error message for now as most components may not yet
1557 // support this setting
1558 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1559 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001560 }
1561
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001562 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001563 if (buffersBoundToCodec) {
1564 // WORKAROUND: if we're using early CSD workaround we convert to
1565 // array mode, to appease apps assuming the output
1566 // buffers to be of the same size.
1567 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1568 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001569
1570 int32_t channelCount;
1571 int32_t sampleRate;
1572 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1573 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1574 int32_t delay = 0;
1575 int32_t padding = 0;;
1576 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1577 delay = 0;
1578 }
1579 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1580 padding = 0;
1581 }
1582 if (delay || padding) {
1583 // We need write access to the buffers, and we're already in
1584 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001585 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001586 }
1587 }
1588 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001589
1590 int32_t tunneled = 0;
1591 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1592 tunneled = 0;
1593 }
1594 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001595 }
1596
1597 // Set up pipeline control. This has to be done after mInputBuffers and
1598 // mOutputBuffers are initialized to make sure that lingering callbacks
1599 // about buffers from the previous generation do not interfere with the
1600 // newly initialized pipeline capacity.
1601
Wonsik Kim62545252021-01-20 11:25:41 -08001602 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001603 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001604 watcher->inputDelay(inputDelayValue)
1605 .pipelineDelay(pipelineDelayValue)
1606 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001607 .smoothnessFactor(kSmoothnessFactor);
1608 watcher->flush();
1609 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001610
1611 mInputMetEos = false;
1612 mSync.start();
1613 return OK;
1614}
1615
Wonsik Kim34b28b42022-05-20 15:49:32 -07001616status_t CCodecBufferChannel::prepareInitialInputBuffers(
1617 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001618 if (mInputSurface) {
1619 return OK;
1620 }
1621
Wonsik Kim34b28b42022-05-20 15:49:32 -07001622 size_t numInputSlots = mInput.lock()->numSlots;
1623
1624 {
1625 Mutexed<Input>::Locked input(mInput);
1626 while (clientInputBuffers->size() < numInputSlots) {
1627 size_t index;
1628 sp<MediaCodecBuffer> buffer;
1629 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1630 break;
1631 }
1632 clientInputBuffers->emplace(index, buffer);
1633 }
1634 }
1635 if (clientInputBuffers->empty()) {
1636 ALOGW("[%s] start: cannot allocate memory at all", mName);
1637 return NO_MEMORY;
1638 } else if (clientInputBuffers->size() < numInputSlots) {
1639 ALOGD("[%s] start: cannot allocate memory for all slots, "
1640 "only %zu buffers allocated",
1641 mName, clientInputBuffers->size());
1642 } else {
1643 ALOGV("[%s] %zu initial input buffers available",
1644 mName, clientInputBuffers->size());
1645 }
1646 return OK;
1647}
1648
1649status_t CCodecBufferChannel::requestInitialInputBuffers(
1650 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001651 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001652 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1653 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1654 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001655 return UNKNOWN_ERROR;
1656 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001657
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001658 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1659 mFlushedConfigs.lock()->swap(flushedConfigs);
1660 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001661 {
1662 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1663 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1664 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1665 watcher->onWorkQueued(
1666 work->input.ordinal.frameIndex.peeku(),
1667 std::vector(work->input.buffers),
1668 now);
1669 }
1670 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001671 err = mComponent->queue(&flushedConfigs);
1672 if (err != C2_OK) {
1673 ALOGW("[%s] Error while queueing a flushed config", mName);
1674 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001675 }
1676 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001677 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001678 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1679 !clientInputBuffers.empty()) {
1680 size_t minIndex = clientInputBuffers.begin()->first;
1681 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1682 for (const auto &[index, buffer] : clientInputBuffers) {
1683 if (minBuffer->capacity() > buffer->capacity()) {
1684 minIndex = index;
1685 minBuffer = buffer;
1686 }
1687 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001688 // WORKAROUND: Some apps expect CSD available without queueing
1689 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001690 minBuffer->setRange(0, 0);
1691 minBuffer->meta()->clear();
1692 minBuffer->meta()->setInt64("timeUs", 0);
1693 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001694 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1695 mName);
1696 return UNKNOWN_ERROR;
1697 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001698 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001699 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001700
Wonsik Kim34b28b42022-05-20 15:49:32 -07001701 for (const auto &[index, buffer] : clientInputBuffers) {
1702 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001703 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001704
Pawin Vongmasa36653902018-11-15 00:10:25 -08001705 return OK;
1706}
1707
1708void CCodecBufferChannel::stop() {
1709 mSync.stop();
1710 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001711}
1712
Sungtak Lee99144332023-01-26 11:03:14 +00001713void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
1714 sp<Surface> surface = mOutputSurface.lock()->surface;
1715 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00001716 C2BlockPool::local_id_t outputPoolId;
1717 {
1718 Mutexed<BlockPools>::Locked pools(mBlockPools);
1719 outputPoolId = pools->outputPoolId;
1720 }
1721 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00001722
1723 if (pushBlankBuffer) {
1724 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
1725 if (anw) {
1726 pushBlankBuffersToNativeWindow(anw.get());
1727 }
1728 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00001729 }
1730}
1731
Wonsik Kim936a89c2020-05-08 16:07:50 -07001732void CCodecBufferChannel::reset() {
1733 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001734 if (mInputSurface != nullptr) {
1735 mInputSurface.reset();
1736 }
1737 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001738 {
1739 Mutexed<Input>::Locked input(mInput);
1740 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001741 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001742 }
1743 {
1744 Mutexed<Output>::Locked output(mOutput);
1745 output->buffers.reset();
1746 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001747 // reset the frames that are being tracked for onFrameRendered callbacks
1748 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001749}
1750
1751void CCodecBufferChannel::release() {
1752 mComponent.reset();
1753 mInputAllocator.reset();
1754 mOutputSurface.lock()->surface.clear();
1755 {
1756 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1757 blockPools->inputPool.reset();
1758 blockPools->outputPoolIntf.reset();
1759 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001760 setCrypto(nullptr);
1761 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001762}
1763
Pawin Vongmasa36653902018-11-15 00:10:25 -08001764void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1765 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001766 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001767 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001768 {
1769 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1770 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1771 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1772 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1773 watcher->onWorkDone(frameIndex);
1774 continue;
1775 }
1776 if (work->input.buffers.empty()
1777 || work->input.buffers.front() == nullptr
1778 || work->input.buffers.front()->data().linearBlocks().empty()) {
1779 ALOGD("[%s] no linear codec config data found", mName);
1780 watcher->onWorkDone(frameIndex);
1781 continue;
1782 }
1783 std::unique_ptr<C2Work> copy(new C2Work);
1784 copy->input.flags = C2FrameData::flags_t(
1785 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1786 copy->input.ordinal = work->input.ordinal;
1787 copy->input.ordinal.frameIndex = mFrameIndex++;
1788 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1789 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1790 }
1791 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1792 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1793 }
1794 copy->input.infoBuffers.insert(
1795 copy->input.infoBuffers.begin(),
1796 work->input.infoBuffers.begin(),
1797 work->input.infoBuffers.end());
1798 copy->worklets.emplace_back(new C2Worklet);
1799 configs.push_back(std::move(copy));
1800 watcher->onWorkDone(frameIndex);
1801 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001802 }
1803 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001804 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001805 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001806 Mutexed<Input>::Locked input(mInput);
1807 input->buffers->flush();
1808 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001809 }
1810 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001811 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001812 if (output->buffers) {
1813 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001814 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001815 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001816 }
1817}
1818
1819void CCodecBufferChannel::onWorkDone(
1820 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001821 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001822 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001823 feedInputBufferIfAvailable();
1824 }
1825}
1826
1827void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001828 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001829 if (mInputSurface) {
1830 return;
1831 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001832 std::shared_ptr<C2Buffer> buffer =
1833 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001834 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001835 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001836 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001837 if (input->lastFlushIndex >= frameIndex) {
1838 ALOGD("[%s] Ignoring stale input buffer done callback: "
1839 "last flush index = %lld, frameIndex = %lld",
1840 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1841 } else {
1842 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1843 if (!newInputSlotAvailable) {
1844 (void)input->extraBuffers.expireComponentBuffer(buffer);
1845 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001846 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001847 }
1848 if (newInputSlotAvailable) {
1849 feedInputBufferIfAvailable();
1850 }
1851}
1852
1853bool CCodecBufferChannel::handleWork(
1854 std::unique_ptr<C2Work> work,
1855 const sp<AMessage> &outputFormat,
1856 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001857 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001858 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001859 if (!output->buffers) {
1860 return false;
1861 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001862 }
1863
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001864 // Whether the output buffer should be reported to the client or not.
1865 bool notifyClient = false;
1866
1867 if (work->result == C2_OK){
1868 notifyClient = true;
1869 } else if (work->result == C2_NOT_FOUND) {
1870 ALOGD("[%s] flushed work; ignored.", mName);
1871 } else {
1872 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1873 // the config update.
1874 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1875 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1876 return false;
1877 }
1878
1879 if ((work->input.ordinal.frameIndex -
1880 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001881 // Discard frames from previous generation.
1882 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001883 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001884 }
1885
Wonsik Kim524b0582019-03-12 11:28:57 -07001886 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001887 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001888 || !(work->worklets.front()->output.flags &
1889 C2FrameData::FLAG_INCOMPLETE))) {
1890 mPipelineWatcher.lock()->onWorkDone(
1891 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001892 }
1893
1894 // NOTE: MediaCodec usage supposedly have only one worklet
1895 if (work->worklets.size() != 1u) {
1896 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1897 mName, work->worklets.size());
1898 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1899 return false;
1900 }
1901
1902 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1903
1904 std::shared_ptr<C2Buffer> buffer;
1905 // NOTE: MediaCodec usage supposedly have only one output stream.
1906 if (worklet->output.buffers.size() > 1u) {
1907 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1908 mName, worklet->output.buffers.size());
1909 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1910 return false;
1911 } else if (worklet->output.buffers.size() == 1u) {
1912 buffer = worklet->output.buffers[0];
1913 if (!buffer) {
1914 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1915 }
1916 }
1917
Wonsik Kim3dedf682021-05-03 10:57:09 -07001918 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1919 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001920 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001921 while (!worklet->output.configUpdate.empty()) {
1922 std::unique_ptr<C2Param> param;
1923 worklet->output.configUpdate.back().swap(param);
1924 worklet->output.configUpdate.pop_back();
1925 switch (param->coreIndex().coreIndex()) {
1926 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1927 C2PortReorderBufferDepthTuning::output reorderDepth;
1928 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001929 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1930 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001931 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001932 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001933 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001934 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1935 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001936 }
1937 break;
1938 }
1939 case C2PortReorderKeySetting::CORE_INDEX: {
1940 C2PortReorderKeySetting::output reorderKey;
1941 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001942 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001943 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1944 mName, reorderKey.value);
1945 } else {
1946 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1947 }
1948 break;
1949 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001950 case C2PortActualDelayTuning::CORE_INDEX: {
1951 if (param->isGlobal()) {
1952 C2ActualPipelineDelayTuning pipelineDelay;
1953 if (pipelineDelay.updateFrom(*param)) {
1954 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1955 mName, pipelineDelay.value);
1956 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001957 (void)mPipelineWatcher.lock()->pipelineDelay(
1958 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001959 }
1960 }
1961 if (param->forInput()) {
1962 C2PortActualDelayTuning::input inputDelay;
1963 if (inputDelay.updateFrom(*param)) {
1964 ALOGV("[%s] onWorkDone: updating input delay %u",
1965 mName, inputDelay.value);
1966 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001967 (void)mPipelineWatcher.lock()->inputDelay(
1968 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001969 }
1970 }
1971 if (param->forOutput()) {
1972 C2PortActualDelayTuning::output outputDelay;
1973 if (outputDelay.updateFrom(*param)) {
1974 ALOGV("[%s] onWorkDone: updating output delay %u",
1975 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001976 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001977 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001978 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001979
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001980 }
1981 }
1982 break;
1983 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001984 case C2PortTunnelSystemTime::CORE_INDEX: {
1985 C2PortTunnelSystemTime::output frameRenderTime;
1986 if (frameRenderTime.updateFrom(*param)) {
1987 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1988 mName, (long long)frameRenderTime.value,
1989 (long long)worklet->output.ordinal.timestamp.peekll());
1990 mCCodecCallback->onOutputFramesRendered(
1991 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1992 }
1993 break;
1994 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001995 case C2StreamTunnelHoldRender::CORE_INDEX: {
1996 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1997 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1998 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1999 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
2000 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
2001 mCCodecCallback->onFirstTunnelFrameReady();
2002 break;
2003 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002004 default:
2005 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2006 mName, param->index());
2007 break;
2008 }
2009 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002010 if (newInputDelay || newPipelineDelay) {
2011 Mutexed<Input>::Locked input(mInput);
2012 size_t newNumSlots =
2013 newInputDelay.value_or(input->inputDelay) +
2014 newPipelineDelay.value_or(input->pipelineDelay) +
2015 kSmoothnessFactor;
2016 if (input->buffers->isArrayMode()) {
2017 if (input->numSlots >= newNumSlots) {
2018 input->numExtraSlots = 0;
2019 } else {
2020 input->numExtraSlots = newNumSlots - input->numSlots;
2021 }
2022 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2023 mName, input->numExtraSlots);
2024 } else {
2025 input->numSlots = newNumSlots;
2026 }
2027 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002028 size_t numOutputSlots = 0;
2029 uint32_t reorderDepth = 0;
2030 bool outputBuffersChanged = false;
2031 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2032 Mutexed<Output>::Locked output(mOutput);
2033 if (!output->buffers) {
2034 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002035 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002036 numOutputSlots = output->numSlots;
2037 if (newReorderKey) {
2038 output->buffers->setReorderKey(newReorderKey.value());
2039 }
2040 if (newReorderDepth) {
2041 output->buffers->setReorderDepth(newReorderDepth.value());
2042 }
2043 reorderDepth = output->buffers->getReorderDepth();
2044 if (newOutputDelay) {
2045 output->outputDelay = newOutputDelay.value();
2046 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2047 if (output->numSlots < numOutputSlots) {
2048 output->numSlots = numOutputSlots;
2049 if (output->buffers->isArrayMode()) {
2050 OutputBuffersArray *array =
2051 (OutputBuffersArray *)output->buffers.get();
2052 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2053 mName, numOutputSlots);
2054 array->grow(numOutputSlots);
2055 outputBuffersChanged = true;
2056 }
2057 }
2058 }
2059 numOutputSlots = output->numSlots;
2060 }
2061 if (outputBuffersChanged) {
2062 mCCodecCallback->onOutputBuffersChanged();
2063 }
2064 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002065 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002066 {
2067 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2068 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002069 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002070 if (output->surface) {
2071 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2072 }
2073 }
2074 if (maxDequeueCount > 0) {
2075 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002076 }
2077 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002078
Pawin Vongmasa36653902018-11-15 00:10:25 -08002079 int32_t flags = 0;
2080 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002081 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002082 ALOGV("[%s] onWorkDone: output EOS", mName);
2083 }
2084
Pawin Vongmasa36653902018-11-15 00:10:25 -08002085 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2086 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2087 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2088 // shall correspond to the client input timesamp (in customOrdinal). By using the
2089 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2090 // produces multiple output.
2091 c2_cntr64_t timestamp =
2092 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2093 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002094 if (mInputSurface != nullptr) {
2095 // When using input surface we need to restore the original input timestamp.
2096 timestamp = work->input.ordinal.customOrdinal;
2097 }
My Name6bd9a7d2022-03-25 12:37:58 -07002098 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2099 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002100 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2101 mName,
2102 work->input.ordinal.customOrdinal.peekll(),
2103 work->input.ordinal.timestamp.peekll(),
2104 worklet->output.ordinal.timestamp.peekll(),
2105 timestamp.peekll());
2106
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002107 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002108 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002109 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002110 if (!output->buffers) {
2111 return false;
2112 }
2113 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002114 output->buffers->updateSkipCutBuffer(outputFormat);
2115 output->buffers->setFormat(outputFormat);
2116 }
2117 if (!notifyClient) {
2118 return false;
2119 }
2120 size_t index;
2121 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002122 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002123 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002124 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002125 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2126
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002127 // TRICKY: we want popped buffers reported in order, so sending
2128 // the callback while holding the lock here. This assumes that
2129 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2130 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002131 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002132 } else {
2133 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002134 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002135 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002136 return false;
2137 }
2138 }
2139
Wonsik Kimec585c32021-10-01 01:11:00 -07002140 bool drop = false;
2141 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2142 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2143 drop = true;
2144 }
2145
Marc Kassisec910342022-11-25 11:43:05 +01002146 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2147 // HAL, the flag is then removed in the corresponding output buffer.
2148 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2149 flags |= BUFFER_FLAG_DECODE_ONLY;
2150 }
2151
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002152 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002153 if (mTunneled && drop && outputFormat) {
2154 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2155 mName, work->input.ordinal.frameIndex.peekull());
2156 } else {
2157 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2158 mName, work->input.ordinal.frameIndex.peekull());
2159 notifyClient = false;
2160 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002161 }
2162
2163 if (buffer) {
2164 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2165 // TODO: properly translate these to metadata
2166 switch (info->coreIndex().coreIndex()) {
2167 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002168 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002169 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002170 }
2171 break;
2172 default:
2173 break;
2174 }
2175 }
2176 }
2177
2178 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002179 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002180 if (!output->buffers) {
2181 return false;
2182 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002183 output->buffers->pushToStash(
2184 buffer,
2185 notifyClient,
2186 timestamp.peek(),
2187 flags,
2188 outputFormat,
2189 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002190 }
2191 sendOutputBuffers();
2192 return true;
2193}
2194
2195void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002196 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002197 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002198 sp<MediaCodecBuffer> outBuffer;
2199 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002200
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002201 constexpr int kMaxReallocTry = 5;
2202 int reallocTryNum = 0;
2203
Pawin Vongmasa36653902018-11-15 00:10:25 -08002204 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002205 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002206 if (!output->buffers) {
2207 return;
2208 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002209 action = output->buffers->popFromStashAndRegister(
2210 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002211 if (action != OutputBuffers::REALLOCATE) {
2212 reallocTryNum = 0;
2213 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002214 switch (action) {
2215 case OutputBuffers::SKIP:
2216 return;
2217 case OutputBuffers::DISCARD:
2218 break;
2219 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002220 // TRICKY: we want popped buffers reported in order, so sending
2221 // the callback while holding the lock here. This assumes that
2222 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2223 // callbacks are always sent with the Output lock held.
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002224 mCallback->onOutputBufferAvailable(index, outBuffer);
2225 break;
2226 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002227 if (++reallocTryNum > kMaxReallocTry) {
2228 output.unlock();
2229 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2230 mName, kMaxReallocTry);
2231 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2232 return;
2233 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002234 if (!output->buffers->isArrayMode()) {
2235 output->buffers =
2236 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002237 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002238 static_cast<OutputBuffersArray*>(output->buffers.get())->
2239 realloc(c2Buffer);
2240 output.unlock();
2241 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002242 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002243 case OutputBuffers::RETRY:
2244 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2245 mName);
2246 return;
2247 default:
2248 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2249 "corrupted BufferAction value (%d) "
2250 "returned from popFromStashAndRegister.",
2251 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002252 return;
2253 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002254 }
2255}
2256
Sungtak Lee99144332023-01-26 11:03:14 +00002257status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002258 static std::atomic_uint32_t surfaceGeneration{0};
2259 uint32_t generation = (getpid() << 10) |
2260 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2261 & ((1 << 10) - 1));
2262
2263 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002264 int maxDequeueCount;
2265 sp<Surface> oldSurface;
2266 {
2267 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2268 maxDequeueCount = outputSurface->maxDequeueBuffers;
2269 oldSurface = outputSurface->surface;
2270 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002271 if (newSurface) {
2272 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002273 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002274 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002275 producer = newSurface->getIGraphicBufferProducer();
2276 producer->setGenerationNumber(generation);
2277 } else {
2278 ALOGE("[%s] setting output surface to null", mName);
2279 return INVALID_OPERATION;
2280 }
2281
2282 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2283 C2BlockPool::local_id_t outputPoolId;
2284 {
2285 Mutexed<BlockPools>::Locked pools(mBlockPools);
2286 outputPoolId = pools->outputPoolId;
2287 outputPoolIntf = pools->outputPoolIntf;
2288 }
2289
2290 if (outputPoolIntf) {
2291 if (mComponent->setOutputSurface(
2292 outputPoolId,
2293 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002294 generation,
2295 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002296 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2297 return INVALID_OPERATION;
2298 }
2299 }
2300
2301 {
2302 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2303 output->surface = newSurface;
2304 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002305 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002306 }
2307
Sungtak Lee99144332023-01-26 11:03:14 +00002308 if (oldSurface && pushBlankBuffer) {
2309 // When ReleaseSurface was set from MediaCodec,
2310 // pushing a blank buffer at the end might be necessary.
2311 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2312 if (anw) {
2313 pushBlankBuffersToNativeWindow(anw.get());
2314 }
2315 }
2316
Pawin Vongmasa36653902018-11-15 00:10:25 -08002317 return OK;
2318}
2319
Wonsik Kimab34ed62019-01-31 15:28:46 -08002320PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002321 // Otherwise, component may have stalled work due to input starvation up to
2322 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002323 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2324 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002325 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002326 size_t outputDelay = mOutput.lock()->outputDelay;
2327 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002328 Mutexed<Input>::Locked input(mInput);
2329 n = input->inputDelay + input->pipelineDelay + outputDelay;
2330 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002331 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002332}
2333
Pawin Vongmasa36653902018-11-15 00:10:25 -08002334void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2335 mMetaMode = mode;
2336}
2337
Wonsik Kim596187e2019-10-25 12:44:10 -07002338void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002339 if (mCrypto != nullptr) {
2340 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2341 mCrypto->unsetHeap(entry.second);
2342 }
2343 mHeapSeqNumMap.clear();
2344 if (mHeapSeqNum >= 0) {
2345 mCrypto->unsetHeap(mHeapSeqNum);
2346 mHeapSeqNum = -1;
2347 }
2348 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002349 mCrypto = crypto;
2350}
2351
2352void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2353 mDescrambler = descrambler;
2354}
2355
Pawin Vongmasa36653902018-11-15 00:10:25 -08002356status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2357 // C2_OK is always translated to OK.
2358 if (c2s == C2_OK) {
2359 return OK;
2360 }
2361
2362 // Operation-dependent translation
2363 // TODO: Add as necessary
2364 switch (c2op) {
2365 case C2_OPERATION_Component_start:
2366 switch (c2s) {
2367 case C2_NO_MEMORY:
2368 return NO_MEMORY;
2369 default:
2370 return UNKNOWN_ERROR;
2371 }
2372 default:
2373 break;
2374 }
2375
2376 // Backup operation-agnostic translation
2377 switch (c2s) {
2378 case C2_BAD_INDEX:
2379 return BAD_INDEX;
2380 case C2_BAD_VALUE:
2381 return BAD_VALUE;
2382 case C2_BLOCKING:
2383 return WOULD_BLOCK;
2384 case C2_DUPLICATE:
2385 return ALREADY_EXISTS;
2386 case C2_NO_INIT:
2387 return NO_INIT;
2388 case C2_NO_MEMORY:
2389 return NO_MEMORY;
2390 case C2_NOT_FOUND:
2391 return NAME_NOT_FOUND;
2392 case C2_TIMED_OUT:
2393 return TIMED_OUT;
2394 case C2_BAD_STATE:
2395 case C2_CANCELED:
2396 case C2_CANNOT_DO:
2397 case C2_CORRUPTED:
2398 case C2_OMITTED:
2399 case C2_REFUSED:
2400 return UNKNOWN_ERROR;
2401 default:
2402 return -static_cast<status_t>(c2s);
2403 }
2404}
2405
Pawin Vongmasa36653902018-11-15 00:10:25 -08002406} // namespace android