blob: bddf3cb931ad599d3c9829260ab326e5fa27b4fd [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 }
1047 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1048 // actually rendered.
1049 TrackedFrame frame;
1050 frame.number = qbo.nextFrameNumber - 1;
1051 frame.mediaTimeUs = mediaTimeUs;
1052 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1053 frame.latchTime = -1;
1054 frame.presentFence = nullptr;
1055 mTrackedFrames.push_back(frame);
1056}
1057
1058void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1059 // Grab the latch times and present fences from the frame event deltas
1060 for (const auto& delta : deltas) {
1061 for (auto& frame : mTrackedFrames) {
1062 if (delta.getFrameNumber() == frame.number) {
1063 delta.getLatchTime(&frame.latchTime);
1064 delta.getDisplayPresentFence(&frame.presentFence);
1065 }
1066 }
1067 }
1068
1069 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1070 // in fact, been rendered.
1071 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1072 while (!mTrackedFrames.empty()) {
1073 TrackedFrame & frame = mTrackedFrames.front();
1074 // Frames that should have been rendered at least 100ms in the past are checked
1075 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1076 break;
1077 }
1078
1079 // If we don't have a render time by now, then consider the frame as dropped
1080 int64_t renderTimeNs = getRenderTimeNs(frame);
1081 if (renderTimeNs != -1) {
1082 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1083 }
1084 mTrackedFrames.pop_front();
1085 }
1086}
1087
1088int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1089 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1090 if (!mHasPresentFenceTimes) {
1091 if (frame.latchTime == -1) {
1092 ALOGD("no latch time for frame %d", (int) frame.number);
1093 return -1;
1094 }
1095 return frame.latchTime;
1096 }
1097
1098 if (frame.presentFence == nullptr) {
1099 ALOGW("no present fence for frame %d", (int) frame.number);
1100 return -1;
1101 }
1102
1103 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1104
1105 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1106 ALOGW("invalid signal time for frame %d", (int) frame.number);
1107 return -1;
1108 }
1109
1110 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1111 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1112 return -1;
1113 }
1114
1115 return actualRenderTimeNs;
1116}
1117
1118void CCodecBufferChannel::pollForRenderedBuffers() {
1119 FrameEventHistoryDelta delta;
1120 mComponent->pollForRenderedFrames(&delta);
1121 processRenderedFrames(delta);
1122}
1123
Pawin Vongmasa36653902018-11-15 00:10:25 -08001124status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1125 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1126 bool released = false;
1127 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001128 Mutexed<Input>::Locked input(mInput);
1129 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001130 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001131 }
1132 }
1133 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001134 Mutexed<Output>::Locked output(mOutput);
1135 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001136 released = true;
1137 }
1138 }
1139 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001140 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001141 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001142 } else {
1143 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1144 }
1145 return OK;
1146}
1147
1148void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1149 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001150 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001151
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001152 if (!input->buffers) {
1153 ALOGE("getInputBufferArray: No Input Buffers allocated");
1154 return;
1155 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001156 if (!input->buffers->isArrayMode()) {
1157 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001158 }
1159
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001160 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001161}
1162
1163void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1164 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001165 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001166 if (!output->buffers) {
1167 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1168 return;
1169 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001170 if (!output->buffers->isArrayMode()) {
1171 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001172 }
1173
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001174 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001175}
1176
1177status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001178 const sp<AMessage> &inputFormat,
1179 const sp<AMessage> &outputFormat,
1180 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001181 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1182 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001183 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001184 C2PortReorderBufferDepthTuning::output reorderDepth;
1185 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001186 C2PortActualDelayTuning::input inputDelay(0);
1187 C2PortActualDelayTuning::output outputDelay(0);
1188 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001189 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001190
Pawin Vongmasa36653902018-11-15 00:10:25 -08001191 c2_status_t err = mComponent->query(
1192 {
1193 &iStreamFormat,
1194 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001195 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001196 &reorderDepth,
1197 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001198 &inputDelay,
1199 &pipelineDelay,
1200 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001201 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001202 },
1203 {},
1204 C2_DONT_BLOCK,
1205 nullptr);
1206 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001207 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001208 return UNKNOWN_ERROR;
1209 }
1210 } else if (err != C2_OK) {
1211 return UNKNOWN_ERROR;
1212 }
1213
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001214 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1215 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1216 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1217
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001218 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1219 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001220
Pawin Vongmasa36653902018-11-15 00:10:25 -08001221 // TODO: get this from input format
1222 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1223
Sungtak Lee04b30352020-07-27 13:57:25 -07001224 // secure mode is a static parameter (shall not change in the executing state)
1225 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1226
Pawin Vongmasa36653902018-11-15 00:10:25 -08001227 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001228 int poolMask = GetCodec2PoolMask();
1229 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001230
1231 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001232 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001233 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001234 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1235 API_REFLECTION |
1236 API_VALUES |
1237 API_CURRENT_VALUES |
1238 API_DEPENDENCY |
1239 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001240 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1241 C2StreamSampleRateInfo::input sampleRate(0u);
1242 C2StreamChannelCountInfo::input channelCount(0u);
1243 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001244 std::shared_ptr<C2BlockPool> pool;
1245 {
1246 Mutexed<BlockPools>::Locked pools(mBlockPools);
1247
1248 // set default allocator ID.
1249 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001250 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001251
1252 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1253 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1254 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001255 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001256 std::vector<C2Param *> stackParams({&featuresSetting});
1257 if (audioEncoder) {
1258 stackParams.push_back(&encoderFrameSize);
1259 stackParams.push_back(&sampleRate);
1260 stackParams.push_back(&channelCount);
1261 stackParams.push_back(&pcmEncoding);
1262 } else {
1263 encoderFrameSize.invalidate();
1264 sampleRate.invalidate();
1265 channelCount.invalidate();
1266 pcmEncoding.invalidate();
1267 }
1268 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001269 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1270 C2_DONT_BLOCK,
1271 &params);
1272 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1273 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1274 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001275 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001276 C2PortAllocatorsTuning::input *inputAllocators =
1277 C2PortAllocatorsTuning::input::From(params[0].get());
1278 if (inputAllocators && inputAllocators->flexCount() > 0) {
1279 std::shared_ptr<C2Allocator> allocator;
1280 // verify allocator IDs and resolve default allocator
1281 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1282 if (allocator) {
1283 pools->inputAllocatorId = allocator->getId();
1284 } else {
1285 ALOGD("[%s] component requested invalid input allocator ID %u",
1286 mName, inputAllocators->m.values[0]);
1287 }
1288 }
1289 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001290 if (featuresSetting) {
1291 apiFeatures = featuresSetting.value;
1292 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001293
1294 // TODO: use C2Component wrapper to associate this pool with ourselves
1295 if ((poolMask >> pools->inputAllocatorId) & 1) {
1296 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1297 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1298 mName, pools->inputAllocatorId,
1299 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1300 asString(err), err);
1301 } else {
1302 err = C2_NOT_FOUND;
1303 }
1304 if (err != C2_OK) {
1305 C2BlockPool::local_id_t inputPoolId =
1306 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1307 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1308 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1309 mName, (unsigned long long)inputPoolId,
1310 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1311 asString(err), err);
1312 if (err != C2_OK) {
1313 return NO_MEMORY;
1314 }
1315 }
1316 pools->inputPool = pool;
1317 }
1318
Wonsik Kim51051262018-11-28 13:59:05 -08001319 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001320 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001321 input->inputDelay = inputDelayValue;
1322 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001323 input->numSlots = numInputSlots;
1324 input->extraBuffers.flush();
1325 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001326 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001327 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1328 input->frameReassembler.init(
1329 pool,
1330 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1331 encoderFrameSize.value,
1332 sampleRate.value,
1333 channelCount.value,
1334 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1335 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001336 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1337 // For encrypted content, framework decrypts source buffer (ashmem) into
1338 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001339 if (!buffersBoundToCodec
1340 && !input->frameReassembler
1341 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001342 input->buffers.reset(new SlotInputBuffers(mName));
1343 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001344 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001345 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001346 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001347 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001348 // This is to ensure buffers do not get released prematurely.
1349 // TODO: handle this without going into array mode
1350 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001351 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001352 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001353 }
1354 } else {
1355 if (hasCryptoOrDescrambler()) {
1356 int32_t capacity = kLinearBufferSize;
1357 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1358 if ((size_t)capacity > kMaxLinearBufferSize) {
1359 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1360 capacity = kMaxLinearBufferSize;
1361 }
1362 if (mDealer == nullptr) {
1363 mDealer = new MemoryDealer(
1364 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001365 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001366 "EncryptedLinearInputBuffers");
1367 mDecryptDestination = mDealer->allocate((size_t)capacity);
1368 }
1369 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001370 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1371 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001372 } else {
1373 mHeapSeqNum = -1;
1374 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001375 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001376 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001377 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001378 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001379 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001380 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001381 }
1382 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001383 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001384
1385 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001386 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001387 } else {
1388 // TODO: error
1389 }
Wonsik Kim51051262018-11-28 13:59:05 -08001390
1391 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001392 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001393 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 }
1395
1396 if (outputFormat != nullptr) {
1397 sp<IGraphicBufferProducer> outputSurface;
1398 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001399 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001400 {
1401 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001402 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001403 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001404 outputSurface = output->surface ?
1405 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001406 if (outputSurface) {
1407 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1408 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001409 outputGeneration = output->generation;
1410 }
1411
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001412 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001413 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001414 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001415
1416 {
1417 Mutexed<BlockPools>::Locked pools(mBlockPools);
1418
David Stevensc3fbb282021-01-18 18:11:20 +09001419 prevOutputPoolId = pools->outputPoolId;
1420
Pawin Vongmasa36653902018-11-15 00:10:25 -08001421 // set default allocator ID.
1422 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001423 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001424
1425 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1426 // unsuccessful.
1427 std::vector<std::unique_ptr<C2Param>> params;
1428 err = mComponent->query({ },
1429 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1430 C2_DONT_BLOCK,
1431 &params);
1432 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1433 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1434 mName, params.size(), asString(err), err);
1435 } else if (err == C2_OK && params.size() == 1) {
1436 C2PortAllocatorsTuning::output *outputAllocators =
1437 C2PortAllocatorsTuning::output::From(params[0].get());
1438 if (outputAllocators && outputAllocators->flexCount() > 0) {
1439 std::shared_ptr<C2Allocator> allocator;
1440 // verify allocator IDs and resolve default allocator
1441 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1442 if (allocator) {
1443 pools->outputAllocatorId = allocator->getId();
1444 } else {
1445 ALOGD("[%s] component requested invalid output allocator ID %u",
1446 mName, outputAllocators->m.values[0]);
1447 }
1448 }
1449 }
1450
1451 // use bufferqueue if outputting to a surface.
1452 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1453 // if unsuccessful.
1454 if (outputSurface) {
1455 params.clear();
1456 err = mComponent->query({ },
1457 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1458 C2_DONT_BLOCK,
1459 &params);
1460 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1461 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1462 mName, params.size(), asString(err), err);
1463 } else if (err == C2_OK && params.size() == 1) {
1464 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1465 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1466 if (surfaceAllocator) {
1467 std::shared_ptr<C2Allocator> allocator;
1468 // verify allocator IDs and resolve default allocator
1469 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1470 if (allocator) {
1471 pools->outputAllocatorId = allocator->getId();
1472 } else {
1473 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1474 mName, surfaceAllocator->value);
1475 err = C2_BAD_VALUE;
1476 }
1477 }
1478 }
1479 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1480 && err != C2_OK
1481 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1482 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1483 }
1484 }
1485
1486 if ((poolMask >> pools->outputAllocatorId) & 1) {
1487 err = mComponent->createBlockPool(
1488 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1489 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1490 mName, pools->outputAllocatorId,
1491 (unsigned long long)pools->outputPoolId,
1492 asString(err));
1493 } else {
1494 err = C2_NOT_FOUND;
1495 }
1496 if (err != C2_OK) {
1497 // use basic pool instead
1498 pools->outputPoolId =
1499 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1500 }
1501
1502 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1503 // component.
1504 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1505 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1506
1507 std::vector<std::unique_ptr<C2SettingResult>> failures;
1508 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1509 ALOGD("[%s] Configured output block pool ids %llu => %s",
1510 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1511 outputPoolId_ = pools->outputPoolId;
1512 }
1513
David Stevensc3fbb282021-01-18 18:11:20 +09001514 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1515 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1516 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1517 if (err != C2_OK) {
1518 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1519 (unsigned long long) prevOutputPoolId, asString(err), err);
1520 }
1521 }
1522
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001523 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001524 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001525 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001526 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001527 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001528 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001529 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001530 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001531 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001532 }
1533 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001534 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001535 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001536 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001537
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001538 output->buffers->clearStash();
1539 if (reorderDepth) {
1540 output->buffers->setReorderDepth(reorderDepth.value);
1541 }
1542 if (reorderKey) {
1543 output->buffers->setReorderKey(reorderKey.value);
1544 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001545
1546 // Try to set output surface to created block pool if given.
1547 if (outputSurface) {
1548 mComponent->setOutputSurface(
1549 outputPoolId_,
1550 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001551 outputGeneration,
1552 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001553 } else {
1554 // configure CPU read consumer usage
1555 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1556 std::vector<std::unique_ptr<C2SettingResult>> failures;
1557 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1558 // do not print error message for now as most components may not yet
1559 // support this setting
1560 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1561 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001562 }
1563
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001564 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001565 if (buffersBoundToCodec) {
1566 // WORKAROUND: if we're using early CSD workaround we convert to
1567 // array mode, to appease apps assuming the output
1568 // buffers to be of the same size.
1569 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1570 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001571
1572 int32_t channelCount;
1573 int32_t sampleRate;
1574 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1575 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1576 int32_t delay = 0;
1577 int32_t padding = 0;;
1578 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1579 delay = 0;
1580 }
1581 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1582 padding = 0;
1583 }
1584 if (delay || padding) {
1585 // We need write access to the buffers, and we're already in
1586 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001587 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001588 }
1589 }
1590 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001591
1592 int32_t tunneled = 0;
1593 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1594 tunneled = 0;
1595 }
1596 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001597 }
1598
1599 // Set up pipeline control. This has to be done after mInputBuffers and
1600 // mOutputBuffers are initialized to make sure that lingering callbacks
1601 // about buffers from the previous generation do not interfere with the
1602 // newly initialized pipeline capacity.
1603
Wonsik Kim62545252021-01-20 11:25:41 -08001604 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001605 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001606 watcher->inputDelay(inputDelayValue)
1607 .pipelineDelay(pipelineDelayValue)
1608 .outputDelay(outputDelayValue)
Houxiang Dai0b573282023-03-11 18:31:56 +08001609 .smoothnessFactor(kSmoothnessFactor)
1610 .tunneled(mTunneled);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001611 watcher->flush();
1612 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001613
1614 mInputMetEos = false;
1615 mSync.start();
1616 return OK;
1617}
1618
Wonsik Kim34b28b42022-05-20 15:49:32 -07001619status_t CCodecBufferChannel::prepareInitialInputBuffers(
1620 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001621 if (mInputSurface) {
1622 return OK;
1623 }
1624
Wonsik Kim34b28b42022-05-20 15:49:32 -07001625 size_t numInputSlots = mInput.lock()->numSlots;
1626
1627 {
1628 Mutexed<Input>::Locked input(mInput);
1629 while (clientInputBuffers->size() < numInputSlots) {
1630 size_t index;
1631 sp<MediaCodecBuffer> buffer;
1632 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1633 break;
1634 }
1635 clientInputBuffers->emplace(index, buffer);
1636 }
1637 }
1638 if (clientInputBuffers->empty()) {
1639 ALOGW("[%s] start: cannot allocate memory at all", mName);
1640 return NO_MEMORY;
1641 } else if (clientInputBuffers->size() < numInputSlots) {
1642 ALOGD("[%s] start: cannot allocate memory for all slots, "
1643 "only %zu buffers allocated",
1644 mName, clientInputBuffers->size());
1645 } else {
1646 ALOGV("[%s] %zu initial input buffers available",
1647 mName, clientInputBuffers->size());
1648 }
1649 return OK;
1650}
1651
1652status_t CCodecBufferChannel::requestInitialInputBuffers(
1653 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001654 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001655 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1656 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1657 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001658 return UNKNOWN_ERROR;
1659 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001660
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001661 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1662 mFlushedConfigs.lock()->swap(flushedConfigs);
1663 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001664 {
1665 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1666 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1667 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1668 watcher->onWorkQueued(
1669 work->input.ordinal.frameIndex.peeku(),
1670 std::vector(work->input.buffers),
1671 now);
1672 }
1673 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001674 err = mComponent->queue(&flushedConfigs);
1675 if (err != C2_OK) {
1676 ALOGW("[%s] Error while queueing a flushed config", mName);
1677 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001678 }
1679 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001680 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001681 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1682 !clientInputBuffers.empty()) {
1683 size_t minIndex = clientInputBuffers.begin()->first;
1684 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1685 for (const auto &[index, buffer] : clientInputBuffers) {
1686 if (minBuffer->capacity() > buffer->capacity()) {
1687 minIndex = index;
1688 minBuffer = buffer;
1689 }
1690 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001691 // WORKAROUND: Some apps expect CSD available without queueing
1692 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001693 minBuffer->setRange(0, 0);
1694 minBuffer->meta()->clear();
1695 minBuffer->meta()->setInt64("timeUs", 0);
1696 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001697 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1698 mName);
1699 return UNKNOWN_ERROR;
1700 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001701 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001702 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001703
Wonsik Kim34b28b42022-05-20 15:49:32 -07001704 for (const auto &[index, buffer] : clientInputBuffers) {
1705 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001706 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001707
Pawin Vongmasa36653902018-11-15 00:10:25 -08001708 return OK;
1709}
1710
1711void CCodecBufferChannel::stop() {
1712 mSync.stop();
1713 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001714}
1715
Sungtak Lee99144332023-01-26 11:03:14 +00001716void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
1717 sp<Surface> surface = mOutputSurface.lock()->surface;
1718 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00001719 C2BlockPool::local_id_t outputPoolId;
1720 {
1721 Mutexed<BlockPools>::Locked pools(mBlockPools);
1722 outputPoolId = pools->outputPoolId;
1723 }
1724 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00001725
1726 if (pushBlankBuffer) {
1727 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
1728 if (anw) {
1729 pushBlankBuffersToNativeWindow(anw.get());
1730 }
1731 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00001732 }
1733}
1734
Wonsik Kim936a89c2020-05-08 16:07:50 -07001735void CCodecBufferChannel::reset() {
1736 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001737 if (mInputSurface != nullptr) {
1738 mInputSurface.reset();
1739 }
1740 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001741 {
1742 Mutexed<Input>::Locked input(mInput);
1743 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001744 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001745 }
1746 {
1747 Mutexed<Output>::Locked output(mOutput);
1748 output->buffers.reset();
1749 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001750 // reset the frames that are being tracked for onFrameRendered callbacks
1751 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001752}
1753
1754void CCodecBufferChannel::release() {
1755 mComponent.reset();
1756 mInputAllocator.reset();
1757 mOutputSurface.lock()->surface.clear();
1758 {
1759 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1760 blockPools->inputPool.reset();
1761 blockPools->outputPoolIntf.reset();
1762 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001763 setCrypto(nullptr);
1764 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001765}
1766
Pawin Vongmasa36653902018-11-15 00:10:25 -08001767void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1768 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001769 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001770 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001771 {
1772 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1773 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1774 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1775 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1776 watcher->onWorkDone(frameIndex);
1777 continue;
1778 }
1779 if (work->input.buffers.empty()
1780 || work->input.buffers.front() == nullptr
1781 || work->input.buffers.front()->data().linearBlocks().empty()) {
1782 ALOGD("[%s] no linear codec config data found", mName);
1783 watcher->onWorkDone(frameIndex);
1784 continue;
1785 }
1786 std::unique_ptr<C2Work> copy(new C2Work);
1787 copy->input.flags = C2FrameData::flags_t(
1788 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1789 copy->input.ordinal = work->input.ordinal;
1790 copy->input.ordinal.frameIndex = mFrameIndex++;
1791 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1792 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1793 }
1794 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1795 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1796 }
1797 copy->input.infoBuffers.insert(
1798 copy->input.infoBuffers.begin(),
1799 work->input.infoBuffers.begin(),
1800 work->input.infoBuffers.end());
1801 copy->worklets.emplace_back(new C2Worklet);
1802 configs.push_back(std::move(copy));
1803 watcher->onWorkDone(frameIndex);
1804 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001805 }
1806 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001807 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001808 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001809 Mutexed<Input>::Locked input(mInput);
1810 input->buffers->flush();
1811 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001812 }
1813 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001814 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001815 if (output->buffers) {
1816 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001817 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001818 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001819 }
1820}
1821
1822void CCodecBufferChannel::onWorkDone(
1823 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001824 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001825 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001826 feedInputBufferIfAvailable();
1827 }
1828}
1829
1830void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001831 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001832 if (mInputSurface) {
1833 return;
1834 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001835 std::shared_ptr<C2Buffer> buffer =
1836 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001837 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001838 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001839 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001840 if (input->lastFlushIndex >= frameIndex) {
1841 ALOGD("[%s] Ignoring stale input buffer done callback: "
1842 "last flush index = %lld, frameIndex = %lld",
1843 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1844 } else {
1845 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1846 if (!newInputSlotAvailable) {
1847 (void)input->extraBuffers.expireComponentBuffer(buffer);
1848 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001849 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001850 }
1851 if (newInputSlotAvailable) {
1852 feedInputBufferIfAvailable();
1853 }
1854}
1855
1856bool CCodecBufferChannel::handleWork(
1857 std::unique_ptr<C2Work> work,
1858 const sp<AMessage> &outputFormat,
1859 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001860 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001861 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001862 if (!output->buffers) {
1863 return false;
1864 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001865 }
1866
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001867 // Whether the output buffer should be reported to the client or not.
1868 bool notifyClient = false;
1869
1870 if (work->result == C2_OK){
1871 notifyClient = true;
1872 } else if (work->result == C2_NOT_FOUND) {
1873 ALOGD("[%s] flushed work; ignored.", mName);
1874 } else {
1875 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1876 // the config update.
1877 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1878 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1879 return false;
1880 }
1881
1882 if ((work->input.ordinal.frameIndex -
1883 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001884 // Discard frames from previous generation.
1885 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001886 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001887 }
1888
Wonsik Kim524b0582019-03-12 11:28:57 -07001889 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001890 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001891 || !(work->worklets.front()->output.flags &
1892 C2FrameData::FLAG_INCOMPLETE))) {
1893 mPipelineWatcher.lock()->onWorkDone(
1894 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001895 }
1896
1897 // NOTE: MediaCodec usage supposedly have only one worklet
1898 if (work->worklets.size() != 1u) {
1899 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1900 mName, work->worklets.size());
1901 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1902 return false;
1903 }
1904
1905 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1906
1907 std::shared_ptr<C2Buffer> buffer;
1908 // NOTE: MediaCodec usage supposedly have only one output stream.
1909 if (worklet->output.buffers.size() > 1u) {
1910 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1911 mName, worklet->output.buffers.size());
1912 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1913 return false;
1914 } else if (worklet->output.buffers.size() == 1u) {
1915 buffer = worklet->output.buffers[0];
1916 if (!buffer) {
1917 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1918 }
1919 }
1920
Wonsik Kim3dedf682021-05-03 10:57:09 -07001921 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1922 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001923 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001924 while (!worklet->output.configUpdate.empty()) {
1925 std::unique_ptr<C2Param> param;
1926 worklet->output.configUpdate.back().swap(param);
1927 worklet->output.configUpdate.pop_back();
1928 switch (param->coreIndex().coreIndex()) {
1929 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1930 C2PortReorderBufferDepthTuning::output reorderDepth;
1931 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001932 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1933 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001934 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001935 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001936 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001937 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1938 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001939 }
1940 break;
1941 }
1942 case C2PortReorderKeySetting::CORE_INDEX: {
1943 C2PortReorderKeySetting::output reorderKey;
1944 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001945 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001946 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1947 mName, reorderKey.value);
1948 } else {
1949 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1950 }
1951 break;
1952 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001953 case C2PortActualDelayTuning::CORE_INDEX: {
1954 if (param->isGlobal()) {
1955 C2ActualPipelineDelayTuning pipelineDelay;
1956 if (pipelineDelay.updateFrom(*param)) {
1957 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1958 mName, pipelineDelay.value);
1959 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001960 (void)mPipelineWatcher.lock()->pipelineDelay(
1961 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001962 }
1963 }
1964 if (param->forInput()) {
1965 C2PortActualDelayTuning::input inputDelay;
1966 if (inputDelay.updateFrom(*param)) {
1967 ALOGV("[%s] onWorkDone: updating input delay %u",
1968 mName, inputDelay.value);
1969 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001970 (void)mPipelineWatcher.lock()->inputDelay(
1971 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001972 }
1973 }
1974 if (param->forOutput()) {
1975 C2PortActualDelayTuning::output outputDelay;
1976 if (outputDelay.updateFrom(*param)) {
1977 ALOGV("[%s] onWorkDone: updating output delay %u",
1978 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001979 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001980 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001981 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001982
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001983 }
1984 }
1985 break;
1986 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001987 case C2PortTunnelSystemTime::CORE_INDEX: {
1988 C2PortTunnelSystemTime::output frameRenderTime;
1989 if (frameRenderTime.updateFrom(*param)) {
1990 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1991 mName, (long long)frameRenderTime.value,
1992 (long long)worklet->output.ordinal.timestamp.peekll());
1993 mCCodecCallback->onOutputFramesRendered(
1994 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1995 }
1996 break;
1997 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001998 case C2StreamTunnelHoldRender::CORE_INDEX: {
1999 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
2000 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
2001 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
2002 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
2003 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
2004 mCCodecCallback->onFirstTunnelFrameReady();
2005 break;
2006 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002007 default:
2008 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2009 mName, param->index());
2010 break;
2011 }
2012 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002013 if (newInputDelay || newPipelineDelay) {
2014 Mutexed<Input>::Locked input(mInput);
2015 size_t newNumSlots =
2016 newInputDelay.value_or(input->inputDelay) +
2017 newPipelineDelay.value_or(input->pipelineDelay) +
2018 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08002019 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002020 if (input->buffers->isArrayMode()) {
2021 if (input->numSlots >= newNumSlots) {
2022 input->numExtraSlots = 0;
2023 } else {
2024 input->numExtraSlots = newNumSlots - input->numSlots;
2025 }
2026 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2027 mName, input->numExtraSlots);
2028 } else {
2029 input->numSlots = newNumSlots;
2030 }
2031 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002032 size_t numOutputSlots = 0;
2033 uint32_t reorderDepth = 0;
2034 bool outputBuffersChanged = false;
2035 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2036 Mutexed<Output>::Locked output(mOutput);
2037 if (!output->buffers) {
2038 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002039 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002040 numOutputSlots = output->numSlots;
2041 if (newReorderKey) {
2042 output->buffers->setReorderKey(newReorderKey.value());
2043 }
2044 if (newReorderDepth) {
2045 output->buffers->setReorderDepth(newReorderDepth.value());
2046 }
2047 reorderDepth = output->buffers->getReorderDepth();
2048 if (newOutputDelay) {
2049 output->outputDelay = newOutputDelay.value();
2050 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2051 if (output->numSlots < numOutputSlots) {
2052 output->numSlots = numOutputSlots;
2053 if (output->buffers->isArrayMode()) {
2054 OutputBuffersArray *array =
2055 (OutputBuffersArray *)output->buffers.get();
2056 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2057 mName, numOutputSlots);
2058 array->grow(numOutputSlots);
2059 outputBuffersChanged = true;
2060 }
2061 }
2062 }
2063 numOutputSlots = output->numSlots;
2064 }
2065 if (outputBuffersChanged) {
2066 mCCodecCallback->onOutputBuffersChanged();
2067 }
2068 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002069 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002070 {
2071 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2072 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002073 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002074 if (output->surface) {
2075 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2076 }
2077 }
2078 if (maxDequeueCount > 0) {
2079 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002080 }
2081 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002082
Pawin Vongmasa36653902018-11-15 00:10:25 -08002083 int32_t flags = 0;
2084 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002085 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002086 ALOGV("[%s] onWorkDone: output EOS", mName);
2087 }
2088
Pawin Vongmasa36653902018-11-15 00:10:25 -08002089 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2090 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2091 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2092 // shall correspond to the client input timesamp (in customOrdinal). By using the
2093 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2094 // produces multiple output.
2095 c2_cntr64_t timestamp =
2096 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2097 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002098 if (mInputSurface != nullptr) {
2099 // When using input surface we need to restore the original input timestamp.
2100 timestamp = work->input.ordinal.customOrdinal;
2101 }
My Name6bd9a7d2022-03-25 12:37:58 -07002102 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2103 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002104 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2105 mName,
2106 work->input.ordinal.customOrdinal.peekll(),
2107 work->input.ordinal.timestamp.peekll(),
2108 worklet->output.ordinal.timestamp.peekll(),
2109 timestamp.peekll());
2110
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002111 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002112 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002113 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002114 if (!output->buffers) {
2115 return false;
2116 }
2117 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002118 output->buffers->updateSkipCutBuffer(outputFormat);
2119 output->buffers->setFormat(outputFormat);
2120 }
2121 if (!notifyClient) {
2122 return false;
2123 }
2124 size_t index;
2125 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002126 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002127 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002128 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002129 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2130
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002131 // TRICKY: we want popped buffers reported in order, so sending
2132 // the callback while holding the lock here. This assumes that
2133 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2134 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002135 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002136 } else {
2137 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002138 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002139 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002140 return false;
2141 }
2142 }
2143
Wonsik Kimec585c32021-10-01 01:11:00 -07002144 bool drop = false;
2145 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2146 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2147 drop = true;
2148 }
2149
Marc Kassisec910342022-11-25 11:43:05 +01002150 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2151 // HAL, the flag is then removed in the corresponding output buffer.
2152 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2153 flags |= BUFFER_FLAG_DECODE_ONLY;
2154 }
2155
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002156 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002157 if (mTunneled && drop && outputFormat) {
Houxiang Daie74e5062022-05-19 15:32:54 +08002158 if (mOutputFormat != outputFormat) {
2159 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2160 mName, work->input.ordinal.frameIndex.peekull());
2161 mOutputFormat = outputFormat;
2162 } else {
2163 ALOGV("[%s] onWorkDone: Not reporting output buffer without format change (%lld)",
2164 mName, work->input.ordinal.frameIndex.peekull());
2165 notifyClient = false;
2166 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002167 } else {
2168 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2169 mName, work->input.ordinal.frameIndex.peekull());
2170 notifyClient = false;
2171 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002172 }
2173
2174 if (buffer) {
2175 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2176 // TODO: properly translate these to metadata
2177 switch (info->coreIndex().coreIndex()) {
2178 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002179 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002180 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002181 }
2182 break;
2183 default:
2184 break;
2185 }
2186 }
2187 }
2188
2189 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002190 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002191 if (!output->buffers) {
2192 return false;
2193 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002194 output->buffers->pushToStash(
2195 buffer,
2196 notifyClient,
2197 timestamp.peek(),
2198 flags,
2199 outputFormat,
2200 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002201 }
2202 sendOutputBuffers();
2203 return true;
2204}
2205
2206void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002207 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002208 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002209 sp<MediaCodecBuffer> outBuffer;
2210 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002211
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002212 constexpr int kMaxReallocTry = 5;
2213 int reallocTryNum = 0;
2214
Pawin Vongmasa36653902018-11-15 00:10:25 -08002215 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002216 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002217 if (!output->buffers) {
2218 return;
2219 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002220 action = output->buffers->popFromStashAndRegister(
2221 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002222 if (action != OutputBuffers::REALLOCATE) {
2223 reallocTryNum = 0;
2224 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002225 switch (action) {
2226 case OutputBuffers::SKIP:
2227 return;
2228 case OutputBuffers::DISCARD:
2229 break;
2230 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002231 // TRICKY: we want popped buffers reported in order, so sending
2232 // the callback while holding the lock here. This assumes that
2233 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2234 // callbacks are always sent with the Output lock held.
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002235 mCallback->onOutputBufferAvailable(index, outBuffer);
2236 break;
2237 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002238 if (++reallocTryNum > kMaxReallocTry) {
2239 output.unlock();
2240 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2241 mName, kMaxReallocTry);
2242 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2243 return;
2244 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002245 if (!output->buffers->isArrayMode()) {
2246 output->buffers =
2247 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002248 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002249 static_cast<OutputBuffersArray*>(output->buffers.get())->
2250 realloc(c2Buffer);
2251 output.unlock();
2252 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002253 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002254 case OutputBuffers::RETRY:
2255 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2256 mName);
2257 return;
2258 default:
2259 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2260 "corrupted BufferAction value (%d) "
2261 "returned from popFromStashAndRegister.",
2262 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002263 return;
2264 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002265 }
2266}
2267
Sungtak Lee99144332023-01-26 11:03:14 +00002268status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002269 static std::atomic_uint32_t surfaceGeneration{0};
2270 uint32_t generation = (getpid() << 10) |
2271 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2272 & ((1 << 10) - 1));
2273
2274 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002275 int maxDequeueCount;
2276 sp<Surface> oldSurface;
2277 {
2278 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2279 maxDequeueCount = outputSurface->maxDequeueBuffers;
2280 oldSurface = outputSurface->surface;
2281 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002282 if (newSurface) {
2283 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002284 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002285 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002286 producer = newSurface->getIGraphicBufferProducer();
2287 producer->setGenerationNumber(generation);
2288 } else {
2289 ALOGE("[%s] setting output surface to null", mName);
2290 return INVALID_OPERATION;
2291 }
2292
2293 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2294 C2BlockPool::local_id_t outputPoolId;
2295 {
2296 Mutexed<BlockPools>::Locked pools(mBlockPools);
2297 outputPoolId = pools->outputPoolId;
2298 outputPoolIntf = pools->outputPoolIntf;
2299 }
2300
2301 if (outputPoolIntf) {
2302 if (mComponent->setOutputSurface(
2303 outputPoolId,
2304 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002305 generation,
2306 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002307 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2308 return INVALID_OPERATION;
2309 }
2310 }
2311
2312 {
2313 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2314 output->surface = newSurface;
2315 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002316 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002317 }
2318
Sungtak Lee99144332023-01-26 11:03:14 +00002319 if (oldSurface && pushBlankBuffer) {
2320 // When ReleaseSurface was set from MediaCodec,
2321 // pushing a blank buffer at the end might be necessary.
2322 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2323 if (anw) {
2324 pushBlankBuffersToNativeWindow(anw.get());
2325 }
2326 }
2327
Pawin Vongmasa36653902018-11-15 00:10:25 -08002328 return OK;
2329}
2330
Wonsik Kimab34ed62019-01-31 15:28:46 -08002331PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002332 // Otherwise, component may have stalled work due to input starvation up to
2333 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002334 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2335 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002336 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002337 size_t outputDelay = mOutput.lock()->outputDelay;
2338 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002339 Mutexed<Input>::Locked input(mInput);
2340 n = input->inputDelay + input->pipelineDelay + outputDelay;
2341 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002342 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002343}
2344
Pawin Vongmasa36653902018-11-15 00:10:25 -08002345void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2346 mMetaMode = mode;
2347}
2348
Wonsik Kim596187e2019-10-25 12:44:10 -07002349void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002350 if (mCrypto != nullptr) {
2351 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2352 mCrypto->unsetHeap(entry.second);
2353 }
2354 mHeapSeqNumMap.clear();
2355 if (mHeapSeqNum >= 0) {
2356 mCrypto->unsetHeap(mHeapSeqNum);
2357 mHeapSeqNum = -1;
2358 }
2359 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002360 mCrypto = crypto;
2361}
2362
2363void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2364 mDescrambler = descrambler;
2365}
2366
Pawin Vongmasa36653902018-11-15 00:10:25 -08002367status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2368 // C2_OK is always translated to OK.
2369 if (c2s == C2_OK) {
2370 return OK;
2371 }
2372
2373 // Operation-dependent translation
2374 // TODO: Add as necessary
2375 switch (c2op) {
2376 case C2_OPERATION_Component_start:
2377 switch (c2s) {
2378 case C2_NO_MEMORY:
2379 return NO_MEMORY;
2380 default:
2381 return UNKNOWN_ERROR;
2382 }
2383 default:
2384 break;
2385 }
2386
2387 // Backup operation-agnostic translation
2388 switch (c2s) {
2389 case C2_BAD_INDEX:
2390 return BAD_INDEX;
2391 case C2_BAD_VALUE:
2392 return BAD_VALUE;
2393 case C2_BLOCKING:
2394 return WOULD_BLOCK;
2395 case C2_DUPLICATE:
2396 return ALREADY_EXISTS;
2397 case C2_NO_INIT:
2398 return NO_INIT;
2399 case C2_NO_MEMORY:
2400 return NO_MEMORY;
2401 case C2_NOT_FOUND:
2402 return NAME_NOT_FOUND;
2403 case C2_TIMED_OUT:
2404 return TIMED_OUT;
2405 case C2_BAD_STATE:
2406 case C2_CANCELED:
2407 case C2_CANNOT_DO:
2408 case C2_CORRUPTED:
2409 case C2_OMITTED:
2410 case C2_REFUSED:
2411 return UNKNOWN_ERROR;
2412 default:
2413 return -static_cast<status_t>(c2s);
2414 }
2415}
2416
Pawin Vongmasa36653902018-11-15 00:10:25 -08002417} // namespace android