blob: 514d622ab39e63cb9785e65407742bafa7208d8d [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright 2017, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010018#include <utils/Errors.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080019#define LOG_TAG "CCodecBufferChannel"
My Name6bd9a7d2022-03-25 12:37:58 -070020#define ATRACE_TAG ATRACE_TAG_VIDEO
Pawin Vongmasa36653902018-11-15 00:10:25 -080021#include <utils/Log.h>
My Name6bd9a7d2022-03-25 12:37:58 -070022#include <utils/Trace.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080023
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070024#include <algorithm>
Wonsik Kim6b2c8be2021-09-28 05:11:04 -070025#include <atomic>
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070026#include <list>
Pawin Vongmasa36653902018-11-15 00:10:25 -080027#include <numeric>
28
29#include <C2AllocatorGralloc.h>
30#include <C2PlatformSupport.h>
31#include <C2BlockInternal.h>
32#include <C2Config.h>
33#include <C2Debug.h>
34
35#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070036#include <android/hardware/drm/1.0/types.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070037#include <android-base/parseint.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080038#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080039#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080040#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080041#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070042#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080043#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070044#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080045#include <media/openmax/OMX_Core.h>
46#include <media/stagefright/foundation/ABuffer.h>
47#include <media/stagefright/foundation/ALookup.h>
48#include <media/stagefright/foundation/AMessage.h>
49#include <media/stagefright/foundation/AUtils.h>
50#include <media/stagefright/foundation/hexdump.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080051#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070052#include <media/stagefright/SkipCutBuffer.h>
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010053#include <media/stagefright/SurfaceUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080054#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070055#include <mediadrm/ICrypto.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070056#include <server_configurable_flags/get_flags.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080057#include <system/window.h>
58
59#include "CCodecBufferChannel.h"
60#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080061
62namespace android {
63
64using android::base::StringPrintf;
65using hardware::hidl_handle;
66using hardware::hidl_string;
67using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070068using hardware::fromHeap;
69using hardware::HidlMemory;
Brian Lindahl83931482023-08-10 10:12:49 -060070using server_configurable_flags::GetServerConfigurableFlag;
Robert Shih895fba92019-07-16 16:29:44 -070071
Pawin Vongmasa36653902018-11-15 00:10:25 -080072using namespace hardware::cas::V1_0;
73using namespace hardware::cas::native::V1_0;
74
75using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070076using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080077
Pawin Vongmasa36653902018-11-15 00:10:25 -080078namespace {
79
Wonsik Kim469c8342019-04-11 16:46:09 -070080constexpr size_t kSmoothnessFactor = 4;
Pawin Vongmasa36653902018-11-15 00:10:25 -080081
Sungtak Leeab6f2f32019-02-15 14:43:51 -080082// This is for keeping IGBP's buffer dropping logic in legacy mode other
83// than making it non-blocking. Do not change this value.
84const static size_t kDequeueTimeoutNs = 0;
85
Brian Lindahl83931482023-08-10 10:12:49 -060086static bool areRenderMetricsEnabled() {
87 std::string v = GetServerConfigurableFlag("media_native", "render_metrics_enabled", "false");
88 return v == "true";
89}
90
Pawin Vongmasa36653902018-11-15 00:10:25 -080091} // namespace
92
93CCodecBufferChannel::QueueGuard::QueueGuard(
94 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
95 Mutex::Autolock l(mSync.mGuardLock);
96 // At this point it's guaranteed that mSync is not under state transition,
97 // as we are holding its mutex.
98
99 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
100 if (count->value == -1) {
101 mRunning = false;
102 } else {
103 ++count->value;
104 mRunning = true;
105 }
106}
107
108CCodecBufferChannel::QueueGuard::~QueueGuard() {
109 if (mRunning) {
110 // We are not holding mGuardLock at this point so that QueueSync::stop() can
111 // keep holding the lock until mCount reaches zero.
112 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
113 --count->value;
114 count->cond.broadcast();
115 }
116}
117
118void CCodecBufferChannel::QueueSync::start() {
119 Mutex::Autolock l(mGuardLock);
120 // If stopped, it goes to running state; otherwise no-op.
121 Mutexed<Counter>::Locked count(mCount);
122 if (count->value == -1) {
123 count->value = 0;
124 }
125}
126
127void CCodecBufferChannel::QueueSync::stop() {
128 Mutex::Autolock l(mGuardLock);
129 Mutexed<Counter>::Locked count(mCount);
130 if (count->value == -1) {
131 // no-op
132 return;
133 }
134 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
135 // mCount can only decrement. In other words, threads that acquired the lock
136 // are allowed to finish execution but additional threads trying to acquire
137 // the lock at this point will block, and then get QueueGuard at STOPPED
138 // state.
139 while (count->value != 0) {
140 count.waitForCondition(count->cond);
141 }
142 count->value = -1;
143}
144
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700145// Input
146
147CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
148
Pawin Vongmasa36653902018-11-15 00:10:25 -0800149// CCodecBufferChannel
150
151CCodecBufferChannel::CCodecBufferChannel(
152 const std::shared_ptr<CCodecCallback> &callback)
153 : mHeapSeqNum(-1),
154 mCCodecCallback(callback),
155 mFrameIndex(0u),
156 mFirstValidFrameIndex(0u),
Brian Lindahl83931482023-08-10 10:12:49 -0600157 mAreRenderMetricsEnabled(areRenderMetricsEnabled()),
Brian Lindahl2048d492023-04-05 08:49:23 -0600158 mIsSurfaceToDisplay(false),
159 mHasPresentFenceTimes(false),
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700160 mRenderingDepth(3u),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800161 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700162 mInputMetEos(false),
163 mSendEncryptedInfoBuffer(false) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700164 {
165 Mutexed<Input>::Locked input(mInput);
166 input->buffers.reset(new DummyInputBuffers(""));
167 input->extraBuffers.flush();
168 input->inputDelay = 0u;
169 input->pipelineDelay = 0u;
170 input->numSlots = kSmoothnessFactor;
171 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700172 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700173 }
174 {
175 Mutexed<Output>::Locked output(mOutput);
176 output->outputDelay = 0u;
177 output->numSlots = kSmoothnessFactor;
Wonsik Kim3722abc2023-05-17 13:26:31 -0700178 output->bounded = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700179 }
David Stevensc3fbb282021-01-18 18:11:20 +0900180 {
181 Mutexed<BlockPools>::Locked pools(mBlockPools);
182 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
183 }
Brian Lindahl83931482023-08-10 10:12:49 -0600184 std::string value = GetServerConfigurableFlag("media_native", "ccodec_rendering_depth", "3");
Wonsik Kim3a692e62023-05-19 15:37:22 -0700185 android::base::ParseInt(value, &mRenderingDepth);
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700186 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800187}
188
189CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800190 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800191 mCrypto->unsetHeap(mHeapSeqNum);
192 }
193}
194
195void CCodecBufferChannel::setComponent(
196 const std::shared_ptr<Codec2Client::Component> &component) {
197 mComponent = component;
198 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
199 mName = mComponentName.c_str();
200}
201
202status_t CCodecBufferChannel::setInputSurface(
203 const std::shared_ptr<InputSurfaceWrapper> &surface) {
204 ALOGV("[%s] setInputSurface", mName);
205 mInputSurface = surface;
206 return mInputSurface->connect(mComponent);
207}
208
209status_t CCodecBufferChannel::signalEndOfInputStream() {
210 if (mInputSurface == nullptr) {
211 return INVALID_OPERATION;
212 }
213 return mInputSurface->signalEndOfInputStream();
214}
215
Sungtak Lee04b30352020-07-27 13:57:25 -0700216status_t CCodecBufferChannel::queueInputBufferInternal(
217 sp<MediaCodecBuffer> buffer,
218 std::shared_ptr<C2LinearBlock> encryptedBlock,
219 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800220 int64_t timeUs;
221 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
222
223 if (mInputMetEos) {
224 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
225 return OK;
226 }
227
228 int32_t flags = 0;
229 int32_t tmp = 0;
230 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200231 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800232 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
233 eos = true;
234 mInputMetEos = true;
235 ALOGV("[%s] input EOS", mName);
236 }
237 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
238 flags |= C2FrameData::FLAG_CODEC_CONFIG;
239 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200240 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
241 tunnelFirstFrame = true;
242 }
Marc Kassis96343b42022-12-09 11:49:44 +0100243 if (buffer->meta()->findInt32("decode-only", &tmp) && tmp) {
244 flags |= C2FrameData::FLAG_DROP_FRAME;
245 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800246 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800247 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800248 std::unique_ptr<C2Work> work(new C2Work);
249 work->input.ordinal.timestamp = timeUs;
250 work->input.ordinal.frameIndex = mFrameIndex++;
251 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
252 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
253 // Keep client timestamp in customOrdinal
254 work->input.ordinal.customOrdinal = timeUs;
255 work->input.buffers.clear();
256
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700257 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800258 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800259
Pawin Vongmasa36653902018-11-15 00:10:25 -0800260 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700261 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800262 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700263 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800264 return -ENOENT;
265 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700266 // TODO: we want to delay copying buffers.
267 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
268 copy = input->buffers->cloneAndReleaseBuffer(buffer);
269 if (copy != nullptr) {
270 (void)input->extraBuffers.assignSlot(copy);
271 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
272 return UNKNOWN_ERROR;
273 }
274 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
275 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
276 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700277 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700278 } else {
279 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
280 "buffer starvation on component.", mName);
281 }
282 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800283 if (input->frameReassembler) {
284 usesFrameReassembler = true;
285 input->frameReassembler.process(buffer, &items);
286 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900287 int32_t cvo = 0;
288 if (buffer->meta()->findInt32("cvo", &cvo)) {
289 int32_t rotation = cvo % 360;
290 // change rotation to counter-clock wise.
291 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
292
293 Mutexed<OutputSurface>::Locked output(mOutputSurface);
294 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
295 output->rotation[frameIndex] = rotation;
296 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800297 work->input.buffers.push_back(c2buffer);
298 if (encryptedBlock) {
299 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
300 kParamIndexEncryptedBuffer,
301 encryptedBlock->share(0, blockSize, C2Fence())));
302 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700303 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800304 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700305 Mutexed<Input>::Locked input(mInput);
306 if (input->frameReassembler) {
307 usesFrameReassembler = true;
308 // drain any pending items with eos
309 input->frameReassembler.process(buffer, &items);
310 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800311 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800312 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800313 if (usesFrameReassembler) {
314 if (!items.empty()) {
315 items.front()->input.configUpdate = std::move(mParamsToBeSet);
316 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
317 }
318 } else {
319 work->input.flags = (C2FrameData::flags_t)flags;
320 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800321
Wonsik Kime1104ca2020-11-24 15:01:33 -0800322 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200323 if (tunnelFirstFrame) {
324 C2StreamTunnelHoldRender::input tunnelHoldRender{
325 0u /* stream */,
326 C2_TRUE /* value */
327 };
328 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
329 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800330 work->worklets.clear();
331 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800332
Wonsik Kime1104ca2020-11-24 15:01:33 -0800333 items.push_back(std::move(work));
334
335 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800336 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800337 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800338 work.reset(new C2Work);
339 work->input.ordinal.timestamp = timeUs;
340 work->input.ordinal.frameIndex = mFrameIndex++;
341 // WORKAROUND: keep client timestamp in customOrdinal
342 work->input.ordinal.customOrdinal = timeUs;
343 work->input.buffers.clear();
344 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800345 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800346 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800347 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800348 c2_status_t err = C2_OK;
349 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700350 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
351 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800352 {
353 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
354 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
355 for (const std::unique_ptr<C2Work> &work : items) {
356 watcher->onWorkQueued(
357 work->input.ordinal.frameIndex.peeku(),
358 std::vector(work->input.buffers),
359 now);
360 }
361 }
362 err = mComponent->queue(&items);
363 }
364 if (err != C2_OK) {
365 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
366 for (const std::unique_ptr<C2Work> &work : items) {
367 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
368 }
369 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700370 Mutexed<Input>::Locked input(mInput);
371 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700372 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700373 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700374 } else if (buffer) {
375 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700376 }
377 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
378 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800379 }
380
381 feedInputBufferIfAvailableInternal();
382 return err;
383}
384
385status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
386 QueueGuard guard(mSync);
387 if (!guard.isRunning()) {
388 ALOGD("[%s] setParameters is only supported in the running state.", mName);
389 return -ENOSYS;
390 }
391 mParamsToBeSet.insert(mParamsToBeSet.end(),
392 std::make_move_iterator(params.begin()),
393 std::make_move_iterator(params.end()));
394 params.clear();
395 return OK;
396}
397
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800398status_t CCodecBufferChannel::attachBuffer(
399 const std::shared_ptr<C2Buffer> &c2Buffer,
400 const sp<MediaCodecBuffer> &buffer) {
401 if (!buffer->copy(c2Buffer)) {
402 return -ENOSYS;
403 }
404 return OK;
405}
406
407void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
408 if (!mDecryptDestination || mDecryptDestination->size() < size) {
409 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
410 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
411 mCrypto->unsetHeap(mHeapSeqNum);
412 }
413 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
414 if (mCrypto) {
415 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
416 }
417 }
418}
419
420int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
421 CHECK(mCrypto);
422 auto it = mHeapSeqNumMap.find(memory);
423 int32_t heapSeqNum = -1;
424 if (it == mHeapSeqNumMap.end()) {
425 heapSeqNum = mCrypto->setHeap(memory);
426 mHeapSeqNumMap.emplace(memory, heapSeqNum);
427 } else {
428 heapSeqNum = it->second;
429 }
430 return heapSeqNum;
431}
432
433status_t CCodecBufferChannel::attachEncryptedBuffer(
434 const sp<hardware::HidlMemory> &memory,
435 bool secure,
436 const uint8_t *key,
437 const uint8_t *iv,
438 CryptoPlugin::Mode mode,
439 CryptoPlugin::Pattern pattern,
440 size_t offset,
441 const CryptoPlugin::SubSample *subSamples,
442 size_t numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000443 const sp<MediaCodecBuffer> &buffer,
444 AString* errorDetailMsg) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800445 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
446 static const C2MemoryUsage kDefaultReadWriteUsage{
447 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
448
449 size_t size = 0;
450 for (size_t i = 0; i < numSubSamples; ++i) {
451 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
452 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700453 if (size == 0) {
454 buffer->setRange(0, 0);
455 return OK;
456 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800457 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
458 std::shared_ptr<C2LinearBlock> block;
459 c2_status_t err = pool->fetchLinearBlock(
460 size,
461 secure ? kSecureUsage : kDefaultReadWriteUsage,
462 &block);
463 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700464 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
465 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800466 return NO_MEMORY;
467 }
468 if (!secure) {
469 ensureDecryptDestination(size);
470 }
471 ssize_t result = -1;
472 ssize_t codecDataOffset = 0;
473 if (mCrypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800474 int32_t heapSeqNum = getHeapSeqNum(memory);
475 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
476 hardware::drm::V1_0::DestinationBuffer dst;
477 if (secure) {
478 dst.type = DrmBufferType::NATIVE_HANDLE;
479 dst.secureMemory = hardware::hidl_handle(block->handle());
480 } else {
481 dst.type = DrmBufferType::SHARED_MEMORY;
482 IMemoryToSharedBuffer(
483 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
484 }
485 result = mCrypto->decrypt(
486 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000487 dst, errorDetailMsg);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800488 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700489 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800490 return result;
491 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800492 } else {
493 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
494 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
495 hidl_vec<SubSample> hidlSubSamples;
496 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
497
498 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
499 hardware::cas::native::V1_0::DestinationBuffer dst;
500 if (secure) {
501 dst.type = BufferType::NATIVE_HANDLE;
502 dst.secureMemory = hardware::hidl_handle(block->handle());
503 } else {
504 dst.type = BufferType::SHARED_MEMORY;
505 dst.nonsecureMemory = src;
506 }
507
508 CasStatus status = CasStatus::OK;
509 hidl_string detailedError;
510 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
511
512 if (key != nullptr) {
513 sctrl = (ScramblingControl)key[0];
514 // Adjust for the PES offset
515 codecDataOffset = key[2] | (key[3] << 8);
516 }
517
518 auto returnVoid = mDescrambler->descramble(
519 sctrl,
520 hidlSubSamples,
521 src,
522 0,
523 dst,
524 0,
525 [&status, &result, &detailedError] (
526 CasStatus _status, uint32_t _bytesWritten,
527 const hidl_string& _detailedError) {
528 status = _status;
529 result = (ssize_t)_bytesWritten;
530 detailedError = _detailedError;
531 });
Arun Johnson634d0802023-02-14 22:07:51 +0000532 if (errorDetailMsg) {
533 errorDetailMsg->setTo(detailedError.c_str(), detailedError.size());
534 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800535 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
536 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
537 mName, returnVoid.description().c_str(), status, result);
538 return UNKNOWN_ERROR;
539 }
540
541 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700542 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
543 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800544 return BAD_VALUE;
545 }
546 }
547 if (!secure) {
548 C2WriteView view = block->map().get();
549 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700550 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
551 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800552 return UNKNOWN_ERROR;
553 }
554 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700555 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
556 "(non-secure)",
557 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800558 return UNKNOWN_ERROR;
559 }
560 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
561 }
562 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
563 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
564 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700565 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800566 return -ENOSYS;
567 }
568 return OK;
569}
570
Pawin Vongmasa36653902018-11-15 00:10:25 -0800571status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
572 QueueGuard guard(mSync);
573 if (!guard.isRunning()) {
574 ALOGD("[%s] No more buffers should be queued at current state.", mName);
575 return -ENOSYS;
576 }
577 return queueInputBufferInternal(buffer);
578}
579
580status_t CCodecBufferChannel::queueSecureInputBuffer(
581 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
582 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
583 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
584 AString *errorDetailMsg) {
585 QueueGuard guard(mSync);
586 if (!guard.isRunning()) {
587 ALOGD("[%s] No more buffers should be queued at current state.", mName);
588 return -ENOSYS;
589 }
590
591 if (!hasCryptoOrDescrambler()) {
592 return -ENOSYS;
593 }
594 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
595
Sungtak Lee04b30352020-07-27 13:57:25 -0700596 std::shared_ptr<C2LinearBlock> block;
597 size_t allocSize = buffer->size();
598 size_t bufferSize = 0;
599 c2_status_t blockRes = C2_OK;
600 bool copied = false;
Arun Johnson7ba67072023-11-06 22:23:04 +0000601 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
602 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
Sungtak Lee04b30352020-07-27 13:57:25 -0700603 if (mSendEncryptedInfoBuffer) {
604 static const C2MemoryUsage kDefaultReadWriteUsage{
605 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
606 constexpr int kAllocGranule0 = 1024 * 64;
607 constexpr int kAllocGranule1 = 1024 * 1024;
608 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
609 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
610 if (allocSize <= kAllocGranule1) {
611 bufferSize = align(allocSize, kAllocGranule0);
612 } else {
613 bufferSize = align(allocSize, kAllocGranule1);
614 }
615 blockRes = pool->fetchLinearBlock(
616 bufferSize, kDefaultReadWriteUsage, &block);
617
618 if (blockRes == C2_OK) {
619 C2WriteView view = block->map().get();
620 if (view.error() == C2_OK && view.size() == bufferSize) {
621 copied = true;
622 // TODO: only copy clear sections
623 memcpy(view.data(), buffer->data(), allocSize);
624 }
625 }
626 }
627
628 if (!copied) {
629 block.reset();
630 }
631
Pawin Vongmasa36653902018-11-15 00:10:25 -0800632 ssize_t result = -1;
633 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700634 if (numSubSamples == 1
635 && subSamples[0].mNumBytesOfClearData == 0
636 && subSamples[0].mNumBytesOfEncryptedData == 0) {
637 // We don't need to go through crypto or descrambler if the input is empty.
638 result = 0;
639 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700640 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800641 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700642 destination.type = DrmBufferType::NATIVE_HANDLE;
643 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800644 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700645 destination.type = DrmBufferType::SHARED_MEMORY;
646 IMemoryToSharedBuffer(
647 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800648 }
Robert Shih895fba92019-07-16 16:29:44 -0700649 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800650 encryptedBuffer->fillSourceBuffer(&source);
651 result = mCrypto->decrypt(
652 key, iv, mode, pattern, source, buffer->offset(),
653 subSamples, numSubSamples, destination, errorDetailMsg);
654 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700655 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800656 return result;
657 }
Robert Shih895fba92019-07-16 16:29:44 -0700658 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800659 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
660 }
661 } else {
662 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
663 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
664 hidl_vec<SubSample> hidlSubSamples;
665 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
666
667 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
668 encryptedBuffer->fillSourceBuffer(&srcBuffer);
669
670 DestinationBuffer dstBuffer;
671 if (secure) {
672 dstBuffer.type = BufferType::NATIVE_HANDLE;
673 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
674 } else {
675 dstBuffer.type = BufferType::SHARED_MEMORY;
676 dstBuffer.nonsecureMemory = srcBuffer;
677 }
678
679 CasStatus status = CasStatus::OK;
680 hidl_string detailedError;
681 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
682
683 if (key != nullptr) {
684 sctrl = (ScramblingControl)key[0];
685 // Adjust for the PES offset
686 codecDataOffset = key[2] | (key[3] << 8);
687 }
688
689 auto returnVoid = mDescrambler->descramble(
690 sctrl,
691 hidlSubSamples,
692 srcBuffer,
693 0,
694 dstBuffer,
695 0,
696 [&status, &result, &detailedError] (
697 CasStatus _status, uint32_t _bytesWritten,
698 const hidl_string& _detailedError) {
699 status = _status;
700 result = (ssize_t)_bytesWritten;
701 detailedError = _detailedError;
702 });
703
704 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
705 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
706 mName, returnVoid.description().c_str(), status, result);
707 return UNKNOWN_ERROR;
708 }
709
710 if (result < codecDataOffset) {
711 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
712 return BAD_VALUE;
713 }
714
715 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
716
717 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
718 encryptedBuffer->copyDecryptedContentFromMemory(result);
719 }
720 }
721
722 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700723
724 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800725}
726
727void CCodecBufferChannel::feedInputBufferIfAvailable() {
728 QueueGuard guard(mSync);
729 if (!guard.isRunning()) {
730 ALOGV("[%s] We're not running --- no input buffer reported", mName);
731 return;
732 }
733 feedInputBufferIfAvailableInternal();
734}
735
736void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900737 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800738 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700739 }
740 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700741 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700742 if (!output->buffers ||
743 output->buffers->hasPending() ||
Wonsik Kim3722abc2023-05-17 13:26:31 -0700744 (!output->bounded && output->buffers->numActiveSlots() >= output->numSlots)) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800745 return;
746 }
747 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700748 size_t numActiveSlots = 0;
749 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800750 sp<MediaCodecBuffer> inBuffer;
751 size_t index;
752 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700753 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700754 numActiveSlots = input->buffers->numActiveSlots();
755 if (numActiveSlots >= input->numSlots) {
756 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800757 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700758 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800760 break;
761 }
762 }
763 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
764 mCallback->onInputBufferAvailable(index, inBuffer);
765 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700766 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800767}
768
769status_t CCodecBufferChannel::renderOutputBuffer(
770 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800771 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800772 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800773 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800774 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700775 Mutexed<Output>::Locked output(mOutput);
776 if (output->buffers) {
777 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800778 }
779 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800780 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
781 // set to true.
782 sendOutputBuffers();
783 // input buffer feeding may have been gated by pending output buffers
784 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800785 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800786 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700787 std::call_once(mRenderWarningFlag, [this] {
788 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
789 "timestamp or render=true with non-video buffers. Apps should "
790 "call releaseOutputBuffer() with render=false for those.",
791 mName);
792 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800793 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800794 return INVALID_OPERATION;
795 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800796
797#if 0
798 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
799 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
800 for (const std::shared_ptr<const C2Info> &info : infoParams) {
801 AString res;
802 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
803 if (ix) res.append(", ");
804 res.append(*((int32_t*)info.get() + (ix / 4)));
805 }
806 ALOGV(" [%s]", res.c_str());
807 }
808#endif
809 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
810 std::static_pointer_cast<const C2StreamRotationInfo::output>(
811 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
812 bool flip = rotation && (rotation->flip & 1);
813 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900814
815 {
816 Mutexed<OutputSurface>::Locked output(mOutputSurface);
817 if (output->surface == nullptr) {
818 ALOGI("[%s] cannot render buffer without surface", mName);
819 return OK;
820 }
821 int64_t frameIndex;
822 buffer->meta()->findInt64("frameIndex", &frameIndex);
823 if (output->rotation.count(frameIndex) != 0) {
824 auto it = output->rotation.find(frameIndex);
825 quarters = (it->second / 90) & 3;
826 output->rotation.erase(it);
827 }
828 }
829
Pawin Vongmasa36653902018-11-15 00:10:25 -0800830 uint32_t transform = 0;
831 switch (quarters) {
832 case 0: // no rotation
833 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
834 break;
835 case 1: // 90 degrees counter-clockwise
836 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
837 : HAL_TRANSFORM_ROT_270;
838 break;
839 case 2: // 180 degrees
840 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
841 break;
842 case 3: // 90 degrees clockwise
843 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
844 : HAL_TRANSFORM_ROT_90;
845 break;
846 }
847
848 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
849 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
850 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
851 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
852 if (surfaceScaling) {
853 videoScalingMode = surfaceScaling->value;
854 }
855
856 // Use dataspace from format as it has the default aspects already applied
857 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
858 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
859
860 // HDR static info
861 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
862 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
863 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
864
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800865 // HDR10 plus info
866 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
867 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
868 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800869 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
870 hdr10PlusInfo.reset();
871 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800872
Wonsik Kima79c5522022-01-18 16:29:24 -0800873 // HDR dynamic info
874 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
875 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
876 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
877 // TODO: make this sticky & enable unset
878 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
879 hdrDynamicInfo.reset();
880 }
881
882 if (hdr10PlusInfo) {
883 // C2StreamHdr10PlusInfo is deprecated; components should use
884 // C2StreamHdrDynamicMetadataInfo
885 // TODO: #metric
886 if (hdrDynamicInfo) {
887 // It is unexpected that C2StreamHdr10PlusInfo and
888 // C2StreamHdrDynamicMetadataInfo is both present.
889 // C2StreamHdrDynamicMetadataInfo takes priority.
890 // TODO: #metric
891 } else {
892 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
893 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
894 hdr10PlusInfo->flexCount(),
895 0u,
896 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
897 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
898 hdrDynamicInfo = info;
899 }
900 }
901
Pawin Vongmasa36653902018-11-15 00:10:25 -0800902 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
903 if (blocks.size() != 1u) {
904 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
905 return UNKNOWN_ERROR;
906 }
907 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700908 C2Fence c2fence = block.fence();
909 sp<Fence> fence = Fence::NO_FENCE;
910 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
911 // Once C2Fence::type() is added, check the exact C2Fence type
912 if (c2fence.isHW()) {
913 int fenceFd = c2fence.fd();
914 fence = sp<Fence>::make(fenceFd);
915 if (!fence) {
916 ALOGE("[%s] Failed to allocate a fence", mName);
917 close(fenceFd);
918 return NO_MEMORY;
919 }
920 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800921
922 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -0700923 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800924 timestampNs,
925 false, // droppable
926 dataSpace,
927 Rect(blocks.front().crop().left,
928 blocks.front().crop().top,
929 blocks.front().crop().right(),
930 blocks.front().crop().bottom()),
931 videoScalingMode,
932 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700933 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800934 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800935 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800936 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800937 // If mastering max and min luminance fields are 0, do not use them.
938 // It indicates the value may not be present in the stream.
939 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
940 hdrStaticInfo->mastering.minLuminance > 0.0f) {
941 struct android_smpte2086_metadata smpte2086_meta = {
942 .displayPrimaryRed = {
943 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
944 },
945 .displayPrimaryGreen = {
946 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
947 },
948 .displayPrimaryBlue = {
949 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
950 },
951 .whitePoint = {
952 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
953 },
954 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
955 .minLuminance = hdrStaticInfo->mastering.minLuminance,
956 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800957 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800958 hdr.smpte2086 = smpte2086_meta;
959 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700960 // If the content light level fields are 0, do not use them, it
961 // indicates the value may not be present in the stream.
962 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
963 struct android_cta861_3_metadata cta861_meta = {
964 .maxContentLightLevel = hdrStaticInfo->maxCll,
965 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
966 };
967 hdr.validTypes |= HdrMetadata::CTA861_3;
968 hdr.cta8613 = cta861_meta;
969 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900970
971 // does not have valid info
972 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
973 hdrStaticInfo.reset();
974 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800975 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800976 if (hdrDynamicInfo
977 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800978 hdr.validTypes |= HdrMetadata::HDR10PLUS;
979 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800980 hdrDynamicInfo->m.data,
981 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800982 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800983 qbi.setHdrMetadata(hdr);
984 }
Hongguangfc1478a2022-07-20 22:56:06 -0700985 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
986
Brian Lindahl932bf602023-03-09 11:59:48 -0700987 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
988 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
989 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800990 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
991 if (result != OK) {
992 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800993 if (result == NO_INIT) {
994 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
995 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800996 return result;
997 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800998
999 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
1000 ALOGD("[%s] queue buffer successful", mName);
1001 } else {
1002 ALOGV("[%s] queue buffer successful", mName);
1003 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001004
1005 int64_t mediaTimeUs = 0;
1006 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahl83931482023-08-10 10:12:49 -06001007 if (mAreRenderMetricsEnabled && mIsSurfaceToDisplay) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001008 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
1009 processRenderedFrames(qbo.frameTimestamps);
1010 } else {
1011 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
1012 // when the frame is queued to the non-display surface
1013 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1014 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001015
1016 return OK;
1017}
1018
Brian Lindahl932bf602023-03-09 11:59:48 -07001019void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001020 mTrackedFrames.clear();
1021
1022 int isSurfaceToDisplay = 0;
1023 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1024 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1025 // No frame tracking is needed if we're not sending frames to the display
1026 if (!mIsSurfaceToDisplay) {
1027 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1028 return;
1029 }
1030
Brian Lindahl932bf602023-03-09 11:59:48 -07001031 int hasPresentFenceTimes = 0;
1032 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1033 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
Brian Lindahl119e0c22023-05-19 15:42:13 -06001034 if (!mHasPresentFenceTimes) {
Brian Lindahl932bf602023-03-09 11:59:48 -07001035 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1036 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001037}
1038
1039void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1040 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1041 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1042 // so track the frame as if the desired render time is now.
1043 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1044 if (desiredRenderTimeNs < nowNs) {
1045 desiredRenderTimeNs = nowNs;
1046 }
Brian Lindahl87acc502023-11-15 10:10:51 -07001047
1048 // If the render time is more than a second from now, then pretend the frame is supposed to be
1049 // rendered immediately, because that's what SurfaceFlinger heuristics will do. This is a tight
1050 // coupling, but is really the only way to optimize away unnecessary present fence checks in
1051 // processRenderedFrames.
1052 if (desiredRenderTimeNs > nowNs + 1*1000*1000*1000LL) {
1053 desiredRenderTimeNs = nowNs;
1054 }
1055
Brian Lindahl932bf602023-03-09 11:59:48 -07001056 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1057 // actually rendered.
1058 TrackedFrame frame;
1059 frame.number = qbo.nextFrameNumber - 1;
1060 frame.mediaTimeUs = mediaTimeUs;
1061 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1062 frame.latchTime = -1;
1063 frame.presentFence = nullptr;
1064 mTrackedFrames.push_back(frame);
1065}
1066
1067void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1068 // Grab the latch times and present fences from the frame event deltas
1069 for (const auto& delta : deltas) {
1070 for (auto& frame : mTrackedFrames) {
1071 if (delta.getFrameNumber() == frame.number) {
1072 delta.getLatchTime(&frame.latchTime);
1073 delta.getDisplayPresentFence(&frame.presentFence);
1074 }
1075 }
1076 }
1077
1078 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1079 // in fact, been rendered.
1080 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1081 while (!mTrackedFrames.empty()) {
1082 TrackedFrame & frame = mTrackedFrames.front();
1083 // Frames that should have been rendered at least 100ms in the past are checked
1084 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1085 break;
1086 }
1087
1088 // If we don't have a render time by now, then consider the frame as dropped
1089 int64_t renderTimeNs = getRenderTimeNs(frame);
1090 if (renderTimeNs != -1) {
1091 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1092 }
1093 mTrackedFrames.pop_front();
1094 }
1095}
1096
1097int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1098 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1099 if (!mHasPresentFenceTimes) {
1100 if (frame.latchTime == -1) {
1101 ALOGD("no latch time for frame %d", (int) frame.number);
1102 return -1;
1103 }
1104 return frame.latchTime;
1105 }
1106
1107 if (frame.presentFence == nullptr) {
1108 ALOGW("no present fence for frame %d", (int) frame.number);
1109 return -1;
1110 }
1111
1112 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1113
1114 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1115 ALOGW("invalid signal time for frame %d", (int) frame.number);
1116 return -1;
1117 }
1118
1119 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1120 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1121 return -1;
1122 }
1123
1124 return actualRenderTimeNs;
1125}
1126
1127void CCodecBufferChannel::pollForRenderedBuffers() {
1128 FrameEventHistoryDelta delta;
1129 mComponent->pollForRenderedFrames(&delta);
1130 processRenderedFrames(delta);
1131}
1132
Sungtak Lee214ce612023-11-01 10:01:13 +00001133void CCodecBufferChannel::onBufferReleasedFromOutputSurface(uint32_t generation) {
Sungtak Lee6700cc92023-11-22 18:04:05 +00001134 // Note: Since this is called asynchronously from IProducerListener not
1135 // knowing the internal state of CCodec/CCodecBufferChannel,
1136 // prevent mComponent from being destroyed by holding the shared reference
1137 // during this interface being executed.
1138 std::shared_ptr<Codec2Client::Component> comp = mComponent;
1139 if (comp) {
1140 comp->onBufferReleasedFromOutputSurface(generation);
1141 }
Sungtak Lee214ce612023-11-01 10:01:13 +00001142}
1143
Pawin Vongmasa36653902018-11-15 00:10:25 -08001144status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1145 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1146 bool released = false;
1147 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001148 Mutexed<Input>::Locked input(mInput);
1149 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001150 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001151 }
1152 }
1153 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001154 Mutexed<Output>::Locked output(mOutput);
1155 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001156 released = true;
1157 }
1158 }
1159 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001160 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001161 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001162 } else {
1163 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1164 }
1165 return OK;
1166}
1167
1168void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1169 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001170 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001171
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001172 if (!input->buffers) {
1173 ALOGE("getInputBufferArray: No Input Buffers allocated");
1174 return;
1175 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001176 if (!input->buffers->isArrayMode()) {
1177 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001178 }
1179
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001180 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001181}
1182
1183void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1184 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001185 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001186 if (!output->buffers) {
1187 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1188 return;
1189 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001190 if (!output->buffers->isArrayMode()) {
1191 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001192 }
1193
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001194 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001195}
1196
1197status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001198 const sp<AMessage> &inputFormat,
1199 const sp<AMessage> &outputFormat,
1200 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001201 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1202 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001203 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001204 C2PortReorderBufferDepthTuning::output reorderDepth;
1205 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001206 C2PortActualDelayTuning::input inputDelay(0);
1207 C2PortActualDelayTuning::output outputDelay(0);
1208 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001209 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001210
Pawin Vongmasa36653902018-11-15 00:10:25 -08001211 c2_status_t err = mComponent->query(
1212 {
1213 &iStreamFormat,
1214 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001215 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001216 &reorderDepth,
1217 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001218 &inputDelay,
1219 &pipelineDelay,
1220 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001221 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001222 },
1223 {},
1224 C2_DONT_BLOCK,
1225 nullptr);
1226 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001227 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001228 return UNKNOWN_ERROR;
1229 }
1230 } else if (err != C2_OK) {
1231 return UNKNOWN_ERROR;
1232 }
1233
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001234 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1235 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1236 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1237
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001238 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1239 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001240
Pawin Vongmasa36653902018-11-15 00:10:25 -08001241 // TODO: get this from input format
1242 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1243
Sungtak Lee04b30352020-07-27 13:57:25 -07001244 // secure mode is a static parameter (shall not change in the executing state)
1245 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1246
Pawin Vongmasa36653902018-11-15 00:10:25 -08001247 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001248 int poolMask = GetCodec2PoolMask();
1249 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001250
1251 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001252 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001253 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001254 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1255 API_REFLECTION |
1256 API_VALUES |
1257 API_CURRENT_VALUES |
1258 API_DEPENDENCY |
1259 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001260 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1261 C2StreamSampleRateInfo::input sampleRate(0u);
1262 C2StreamChannelCountInfo::input channelCount(0u);
1263 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001264 std::shared_ptr<C2BlockPool> pool;
1265 {
1266 Mutexed<BlockPools>::Locked pools(mBlockPools);
1267
1268 // set default allocator ID.
1269 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001270 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001271
1272 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1273 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1274 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001275 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001276 std::vector<C2Param *> stackParams({&featuresSetting});
1277 if (audioEncoder) {
1278 stackParams.push_back(&encoderFrameSize);
1279 stackParams.push_back(&sampleRate);
1280 stackParams.push_back(&channelCount);
1281 stackParams.push_back(&pcmEncoding);
1282 } else {
1283 encoderFrameSize.invalidate();
1284 sampleRate.invalidate();
1285 channelCount.invalidate();
1286 pcmEncoding.invalidate();
1287 }
1288 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001289 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1290 C2_DONT_BLOCK,
1291 &params);
1292 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1293 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1294 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001295 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001296 C2PortAllocatorsTuning::input *inputAllocators =
1297 C2PortAllocatorsTuning::input::From(params[0].get());
1298 if (inputAllocators && inputAllocators->flexCount() > 0) {
1299 std::shared_ptr<C2Allocator> allocator;
1300 // verify allocator IDs and resolve default allocator
1301 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1302 if (allocator) {
1303 pools->inputAllocatorId = allocator->getId();
1304 } else {
1305 ALOGD("[%s] component requested invalid input allocator ID %u",
1306 mName, inputAllocators->m.values[0]);
1307 }
1308 }
1309 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001310 if (featuresSetting) {
1311 apiFeatures = featuresSetting.value;
1312 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001313
1314 // TODO: use C2Component wrapper to associate this pool with ourselves
1315 if ((poolMask >> pools->inputAllocatorId) & 1) {
1316 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1317 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1318 mName, pools->inputAllocatorId,
1319 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1320 asString(err), err);
1321 } else {
1322 err = C2_NOT_FOUND;
1323 }
1324 if (err != C2_OK) {
1325 C2BlockPool::local_id_t inputPoolId =
1326 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1327 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1328 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1329 mName, (unsigned long long)inputPoolId,
1330 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1331 asString(err), err);
1332 if (err != C2_OK) {
1333 return NO_MEMORY;
1334 }
1335 }
1336 pools->inputPool = pool;
1337 }
1338
Wonsik Kim51051262018-11-28 13:59:05 -08001339 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001340 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001341 input->inputDelay = inputDelayValue;
1342 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001343 input->numSlots = numInputSlots;
1344 input->extraBuffers.flush();
1345 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001346 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001347 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1348 input->frameReassembler.init(
1349 pool,
1350 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1351 encoderFrameSize.value,
1352 sampleRate.value,
1353 channelCount.value,
1354 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1355 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001356 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1357 // For encrypted content, framework decrypts source buffer (ashmem) into
1358 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001359 if (!buffersBoundToCodec
1360 && !input->frameReassembler
1361 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001362 input->buffers.reset(new SlotInputBuffers(mName));
1363 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001364 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001365 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001366 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001367 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001368 // This is to ensure buffers do not get released prematurely.
1369 // TODO: handle this without going into array mode
1370 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001371 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001372 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001373 }
1374 } else {
1375 if (hasCryptoOrDescrambler()) {
1376 int32_t capacity = kLinearBufferSize;
1377 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1378 if ((size_t)capacity > kMaxLinearBufferSize) {
1379 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1380 capacity = kMaxLinearBufferSize;
1381 }
1382 if (mDealer == nullptr) {
1383 mDealer = new MemoryDealer(
1384 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001385 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001386 "EncryptedLinearInputBuffers");
1387 mDecryptDestination = mDealer->allocate((size_t)capacity);
1388 }
1389 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001390 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1391 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001392 } else {
1393 mHeapSeqNum = -1;
1394 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001395 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001396 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001397 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001398 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001399 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001400 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001401 }
1402 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001403 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001404
1405 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001406 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001407 } else {
1408 // TODO: error
1409 }
Wonsik Kim51051262018-11-28 13:59:05 -08001410
1411 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001412 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001413 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001414 }
1415
1416 if (outputFormat != nullptr) {
1417 sp<IGraphicBufferProducer> outputSurface;
1418 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001419 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001420 {
1421 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001422 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001423 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001424 outputSurface = output->surface ?
1425 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001426 if (outputSurface) {
1427 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1428 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001429 outputGeneration = output->generation;
1430 }
1431
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001432 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001433 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001434 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001435
1436 {
1437 Mutexed<BlockPools>::Locked pools(mBlockPools);
1438
David Stevensc3fbb282021-01-18 18:11:20 +09001439 prevOutputPoolId = pools->outputPoolId;
1440
Pawin Vongmasa36653902018-11-15 00:10:25 -08001441 // set default allocator ID.
1442 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001443 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001444
1445 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1446 // unsuccessful.
1447 std::vector<std::unique_ptr<C2Param>> params;
1448 err = mComponent->query({ },
1449 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1450 C2_DONT_BLOCK,
1451 &params);
1452 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1453 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1454 mName, params.size(), asString(err), err);
1455 } else if (err == C2_OK && params.size() == 1) {
1456 C2PortAllocatorsTuning::output *outputAllocators =
1457 C2PortAllocatorsTuning::output::From(params[0].get());
1458 if (outputAllocators && outputAllocators->flexCount() > 0) {
1459 std::shared_ptr<C2Allocator> allocator;
1460 // verify allocator IDs and resolve default allocator
1461 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1462 if (allocator) {
1463 pools->outputAllocatorId = allocator->getId();
1464 } else {
1465 ALOGD("[%s] component requested invalid output allocator ID %u",
1466 mName, outputAllocators->m.values[0]);
1467 }
1468 }
1469 }
1470
1471 // use bufferqueue if outputting to a surface.
1472 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1473 // if unsuccessful.
1474 if (outputSurface) {
1475 params.clear();
1476 err = mComponent->query({ },
1477 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1478 C2_DONT_BLOCK,
1479 &params);
1480 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1481 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1482 mName, params.size(), asString(err), err);
1483 } else if (err == C2_OK && params.size() == 1) {
1484 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1485 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1486 if (surfaceAllocator) {
1487 std::shared_ptr<C2Allocator> allocator;
1488 // verify allocator IDs and resolve default allocator
1489 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1490 if (allocator) {
1491 pools->outputAllocatorId = allocator->getId();
1492 } else {
1493 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1494 mName, surfaceAllocator->value);
1495 err = C2_BAD_VALUE;
1496 }
1497 }
1498 }
1499 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1500 && err != C2_OK
1501 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1502 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1503 }
1504 }
1505
1506 if ((poolMask >> pools->outputAllocatorId) & 1) {
1507 err = mComponent->createBlockPool(
1508 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1509 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1510 mName, pools->outputAllocatorId,
1511 (unsigned long long)pools->outputPoolId,
1512 asString(err));
1513 } else {
1514 err = C2_NOT_FOUND;
1515 }
1516 if (err != C2_OK) {
1517 // use basic pool instead
1518 pools->outputPoolId =
1519 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1520 }
1521
1522 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1523 // component.
1524 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1525 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1526
1527 std::vector<std::unique_ptr<C2SettingResult>> failures;
1528 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1529 ALOGD("[%s] Configured output block pool ids %llu => %s",
1530 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1531 outputPoolId_ = pools->outputPoolId;
1532 }
1533
David Stevensc3fbb282021-01-18 18:11:20 +09001534 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1535 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1536 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1537 if (err != C2_OK) {
1538 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1539 (unsigned long long) prevOutputPoolId, asString(err), err);
1540 }
1541 }
1542
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001543 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001544 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001545 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001546 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001547 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001548 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001549 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001550 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001551 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001552 }
1553 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001554 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001555 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001556 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001557
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001558 output->buffers->clearStash();
1559 if (reorderDepth) {
1560 output->buffers->setReorderDepth(reorderDepth.value);
1561 }
1562 if (reorderKey) {
1563 output->buffers->setReorderKey(reorderKey.value);
1564 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001565
1566 // Try to set output surface to created block pool if given.
1567 if (outputSurface) {
1568 mComponent->setOutputSurface(
1569 outputPoolId_,
1570 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001571 outputGeneration,
1572 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001573 } else {
1574 // configure CPU read consumer usage
1575 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1576 std::vector<std::unique_ptr<C2SettingResult>> failures;
1577 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1578 // do not print error message for now as most components may not yet
1579 // support this setting
1580 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1581 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001582 }
1583
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001584 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001585 if (buffersBoundToCodec) {
1586 // WORKAROUND: if we're using early CSD workaround we convert to
1587 // array mode, to appease apps assuming the output
1588 // buffers to be of the same size.
1589 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1590 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001591
1592 int32_t channelCount;
1593 int32_t sampleRate;
1594 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1595 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1596 int32_t delay = 0;
1597 int32_t padding = 0;;
1598 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1599 delay = 0;
1600 }
1601 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1602 padding = 0;
1603 }
1604 if (delay || padding) {
1605 // We need write access to the buffers, and we're already in
1606 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001607 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001608 }
1609 }
1610 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001611
1612 int32_t tunneled = 0;
1613 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1614 tunneled = 0;
1615 }
1616 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001617 }
1618
1619 // Set up pipeline control. This has to be done after mInputBuffers and
1620 // mOutputBuffers are initialized to make sure that lingering callbacks
1621 // about buffers from the previous generation do not interfere with the
1622 // newly initialized pipeline capacity.
1623
Wonsik Kim62545252021-01-20 11:25:41 -08001624 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001625 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001626 watcher->inputDelay(inputDelayValue)
1627 .pipelineDelay(pipelineDelayValue)
1628 .outputDelay(outputDelayValue)
Houxiang Dai0b573282023-03-11 18:31:56 +08001629 .smoothnessFactor(kSmoothnessFactor)
1630 .tunneled(mTunneled);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001631 watcher->flush();
1632 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001633
1634 mInputMetEos = false;
1635 mSync.start();
1636 return OK;
1637}
1638
Wonsik Kim34b28b42022-05-20 15:49:32 -07001639status_t CCodecBufferChannel::prepareInitialInputBuffers(
1640 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001641 if (mInputSurface) {
1642 return OK;
1643 }
1644
Wonsik Kim34b28b42022-05-20 15:49:32 -07001645 size_t numInputSlots = mInput.lock()->numSlots;
1646
1647 {
1648 Mutexed<Input>::Locked input(mInput);
1649 while (clientInputBuffers->size() < numInputSlots) {
1650 size_t index;
1651 sp<MediaCodecBuffer> buffer;
1652 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1653 break;
1654 }
1655 clientInputBuffers->emplace(index, buffer);
1656 }
1657 }
1658 if (clientInputBuffers->empty()) {
1659 ALOGW("[%s] start: cannot allocate memory at all", mName);
1660 return NO_MEMORY;
1661 } else if (clientInputBuffers->size() < numInputSlots) {
1662 ALOGD("[%s] start: cannot allocate memory for all slots, "
1663 "only %zu buffers allocated",
1664 mName, clientInputBuffers->size());
1665 } else {
1666 ALOGV("[%s] %zu initial input buffers available",
1667 mName, clientInputBuffers->size());
1668 }
1669 return OK;
1670}
1671
1672status_t CCodecBufferChannel::requestInitialInputBuffers(
1673 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001674 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001675 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1676 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1677 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001678 return UNKNOWN_ERROR;
1679 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001680
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001681 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1682 mFlushedConfigs.lock()->swap(flushedConfigs);
1683 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001684 {
1685 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1686 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1687 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1688 watcher->onWorkQueued(
1689 work->input.ordinal.frameIndex.peeku(),
1690 std::vector(work->input.buffers),
1691 now);
1692 }
1693 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001694 err = mComponent->queue(&flushedConfigs);
1695 if (err != C2_OK) {
1696 ALOGW("[%s] Error while queueing a flushed config", mName);
1697 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001698 }
1699 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001700 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001701 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1702 !clientInputBuffers.empty()) {
1703 size_t minIndex = clientInputBuffers.begin()->first;
1704 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1705 for (const auto &[index, buffer] : clientInputBuffers) {
1706 if (minBuffer->capacity() > buffer->capacity()) {
1707 minIndex = index;
1708 minBuffer = buffer;
1709 }
1710 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001711 // WORKAROUND: Some apps expect CSD available without queueing
1712 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001713 minBuffer->setRange(0, 0);
1714 minBuffer->meta()->clear();
1715 minBuffer->meta()->setInt64("timeUs", 0);
1716 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001717 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1718 mName);
1719 return UNKNOWN_ERROR;
1720 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001721 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001722 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001723
Wonsik Kim34b28b42022-05-20 15:49:32 -07001724 for (const auto &[index, buffer] : clientInputBuffers) {
1725 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001726 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001727
Pawin Vongmasa36653902018-11-15 00:10:25 -08001728 return OK;
1729}
1730
1731void CCodecBufferChannel::stop() {
1732 mSync.stop();
1733 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001734}
1735
Sungtak Lee99144332023-01-26 11:03:14 +00001736void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
1737 sp<Surface> surface = mOutputSurface.lock()->surface;
1738 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00001739 C2BlockPool::local_id_t outputPoolId;
1740 {
1741 Mutexed<BlockPools>::Locked pools(mBlockPools);
1742 outputPoolId = pools->outputPoolId;
1743 }
1744 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00001745
1746 if (pushBlankBuffer) {
1747 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
1748 if (anw) {
1749 pushBlankBuffersToNativeWindow(anw.get());
1750 }
1751 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00001752 }
1753}
1754
Wonsik Kim936a89c2020-05-08 16:07:50 -07001755void CCodecBufferChannel::reset() {
1756 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001757 if (mInputSurface != nullptr) {
1758 mInputSurface.reset();
1759 }
1760 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001761 {
1762 Mutexed<Input>::Locked input(mInput);
1763 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001764 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001765 }
1766 {
1767 Mutexed<Output>::Locked output(mOutput);
1768 output->buffers.reset();
1769 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001770 // reset the frames that are being tracked for onFrameRendered callbacks
1771 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001772}
1773
1774void CCodecBufferChannel::release() {
1775 mComponent.reset();
1776 mInputAllocator.reset();
1777 mOutputSurface.lock()->surface.clear();
1778 {
1779 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1780 blockPools->inputPool.reset();
1781 blockPools->outputPoolIntf.reset();
1782 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001783 setCrypto(nullptr);
1784 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001785}
1786
Pawin Vongmasa36653902018-11-15 00:10:25 -08001787void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1788 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001789 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001790 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001791 {
1792 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1793 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1794 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1795 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1796 watcher->onWorkDone(frameIndex);
1797 continue;
1798 }
1799 if (work->input.buffers.empty()
1800 || work->input.buffers.front() == nullptr
1801 || work->input.buffers.front()->data().linearBlocks().empty()) {
1802 ALOGD("[%s] no linear codec config data found", mName);
1803 watcher->onWorkDone(frameIndex);
1804 continue;
1805 }
1806 std::unique_ptr<C2Work> copy(new C2Work);
1807 copy->input.flags = C2FrameData::flags_t(
1808 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1809 copy->input.ordinal = work->input.ordinal;
1810 copy->input.ordinal.frameIndex = mFrameIndex++;
1811 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1812 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1813 }
1814 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1815 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1816 }
1817 copy->input.infoBuffers.insert(
1818 copy->input.infoBuffers.begin(),
1819 work->input.infoBuffers.begin(),
1820 work->input.infoBuffers.end());
1821 copy->worklets.emplace_back(new C2Worklet);
1822 configs.push_back(std::move(copy));
1823 watcher->onWorkDone(frameIndex);
1824 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001825 }
1826 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001827 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001828 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001829 Mutexed<Input>::Locked input(mInput);
1830 input->buffers->flush();
1831 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001832 }
1833 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001834 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001835 if (output->buffers) {
1836 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001837 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001838 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001839 }
1840}
1841
1842void CCodecBufferChannel::onWorkDone(
1843 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001844 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001845 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001846 feedInputBufferIfAvailable();
1847 }
1848}
1849
1850void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001851 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001852 if (mInputSurface) {
1853 return;
1854 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001855 std::shared_ptr<C2Buffer> buffer =
1856 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001857 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001858 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001859 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001860 if (input->lastFlushIndex >= frameIndex) {
1861 ALOGD("[%s] Ignoring stale input buffer done callback: "
1862 "last flush index = %lld, frameIndex = %lld",
1863 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1864 } else {
1865 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1866 if (!newInputSlotAvailable) {
1867 (void)input->extraBuffers.expireComponentBuffer(buffer);
1868 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001869 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001870 }
1871 if (newInputSlotAvailable) {
1872 feedInputBufferIfAvailable();
1873 }
1874}
1875
1876bool CCodecBufferChannel::handleWork(
1877 std::unique_ptr<C2Work> work,
1878 const sp<AMessage> &outputFormat,
1879 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001880 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001881 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001882 if (!output->buffers) {
1883 return false;
1884 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001885 }
1886
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001887 // Whether the output buffer should be reported to the client or not.
1888 bool notifyClient = false;
1889
1890 if (work->result == C2_OK){
1891 notifyClient = true;
1892 } else if (work->result == C2_NOT_FOUND) {
1893 ALOGD("[%s] flushed work; ignored.", mName);
1894 } else {
1895 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1896 // the config update.
1897 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1898 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1899 return false;
1900 }
1901
1902 if ((work->input.ordinal.frameIndex -
1903 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001904 // Discard frames from previous generation.
1905 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001906 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001907 }
1908
Wonsik Kim524b0582019-03-12 11:28:57 -07001909 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001910 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001911 || !(work->worklets.front()->output.flags &
1912 C2FrameData::FLAG_INCOMPLETE))) {
1913 mPipelineWatcher.lock()->onWorkDone(
1914 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001915 }
1916
1917 // NOTE: MediaCodec usage supposedly have only one worklet
1918 if (work->worklets.size() != 1u) {
1919 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1920 mName, work->worklets.size());
1921 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1922 return false;
1923 }
1924
1925 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1926
1927 std::shared_ptr<C2Buffer> buffer;
1928 // NOTE: MediaCodec usage supposedly have only one output stream.
1929 if (worklet->output.buffers.size() > 1u) {
1930 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1931 mName, worklet->output.buffers.size());
1932 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1933 return false;
1934 } else if (worklet->output.buffers.size() == 1u) {
1935 buffer = worklet->output.buffers[0];
1936 if (!buffer) {
1937 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1938 }
1939 }
1940
Wonsik Kim3dedf682021-05-03 10:57:09 -07001941 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1942 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001943 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001944 while (!worklet->output.configUpdate.empty()) {
1945 std::unique_ptr<C2Param> param;
1946 worklet->output.configUpdate.back().swap(param);
1947 worklet->output.configUpdate.pop_back();
1948 switch (param->coreIndex().coreIndex()) {
1949 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1950 C2PortReorderBufferDepthTuning::output reorderDepth;
1951 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001952 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1953 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001954 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001955 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001956 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001957 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1958 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001959 }
1960 break;
1961 }
1962 case C2PortReorderKeySetting::CORE_INDEX: {
1963 C2PortReorderKeySetting::output reorderKey;
1964 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001965 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001966 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1967 mName, reorderKey.value);
1968 } else {
1969 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1970 }
1971 break;
1972 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001973 case C2PortActualDelayTuning::CORE_INDEX: {
1974 if (param->isGlobal()) {
1975 C2ActualPipelineDelayTuning pipelineDelay;
1976 if (pipelineDelay.updateFrom(*param)) {
1977 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1978 mName, pipelineDelay.value);
1979 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001980 (void)mPipelineWatcher.lock()->pipelineDelay(
1981 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001982 }
1983 }
1984 if (param->forInput()) {
1985 C2PortActualDelayTuning::input inputDelay;
1986 if (inputDelay.updateFrom(*param)) {
1987 ALOGV("[%s] onWorkDone: updating input delay %u",
1988 mName, inputDelay.value);
1989 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001990 (void)mPipelineWatcher.lock()->inputDelay(
1991 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001992 }
1993 }
1994 if (param->forOutput()) {
1995 C2PortActualDelayTuning::output outputDelay;
1996 if (outputDelay.updateFrom(*param)) {
1997 ALOGV("[%s] onWorkDone: updating output delay %u",
1998 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001999 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002000 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002001 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002002
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002003 }
2004 }
2005 break;
2006 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08002007 case C2PortTunnelSystemTime::CORE_INDEX: {
2008 C2PortTunnelSystemTime::output frameRenderTime;
2009 if (frameRenderTime.updateFrom(*param)) {
2010 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
2011 mName, (long long)frameRenderTime.value,
2012 (long long)worklet->output.ordinal.timestamp.peekll());
2013 mCCodecCallback->onOutputFramesRendered(
2014 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
2015 }
2016 break;
2017 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02002018 case C2StreamTunnelHoldRender::CORE_INDEX: {
2019 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
2020 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
2021 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
2022 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
2023 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
2024 mCCodecCallback->onFirstTunnelFrameReady();
2025 break;
2026 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002027 default:
2028 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2029 mName, param->index());
2030 break;
2031 }
2032 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002033 if (newInputDelay || newPipelineDelay) {
2034 Mutexed<Input>::Locked input(mInput);
2035 size_t newNumSlots =
2036 newInputDelay.value_or(input->inputDelay) +
2037 newPipelineDelay.value_or(input->pipelineDelay) +
2038 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08002039 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002040 if (input->buffers->isArrayMode()) {
2041 if (input->numSlots >= newNumSlots) {
2042 input->numExtraSlots = 0;
2043 } else {
2044 input->numExtraSlots = newNumSlots - input->numSlots;
2045 }
2046 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2047 mName, input->numExtraSlots);
2048 } else {
2049 input->numSlots = newNumSlots;
2050 }
2051 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002052 size_t numOutputSlots = 0;
2053 uint32_t reorderDepth = 0;
2054 bool outputBuffersChanged = false;
2055 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2056 Mutexed<Output>::Locked output(mOutput);
2057 if (!output->buffers) {
2058 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002059 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002060 numOutputSlots = output->numSlots;
2061 if (newReorderKey) {
2062 output->buffers->setReorderKey(newReorderKey.value());
2063 }
2064 if (newReorderDepth) {
2065 output->buffers->setReorderDepth(newReorderDepth.value());
2066 }
2067 reorderDepth = output->buffers->getReorderDepth();
2068 if (newOutputDelay) {
2069 output->outputDelay = newOutputDelay.value();
2070 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2071 if (output->numSlots < numOutputSlots) {
2072 output->numSlots = numOutputSlots;
2073 if (output->buffers->isArrayMode()) {
2074 OutputBuffersArray *array =
2075 (OutputBuffersArray *)output->buffers.get();
2076 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2077 mName, numOutputSlots);
2078 array->grow(numOutputSlots);
2079 outputBuffersChanged = true;
2080 }
2081 }
2082 }
2083 numOutputSlots = output->numSlots;
2084 }
2085 if (outputBuffersChanged) {
2086 mCCodecCallback->onOutputBuffersChanged();
2087 }
2088 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002089 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002090 {
2091 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2092 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002093 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002094 if (output->surface) {
2095 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2096 }
2097 }
2098 if (maxDequeueCount > 0) {
2099 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002100 }
2101 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002102
Pawin Vongmasa36653902018-11-15 00:10:25 -08002103 int32_t flags = 0;
2104 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002105 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002106 ALOGV("[%s] onWorkDone: output EOS", mName);
2107 }
2108
Pawin Vongmasa36653902018-11-15 00:10:25 -08002109 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2110 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2111 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2112 // shall correspond to the client input timesamp (in customOrdinal). By using the
2113 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2114 // produces multiple output.
2115 c2_cntr64_t timestamp =
2116 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2117 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002118 if (mInputSurface != nullptr) {
2119 // When using input surface we need to restore the original input timestamp.
2120 timestamp = work->input.ordinal.customOrdinal;
2121 }
My Name6bd9a7d2022-03-25 12:37:58 -07002122 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2123 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002124 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2125 mName,
2126 work->input.ordinal.customOrdinal.peekll(),
2127 work->input.ordinal.timestamp.peekll(),
2128 worklet->output.ordinal.timestamp.peekll(),
2129 timestamp.peekll());
2130
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002131 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002132 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002133 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002134 if (!output->buffers) {
2135 return false;
2136 }
2137 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002138 output->buffers->updateSkipCutBuffer(outputFormat);
2139 output->buffers->setFormat(outputFormat);
2140 }
2141 if (!notifyClient) {
2142 return false;
2143 }
2144 size_t index;
2145 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002146 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002147 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002148 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002149 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2150
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002151 // TRICKY: we want popped buffers reported in order, so sending
2152 // the callback while holding the lock here. This assumes that
2153 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2154 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002155 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002156 } else {
2157 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002158 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002159 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002160 return false;
2161 }
2162 }
2163
Wonsik Kimec585c32021-10-01 01:11:00 -07002164 bool drop = false;
2165 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2166 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2167 drop = true;
2168 }
2169
Marc Kassisec910342022-11-25 11:43:05 +01002170 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2171 // HAL, the flag is then removed in the corresponding output buffer.
2172 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2173 flags |= BUFFER_FLAG_DECODE_ONLY;
2174 }
2175
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002176 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002177 if (mTunneled && drop && outputFormat) {
Houxiang Daie74e5062022-05-19 15:32:54 +08002178 if (mOutputFormat != outputFormat) {
2179 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2180 mName, work->input.ordinal.frameIndex.peekull());
2181 mOutputFormat = outputFormat;
2182 } else {
2183 ALOGV("[%s] onWorkDone: Not reporting output buffer without format change (%lld)",
2184 mName, work->input.ordinal.frameIndex.peekull());
2185 notifyClient = false;
2186 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002187 } else {
2188 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2189 mName, work->input.ordinal.frameIndex.peekull());
2190 notifyClient = false;
2191 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002192 }
2193
2194 if (buffer) {
2195 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2196 // TODO: properly translate these to metadata
2197 switch (info->coreIndex().coreIndex()) {
2198 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002199 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002200 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002201 }
2202 break;
2203 default:
2204 break;
2205 }
2206 }
2207 }
2208
2209 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002210 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002211 if (!output->buffers) {
2212 return false;
2213 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002214 output->buffers->pushToStash(
2215 buffer,
2216 notifyClient,
2217 timestamp.peek(),
2218 flags,
2219 outputFormat,
2220 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002221 }
2222 sendOutputBuffers();
2223 return true;
2224}
2225
2226void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002227 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002228 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002229 sp<MediaCodecBuffer> outBuffer;
2230 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002231
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002232 constexpr int kMaxReallocTry = 5;
2233 int reallocTryNum = 0;
2234
Pawin Vongmasa36653902018-11-15 00:10:25 -08002235 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002236 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002237 if (!output->buffers) {
2238 return;
2239 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002240 action = output->buffers->popFromStashAndRegister(
2241 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002242 if (action != OutputBuffers::REALLOCATE) {
2243 reallocTryNum = 0;
2244 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002245 switch (action) {
2246 case OutputBuffers::SKIP:
2247 return;
2248 case OutputBuffers::DISCARD:
2249 break;
2250 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002251 // TRICKY: we want popped buffers reported in order, so sending
2252 // the callback while holding the lock here. This assumes that
2253 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2254 // callbacks are always sent with the Output lock held.
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002255 mCallback->onOutputBufferAvailable(index, outBuffer);
2256 break;
2257 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002258 if (++reallocTryNum > kMaxReallocTry) {
2259 output.unlock();
2260 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2261 mName, kMaxReallocTry);
2262 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2263 return;
2264 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002265 if (!output->buffers->isArrayMode()) {
2266 output->buffers =
2267 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002268 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002269 static_cast<OutputBuffersArray*>(output->buffers.get())->
2270 realloc(c2Buffer);
2271 output.unlock();
2272 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002273 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002274 case OutputBuffers::RETRY:
2275 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2276 mName);
2277 return;
2278 default:
2279 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2280 "corrupted BufferAction value (%d) "
2281 "returned from popFromStashAndRegister.",
2282 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002283 return;
2284 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002285 }
2286}
2287
Sungtak Lee214ce612023-11-01 10:01:13 +00002288status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface,
2289 uint32_t generation, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002290 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002291 int maxDequeueCount;
2292 sp<Surface> oldSurface;
2293 {
2294 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2295 maxDequeueCount = outputSurface->maxDequeueBuffers;
2296 oldSurface = outputSurface->surface;
2297 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002298 if (newSurface) {
2299 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002300 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002301 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002302 producer = newSurface->getIGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002303 } else {
2304 ALOGE("[%s] setting output surface to null", mName);
2305 return INVALID_OPERATION;
2306 }
2307
2308 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2309 C2BlockPool::local_id_t outputPoolId;
2310 {
2311 Mutexed<BlockPools>::Locked pools(mBlockPools);
2312 outputPoolId = pools->outputPoolId;
2313 outputPoolIntf = pools->outputPoolIntf;
2314 }
2315
2316 if (outputPoolIntf) {
2317 if (mComponent->setOutputSurface(
2318 outputPoolId,
2319 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002320 generation,
2321 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002322 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2323 return INVALID_OPERATION;
2324 }
2325 }
2326
2327 {
2328 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2329 output->surface = newSurface;
2330 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002331 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002332 }
2333
Sungtak Lee99144332023-01-26 11:03:14 +00002334 if (oldSurface && pushBlankBuffer) {
2335 // When ReleaseSurface was set from MediaCodec,
2336 // pushing a blank buffer at the end might be necessary.
2337 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2338 if (anw) {
2339 pushBlankBuffersToNativeWindow(anw.get());
2340 }
2341 }
2342
Pawin Vongmasa36653902018-11-15 00:10:25 -08002343 return OK;
2344}
2345
Wonsik Kimab34ed62019-01-31 15:28:46 -08002346PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002347 // Otherwise, component may have stalled work due to input starvation up to
2348 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002349 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2350 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002351 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002352 size_t outputDelay = mOutput.lock()->outputDelay;
2353 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002354 Mutexed<Input>::Locked input(mInput);
2355 n = input->inputDelay + input->pipelineDelay + outputDelay;
2356 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002357 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002358}
2359
Pawin Vongmasa36653902018-11-15 00:10:25 -08002360void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2361 mMetaMode = mode;
2362}
2363
Wonsik Kim596187e2019-10-25 12:44:10 -07002364void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002365 if (mCrypto != nullptr) {
2366 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2367 mCrypto->unsetHeap(entry.second);
2368 }
2369 mHeapSeqNumMap.clear();
2370 if (mHeapSeqNum >= 0) {
2371 mCrypto->unsetHeap(mHeapSeqNum);
2372 mHeapSeqNum = -1;
2373 }
2374 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002375 mCrypto = crypto;
2376}
2377
2378void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2379 mDescrambler = descrambler;
2380}
2381
Pawin Vongmasa36653902018-11-15 00:10:25 -08002382status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2383 // C2_OK is always translated to OK.
2384 if (c2s == C2_OK) {
2385 return OK;
2386 }
2387
2388 // Operation-dependent translation
2389 // TODO: Add as necessary
2390 switch (c2op) {
2391 case C2_OPERATION_Component_start:
2392 switch (c2s) {
2393 case C2_NO_MEMORY:
2394 return NO_MEMORY;
2395 default:
2396 return UNKNOWN_ERROR;
2397 }
2398 default:
2399 break;
2400 }
2401
2402 // Backup operation-agnostic translation
2403 switch (c2s) {
2404 case C2_BAD_INDEX:
2405 return BAD_INDEX;
2406 case C2_BAD_VALUE:
2407 return BAD_VALUE;
2408 case C2_BLOCKING:
2409 return WOULD_BLOCK;
2410 case C2_DUPLICATE:
2411 return ALREADY_EXISTS;
2412 case C2_NO_INIT:
2413 return NO_INIT;
2414 case C2_NO_MEMORY:
2415 return NO_MEMORY;
2416 case C2_NOT_FOUND:
2417 return NAME_NOT_FOUND;
2418 case C2_TIMED_OUT:
2419 return TIMED_OUT;
2420 case C2_BAD_STATE:
2421 case C2_CANCELED:
2422 case C2_CANNOT_DO:
2423 case C2_CORRUPTED:
2424 case C2_OMITTED:
2425 case C2_REFUSED:
2426 return UNKNOWN_ERROR;
2427 default:
2428 return -static_cast<status_t>(c2s);
2429 }
2430}
2431
Pawin Vongmasa36653902018-11-15 00:10:25 -08002432} // namespace android