blob: 6e6d3f7b44783032382b24fc53a0d1b0cc5edc53 [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>
Arun Johnson326166e2023-07-28 19:11:52 +000028#include <thread>
29#include <chrono>
Pawin Vongmasa36653902018-11-15 00:10:25 -080030
31#include <C2AllocatorGralloc.h>
32#include <C2PlatformSupport.h>
33#include <C2BlockInternal.h>
34#include <C2Config.h>
35#include <C2Debug.h>
36
37#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070038#include <android/hardware/drm/1.0/types.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070039#include <android-base/parseint.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080040#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080041#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080042#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080043#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070044#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080045#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070046#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080047#include <media/openmax/OMX_Core.h>
48#include <media/stagefright/foundation/ABuffer.h>
49#include <media/stagefright/foundation/ALookup.h>
50#include <media/stagefright/foundation/AMessage.h>
51#include <media/stagefright/foundation/AUtils.h>
52#include <media/stagefright/foundation/hexdump.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080053#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070054#include <media/stagefright/SkipCutBuffer.h>
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010055#include <media/stagefright/SurfaceUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080056#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070057#include <mediadrm/ICrypto.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070058#include <server_configurable_flags/get_flags.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080059#include <system/window.h>
60
61#include "CCodecBufferChannel.h"
62#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080063
64namespace android {
65
66using android::base::StringPrintf;
67using hardware::hidl_handle;
68using hardware::hidl_string;
69using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070070using hardware::fromHeap;
71using hardware::HidlMemory;
Brian Lindahld7967a92023-08-10 10:12:49 -060072using server_configurable_flags::GetServerConfigurableFlag;
Robert Shih895fba92019-07-16 16:29:44 -070073
Pawin Vongmasa36653902018-11-15 00:10:25 -080074using namespace hardware::cas::V1_0;
75using namespace hardware::cas::native::V1_0;
76
77using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070078using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080079
Pawin Vongmasa36653902018-11-15 00:10:25 -080080namespace {
81
Wonsik Kim469c8342019-04-11 16:46:09 -070082constexpr size_t kSmoothnessFactor = 4;
Pawin Vongmasa36653902018-11-15 00:10:25 -080083
Sungtak Leeab6f2f32019-02-15 14:43:51 -080084// This is for keeping IGBP's buffer dropping logic in legacy mode other
85// than making it non-blocking. Do not change this value.
86const static size_t kDequeueTimeoutNs = 0;
87
Brian Lindahld7967a92023-08-10 10:12:49 -060088static bool areRenderMetricsEnabled() {
89 std::string v = GetServerConfigurableFlag("media_native", "render_metrics_enabled", "false");
90 return v == "true";
91}
92
Pawin Vongmasa36653902018-11-15 00:10:25 -080093} // namespace
94
95CCodecBufferChannel::QueueGuard::QueueGuard(
96 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
97 Mutex::Autolock l(mSync.mGuardLock);
98 // At this point it's guaranteed that mSync is not under state transition,
99 // as we are holding its mutex.
100
101 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
102 if (count->value == -1) {
103 mRunning = false;
104 } else {
105 ++count->value;
106 mRunning = true;
107 }
108}
109
110CCodecBufferChannel::QueueGuard::~QueueGuard() {
111 if (mRunning) {
112 // We are not holding mGuardLock at this point so that QueueSync::stop() can
113 // keep holding the lock until mCount reaches zero.
114 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
115 --count->value;
116 count->cond.broadcast();
117 }
118}
119
120void CCodecBufferChannel::QueueSync::start() {
121 Mutex::Autolock l(mGuardLock);
122 // If stopped, it goes to running state; otherwise no-op.
123 Mutexed<Counter>::Locked count(mCount);
124 if (count->value == -1) {
125 count->value = 0;
126 }
127}
128
129void CCodecBufferChannel::QueueSync::stop() {
130 Mutex::Autolock l(mGuardLock);
131 Mutexed<Counter>::Locked count(mCount);
132 if (count->value == -1) {
133 // no-op
134 return;
135 }
136 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
137 // mCount can only decrement. In other words, threads that acquired the lock
138 // are allowed to finish execution but additional threads trying to acquire
139 // the lock at this point will block, and then get QueueGuard at STOPPED
140 // state.
141 while (count->value != 0) {
142 count.waitForCondition(count->cond);
143 }
144 count->value = -1;
145}
146
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700147// Input
148
149CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
150
Pawin Vongmasa36653902018-11-15 00:10:25 -0800151// CCodecBufferChannel
152
153CCodecBufferChannel::CCodecBufferChannel(
154 const std::shared_ptr<CCodecCallback> &callback)
155 : mHeapSeqNum(-1),
156 mCCodecCallback(callback),
157 mFrameIndex(0u),
158 mFirstValidFrameIndex(0u),
Brian Lindahld7967a92023-08-10 10:12:49 -0600159 mAreRenderMetricsEnabled(areRenderMetricsEnabled()),
Brian Lindahl2048d492023-04-05 08:49:23 -0600160 mIsSurfaceToDisplay(false),
161 mHasPresentFenceTimes(false),
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700162 mRenderingDepth(3u),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800163 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700164 mInputMetEos(false),
165 mSendEncryptedInfoBuffer(false) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700166 {
167 Mutexed<Input>::Locked input(mInput);
168 input->buffers.reset(new DummyInputBuffers(""));
169 input->extraBuffers.flush();
170 input->inputDelay = 0u;
171 input->pipelineDelay = 0u;
172 input->numSlots = kSmoothnessFactor;
173 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700174 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700175 }
176 {
177 Mutexed<Output>::Locked output(mOutput);
178 output->outputDelay = 0u;
179 output->numSlots = kSmoothnessFactor;
Wonsik Kim3722abc2023-05-17 13:26:31 -0700180 output->bounded = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700181 }
David Stevensc3fbb282021-01-18 18:11:20 +0900182 {
183 Mutexed<BlockPools>::Locked pools(mBlockPools);
184 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
185 }
Brian Lindahld7967a92023-08-10 10:12:49 -0600186 std::string value = GetServerConfigurableFlag("media_native", "ccodec_rendering_depth", "3");
Wonsik Kim3a692e62023-05-19 15:37:22 -0700187 android::base::ParseInt(value, &mRenderingDepth);
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700188 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800189}
190
191CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800192 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800193 mCrypto->unsetHeap(mHeapSeqNum);
194 }
195}
196
197void CCodecBufferChannel::setComponent(
198 const std::shared_ptr<Codec2Client::Component> &component) {
199 mComponent = component;
200 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
201 mName = mComponentName.c_str();
202}
203
204status_t CCodecBufferChannel::setInputSurface(
205 const std::shared_ptr<InputSurfaceWrapper> &surface) {
206 ALOGV("[%s] setInputSurface", mName);
207 mInputSurface = surface;
208 return mInputSurface->connect(mComponent);
209}
210
211status_t CCodecBufferChannel::signalEndOfInputStream() {
212 if (mInputSurface == nullptr) {
213 return INVALID_OPERATION;
214 }
215 return mInputSurface->signalEndOfInputStream();
216}
217
Sungtak Lee04b30352020-07-27 13:57:25 -0700218status_t CCodecBufferChannel::queueInputBufferInternal(
219 sp<MediaCodecBuffer> buffer,
220 std::shared_ptr<C2LinearBlock> encryptedBlock,
221 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800222 int64_t timeUs;
223 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
224
225 if (mInputMetEos) {
226 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
227 return OK;
228 }
229
230 int32_t flags = 0;
231 int32_t tmp = 0;
232 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200233 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800234 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
235 eos = true;
236 mInputMetEos = true;
237 ALOGV("[%s] input EOS", mName);
238 }
239 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
240 flags |= C2FrameData::FLAG_CODEC_CONFIG;
241 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200242 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
243 tunnelFirstFrame = true;
244 }
Marc Kassis96343b42022-12-09 11:49:44 +0100245 if (buffer->meta()->findInt32("decode-only", &tmp) && tmp) {
246 flags |= C2FrameData::FLAG_DROP_FRAME;
247 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800248 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800249 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800250 std::unique_ptr<C2Work> work(new C2Work);
251 work->input.ordinal.timestamp = timeUs;
252 work->input.ordinal.frameIndex = mFrameIndex++;
253 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
254 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
255 // Keep client timestamp in customOrdinal
256 work->input.ordinal.customOrdinal = timeUs;
257 work->input.buffers.clear();
258
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700259 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800260 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800261
Pawin Vongmasa36653902018-11-15 00:10:25 -0800262 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700263 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800264 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700265 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800266 return -ENOENT;
267 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700268 // TODO: we want to delay copying buffers.
269 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
270 copy = input->buffers->cloneAndReleaseBuffer(buffer);
271 if (copy != nullptr) {
272 (void)input->extraBuffers.assignSlot(copy);
273 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
274 return UNKNOWN_ERROR;
275 }
276 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
277 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
278 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700279 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700280 } else {
281 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
282 "buffer starvation on component.", mName);
283 }
284 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800285 if (input->frameReassembler) {
286 usesFrameReassembler = true;
287 input->frameReassembler.process(buffer, &items);
288 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900289 int32_t cvo = 0;
290 if (buffer->meta()->findInt32("cvo", &cvo)) {
291 int32_t rotation = cvo % 360;
292 // change rotation to counter-clock wise.
293 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
294
295 Mutexed<OutputSurface>::Locked output(mOutputSurface);
296 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
297 output->rotation[frameIndex] = rotation;
298 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800299 work->input.buffers.push_back(c2buffer);
300 if (encryptedBlock) {
301 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
302 kParamIndexEncryptedBuffer,
303 encryptedBlock->share(0, blockSize, C2Fence())));
304 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700305 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800306 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700307 Mutexed<Input>::Locked input(mInput);
308 if (input->frameReassembler) {
309 usesFrameReassembler = true;
310 // drain any pending items with eos
311 input->frameReassembler.process(buffer, &items);
312 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800313 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800314 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800315 if (usesFrameReassembler) {
316 if (!items.empty()) {
317 items.front()->input.configUpdate = std::move(mParamsToBeSet);
318 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
319 }
320 } else {
321 work->input.flags = (C2FrameData::flags_t)flags;
322 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800323
Wonsik Kime1104ca2020-11-24 15:01:33 -0800324 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200325 if (tunnelFirstFrame) {
326 C2StreamTunnelHoldRender::input tunnelHoldRender{
327 0u /* stream */,
328 C2_TRUE /* value */
329 };
330 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
331 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800332 work->worklets.clear();
333 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800334
Wonsik Kime1104ca2020-11-24 15:01:33 -0800335 items.push_back(std::move(work));
336
337 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800338 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800339 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800340 work.reset(new C2Work);
341 work->input.ordinal.timestamp = timeUs;
342 work->input.ordinal.frameIndex = mFrameIndex++;
343 // WORKAROUND: keep client timestamp in customOrdinal
344 work->input.ordinal.customOrdinal = timeUs;
345 work->input.buffers.clear();
346 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800347 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800348 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800349 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800350 c2_status_t err = C2_OK;
351 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700352 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
353 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800354 {
355 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
356 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
357 for (const std::unique_ptr<C2Work> &work : items) {
358 watcher->onWorkQueued(
359 work->input.ordinal.frameIndex.peeku(),
360 std::vector(work->input.buffers),
361 now);
362 }
363 }
364 err = mComponent->queue(&items);
365 }
366 if (err != C2_OK) {
367 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
368 for (const std::unique_ptr<C2Work> &work : items) {
369 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
370 }
371 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700372 Mutexed<Input>::Locked input(mInput);
373 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700374 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700375 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700376 } else if (buffer) {
377 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700378 }
379 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
380 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800381 }
382
383 feedInputBufferIfAvailableInternal();
384 return err;
385}
386
387status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
388 QueueGuard guard(mSync);
389 if (!guard.isRunning()) {
390 ALOGD("[%s] setParameters is only supported in the running state.", mName);
391 return -ENOSYS;
392 }
393 mParamsToBeSet.insert(mParamsToBeSet.end(),
394 std::make_move_iterator(params.begin()),
395 std::make_move_iterator(params.end()));
396 params.clear();
397 return OK;
398}
399
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800400status_t CCodecBufferChannel::attachBuffer(
401 const std::shared_ptr<C2Buffer> &c2Buffer,
402 const sp<MediaCodecBuffer> &buffer) {
403 if (!buffer->copy(c2Buffer)) {
404 return -ENOSYS;
405 }
406 return OK;
407}
408
409void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
410 if (!mDecryptDestination || mDecryptDestination->size() < size) {
411 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
412 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
413 mCrypto->unsetHeap(mHeapSeqNum);
414 }
415 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
416 if (mCrypto) {
417 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
418 }
419 }
420}
421
422int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
423 CHECK(mCrypto);
424 auto it = mHeapSeqNumMap.find(memory);
425 int32_t heapSeqNum = -1;
426 if (it == mHeapSeqNumMap.end()) {
427 heapSeqNum = mCrypto->setHeap(memory);
428 mHeapSeqNumMap.emplace(memory, heapSeqNum);
429 } else {
430 heapSeqNum = it->second;
431 }
432 return heapSeqNum;
433}
434
435status_t CCodecBufferChannel::attachEncryptedBuffer(
436 const sp<hardware::HidlMemory> &memory,
437 bool secure,
438 const uint8_t *key,
439 const uint8_t *iv,
440 CryptoPlugin::Mode mode,
441 CryptoPlugin::Pattern pattern,
442 size_t offset,
443 const CryptoPlugin::SubSample *subSamples,
444 size_t numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000445 const sp<MediaCodecBuffer> &buffer,
446 AString* errorDetailMsg) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800447 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
448 static const C2MemoryUsage kDefaultReadWriteUsage{
449 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
450
451 size_t size = 0;
452 for (size_t i = 0; i < numSubSamples; ++i) {
453 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
454 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700455 if (size == 0) {
456 buffer->setRange(0, 0);
457 return OK;
458 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800459 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
460 std::shared_ptr<C2LinearBlock> block;
461 c2_status_t err = pool->fetchLinearBlock(
462 size,
463 secure ? kSecureUsage : kDefaultReadWriteUsage,
464 &block);
465 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700466 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
467 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800468 return NO_MEMORY;
469 }
470 if (!secure) {
471 ensureDecryptDestination(size);
472 }
473 ssize_t result = -1;
474 ssize_t codecDataOffset = 0;
475 if (mCrypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800476 int32_t heapSeqNum = getHeapSeqNum(memory);
477 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
478 hardware::drm::V1_0::DestinationBuffer dst;
479 if (secure) {
480 dst.type = DrmBufferType::NATIVE_HANDLE;
481 dst.secureMemory = hardware::hidl_handle(block->handle());
482 } else {
483 dst.type = DrmBufferType::SHARED_MEMORY;
484 IMemoryToSharedBuffer(
485 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
486 }
487 result = mCrypto->decrypt(
488 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000489 dst, errorDetailMsg);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800490 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700491 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800492 return result;
493 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800494 } else {
495 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
496 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
497 hidl_vec<SubSample> hidlSubSamples;
498 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
499
500 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
501 hardware::cas::native::V1_0::DestinationBuffer dst;
502 if (secure) {
503 dst.type = BufferType::NATIVE_HANDLE;
504 dst.secureMemory = hardware::hidl_handle(block->handle());
505 } else {
506 dst.type = BufferType::SHARED_MEMORY;
507 dst.nonsecureMemory = src;
508 }
509
510 CasStatus status = CasStatus::OK;
511 hidl_string detailedError;
512 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
513
514 if (key != nullptr) {
515 sctrl = (ScramblingControl)key[0];
516 // Adjust for the PES offset
517 codecDataOffset = key[2] | (key[3] << 8);
518 }
519
520 auto returnVoid = mDescrambler->descramble(
521 sctrl,
522 hidlSubSamples,
523 src,
524 0,
525 dst,
526 0,
527 [&status, &result, &detailedError] (
528 CasStatus _status, uint32_t _bytesWritten,
529 const hidl_string& _detailedError) {
530 status = _status;
531 result = (ssize_t)_bytesWritten;
532 detailedError = _detailedError;
533 });
Arun Johnson634d0802023-02-14 22:07:51 +0000534 if (errorDetailMsg) {
535 errorDetailMsg->setTo(detailedError.c_str(), detailedError.size());
536 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800537 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
538 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
539 mName, returnVoid.description().c_str(), status, result);
540 return UNKNOWN_ERROR;
541 }
542
543 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700544 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
545 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800546 return BAD_VALUE;
547 }
548 }
549 if (!secure) {
550 C2WriteView view = block->map().get();
551 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700552 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
553 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800554 return UNKNOWN_ERROR;
555 }
556 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700557 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
558 "(non-secure)",
559 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800560 return UNKNOWN_ERROR;
561 }
562 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
563 }
564 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
565 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
566 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700567 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800568 return -ENOSYS;
569 }
570 return OK;
571}
572
Pawin Vongmasa36653902018-11-15 00:10:25 -0800573status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
574 QueueGuard guard(mSync);
575 if (!guard.isRunning()) {
576 ALOGD("[%s] No more buffers should be queued at current state.", mName);
577 return -ENOSYS;
578 }
579 return queueInputBufferInternal(buffer);
580}
581
582status_t CCodecBufferChannel::queueSecureInputBuffer(
583 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
584 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
585 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
586 AString *errorDetailMsg) {
587 QueueGuard guard(mSync);
588 if (!guard.isRunning()) {
589 ALOGD("[%s] No more buffers should be queued at current state.", mName);
590 return -ENOSYS;
591 }
592
593 if (!hasCryptoOrDescrambler()) {
594 return -ENOSYS;
595 }
596 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
597
Sungtak Lee04b30352020-07-27 13:57:25 -0700598 std::shared_ptr<C2LinearBlock> block;
599 size_t allocSize = buffer->size();
600 size_t bufferSize = 0;
601 c2_status_t blockRes = C2_OK;
602 bool copied = false;
Arun Johnson7ba67072023-11-06 22:23:04 +0000603 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
604 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
Sungtak Lee04b30352020-07-27 13:57:25 -0700605 if (mSendEncryptedInfoBuffer) {
606 static const C2MemoryUsage kDefaultReadWriteUsage{
607 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
608 constexpr int kAllocGranule0 = 1024 * 64;
609 constexpr int kAllocGranule1 = 1024 * 1024;
610 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
611 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
612 if (allocSize <= kAllocGranule1) {
613 bufferSize = align(allocSize, kAllocGranule0);
614 } else {
615 bufferSize = align(allocSize, kAllocGranule1);
616 }
617 blockRes = pool->fetchLinearBlock(
618 bufferSize, kDefaultReadWriteUsage, &block);
619
620 if (blockRes == C2_OK) {
621 C2WriteView view = block->map().get();
622 if (view.error() == C2_OK && view.size() == bufferSize) {
623 copied = true;
624 // TODO: only copy clear sections
625 memcpy(view.data(), buffer->data(), allocSize);
626 }
627 }
628 }
629
630 if (!copied) {
631 block.reset();
632 }
633
Pawin Vongmasa36653902018-11-15 00:10:25 -0800634 ssize_t result = -1;
635 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700636 if (numSubSamples == 1
637 && subSamples[0].mNumBytesOfClearData == 0
638 && subSamples[0].mNumBytesOfEncryptedData == 0) {
639 // We don't need to go through crypto or descrambler if the input is empty.
640 result = 0;
641 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700642 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800643 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700644 destination.type = DrmBufferType::NATIVE_HANDLE;
645 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800646 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700647 destination.type = DrmBufferType::SHARED_MEMORY;
648 IMemoryToSharedBuffer(
649 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800650 }
Robert Shih895fba92019-07-16 16:29:44 -0700651 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800652 encryptedBuffer->fillSourceBuffer(&source);
653 result = mCrypto->decrypt(
654 key, iv, mode, pattern, source, buffer->offset(),
655 subSamples, numSubSamples, destination, errorDetailMsg);
656 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700657 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800658 return result;
659 }
Robert Shih895fba92019-07-16 16:29:44 -0700660 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800661 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
662 }
663 } else {
664 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
665 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
666 hidl_vec<SubSample> hidlSubSamples;
667 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
668
669 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
670 encryptedBuffer->fillSourceBuffer(&srcBuffer);
671
672 DestinationBuffer dstBuffer;
673 if (secure) {
674 dstBuffer.type = BufferType::NATIVE_HANDLE;
675 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
676 } else {
677 dstBuffer.type = BufferType::SHARED_MEMORY;
678 dstBuffer.nonsecureMemory = srcBuffer;
679 }
680
681 CasStatus status = CasStatus::OK;
682 hidl_string detailedError;
683 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
684
685 if (key != nullptr) {
686 sctrl = (ScramblingControl)key[0];
687 // Adjust for the PES offset
688 codecDataOffset = key[2] | (key[3] << 8);
689 }
690
691 auto returnVoid = mDescrambler->descramble(
692 sctrl,
693 hidlSubSamples,
694 srcBuffer,
695 0,
696 dstBuffer,
697 0,
698 [&status, &result, &detailedError] (
699 CasStatus _status, uint32_t _bytesWritten,
700 const hidl_string& _detailedError) {
701 status = _status;
702 result = (ssize_t)_bytesWritten;
703 detailedError = _detailedError;
704 });
705
706 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
707 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
708 mName, returnVoid.description().c_str(), status, result);
709 return UNKNOWN_ERROR;
710 }
711
712 if (result < codecDataOffset) {
713 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
714 return BAD_VALUE;
715 }
716
717 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
718
719 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
720 encryptedBuffer->copyDecryptedContentFromMemory(result);
721 }
722 }
723
724 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700725
726 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800727}
728
729void CCodecBufferChannel::feedInputBufferIfAvailable() {
730 QueueGuard guard(mSync);
731 if (!guard.isRunning()) {
732 ALOGV("[%s] We're not running --- no input buffer reported", mName);
733 return;
734 }
735 feedInputBufferIfAvailableInternal();
736}
737
738void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900739 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800740 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700741 }
742 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700743 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700744 if (!output->buffers ||
745 output->buffers->hasPending() ||
Wonsik Kim3722abc2023-05-17 13:26:31 -0700746 (!output->bounded && output->buffers->numActiveSlots() >= output->numSlots)) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800747 return;
748 }
749 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700750 size_t numActiveSlots = 0;
751 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800752 sp<MediaCodecBuffer> inBuffer;
753 size_t index;
754 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700755 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700756 numActiveSlots = input->buffers->numActiveSlots();
757 if (numActiveSlots >= input->numSlots) {
758 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800759 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700760 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800761 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800762 break;
763 }
764 }
765 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
766 mCallback->onInputBufferAvailable(index, inBuffer);
767 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700768 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800769}
770
771status_t CCodecBufferChannel::renderOutputBuffer(
772 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800773 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800774 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800775 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800776 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700777 Mutexed<Output>::Locked output(mOutput);
778 if (output->buffers) {
779 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800780 }
781 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800782 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
783 // set to true.
784 sendOutputBuffers();
785 // input buffer feeding may have been gated by pending output buffers
786 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800787 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800788 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700789 std::call_once(mRenderWarningFlag, [this] {
790 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
791 "timestamp or render=true with non-video buffers. Apps should "
792 "call releaseOutputBuffer() with render=false for those.",
793 mName);
794 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800795 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800796 return INVALID_OPERATION;
797 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800798
799#if 0
800 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
801 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
802 for (const std::shared_ptr<const C2Info> &info : infoParams) {
803 AString res;
804 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
805 if (ix) res.append(", ");
806 res.append(*((int32_t*)info.get() + (ix / 4)));
807 }
808 ALOGV(" [%s]", res.c_str());
809 }
810#endif
811 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
812 std::static_pointer_cast<const C2StreamRotationInfo::output>(
813 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
814 bool flip = rotation && (rotation->flip & 1);
815 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900816
817 {
818 Mutexed<OutputSurface>::Locked output(mOutputSurface);
819 if (output->surface == nullptr) {
820 ALOGI("[%s] cannot render buffer without surface", mName);
821 return OK;
822 }
823 int64_t frameIndex;
824 buffer->meta()->findInt64("frameIndex", &frameIndex);
825 if (output->rotation.count(frameIndex) != 0) {
826 auto it = output->rotation.find(frameIndex);
827 quarters = (it->second / 90) & 3;
828 output->rotation.erase(it);
829 }
830 }
831
Pawin Vongmasa36653902018-11-15 00:10:25 -0800832 uint32_t transform = 0;
833 switch (quarters) {
834 case 0: // no rotation
835 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
836 break;
837 case 1: // 90 degrees counter-clockwise
838 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
839 : HAL_TRANSFORM_ROT_270;
840 break;
841 case 2: // 180 degrees
842 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
843 break;
844 case 3: // 90 degrees clockwise
845 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
846 : HAL_TRANSFORM_ROT_90;
847 break;
848 }
849
850 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
851 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
852 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
853 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
854 if (surfaceScaling) {
855 videoScalingMode = surfaceScaling->value;
856 }
857
858 // Use dataspace from format as it has the default aspects already applied
859 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
860 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
861
862 // HDR static info
863 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
864 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
865 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
866
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800867 // HDR10 plus info
868 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
869 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
870 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800871 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
872 hdr10PlusInfo.reset();
873 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800874
Wonsik Kima79c5522022-01-18 16:29:24 -0800875 // HDR dynamic info
876 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
877 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
878 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
879 // TODO: make this sticky & enable unset
880 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
881 hdrDynamicInfo.reset();
882 }
883
884 if (hdr10PlusInfo) {
885 // C2StreamHdr10PlusInfo is deprecated; components should use
886 // C2StreamHdrDynamicMetadataInfo
887 // TODO: #metric
888 if (hdrDynamicInfo) {
889 // It is unexpected that C2StreamHdr10PlusInfo and
890 // C2StreamHdrDynamicMetadataInfo is both present.
891 // C2StreamHdrDynamicMetadataInfo takes priority.
892 // TODO: #metric
893 } else {
894 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
895 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
896 hdr10PlusInfo->flexCount(),
897 0u,
898 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
899 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
900 hdrDynamicInfo = info;
901 }
902 }
903
Pawin Vongmasa36653902018-11-15 00:10:25 -0800904 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
905 if (blocks.size() != 1u) {
906 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
907 return UNKNOWN_ERROR;
908 }
909 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700910 C2Fence c2fence = block.fence();
911 sp<Fence> fence = Fence::NO_FENCE;
912 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
913 // Once C2Fence::type() is added, check the exact C2Fence type
914 if (c2fence.isHW()) {
915 int fenceFd = c2fence.fd();
916 fence = sp<Fence>::make(fenceFd);
917 if (!fence) {
918 ALOGE("[%s] Failed to allocate a fence", mName);
919 close(fenceFd);
920 return NO_MEMORY;
921 }
922 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800923
924 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -0700925 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800926 timestampNs,
927 false, // droppable
928 dataSpace,
929 Rect(blocks.front().crop().left,
930 blocks.front().crop().top,
931 blocks.front().crop().right(),
932 blocks.front().crop().bottom()),
933 videoScalingMode,
934 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700935 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800936 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800937 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800938 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800939 // If mastering max and min luminance fields are 0, do not use them.
940 // It indicates the value may not be present in the stream.
941 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
942 hdrStaticInfo->mastering.minLuminance > 0.0f) {
943 struct android_smpte2086_metadata smpte2086_meta = {
944 .displayPrimaryRed = {
945 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
946 },
947 .displayPrimaryGreen = {
948 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
949 },
950 .displayPrimaryBlue = {
951 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
952 },
953 .whitePoint = {
954 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
955 },
956 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
957 .minLuminance = hdrStaticInfo->mastering.minLuminance,
958 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800959 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800960 hdr.smpte2086 = smpte2086_meta;
961 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700962 // If the content light level fields are 0, do not use them, it
963 // indicates the value may not be present in the stream.
964 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
965 struct android_cta861_3_metadata cta861_meta = {
966 .maxContentLightLevel = hdrStaticInfo->maxCll,
967 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
968 };
969 hdr.validTypes |= HdrMetadata::CTA861_3;
970 hdr.cta8613 = cta861_meta;
971 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900972
973 // does not have valid info
974 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
975 hdrStaticInfo.reset();
976 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800977 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800978 if (hdrDynamicInfo
979 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800980 hdr.validTypes |= HdrMetadata::HDR10PLUS;
981 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800982 hdrDynamicInfo->m.data,
983 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800984 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800985 qbi.setHdrMetadata(hdr);
986 }
Hongguangfc1478a2022-07-20 22:56:06 -0700987 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
988
Brian Lindahl932bf602023-03-09 11:59:48 -0700989 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
990 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
991 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800992 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
993 if (result != OK) {
994 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800995 if (result == NO_INIT) {
996 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
997 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800998 return result;
999 }
Josh Hou8eddf4b2021-02-02 16:26:53 +08001000
1001 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
1002 ALOGD("[%s] queue buffer successful", mName);
1003 } else {
1004 ALOGV("[%s] queue buffer successful", mName);
1005 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001006
1007 int64_t mediaTimeUs = 0;
1008 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahld7967a92023-08-10 10:12:49 -06001009 if (mAreRenderMetricsEnabled && mIsSurfaceToDisplay) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001010 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
1011 processRenderedFrames(qbo.frameTimestamps);
1012 } else {
1013 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
1014 // when the frame is queued to the non-display surface
1015 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1016 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001017
1018 return OK;
1019}
1020
Brian Lindahl932bf602023-03-09 11:59:48 -07001021void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001022 mTrackedFrames.clear();
1023
1024 int isSurfaceToDisplay = 0;
1025 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1026 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1027 // No frame tracking is needed if we're not sending frames to the display
1028 if (!mIsSurfaceToDisplay) {
1029 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1030 return;
1031 }
1032
Brian Lindahl932bf602023-03-09 11:59:48 -07001033 int hasPresentFenceTimes = 0;
1034 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1035 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
Brian Lindahl119e0c22023-05-19 15:42:13 -06001036 if (!mHasPresentFenceTimes) {
Brian Lindahl932bf602023-03-09 11:59:48 -07001037 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1038 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001039}
1040
1041void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1042 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1043 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1044 // so track the frame as if the desired render time is now.
1045 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1046 if (desiredRenderTimeNs < nowNs) {
1047 desiredRenderTimeNs = nowNs;
1048 }
Brian Lindahlc8bd9272023-08-28 09:42:43 -06001049
1050 // If the render time is more than a second from now, then pretend the frame is supposed to be
1051 // rendered immediately, because that's what SurfaceFlinger heuristics will do. This is a tight
1052 // coupling, but is really the only way to optimize away unnecessary present fence checks in
1053 // processRenderedFrames.
1054 if (desiredRenderTimeNs > nowNs + 1*1000*1000*1000LL) {
1055 desiredRenderTimeNs = nowNs;
1056 }
1057
Brian Lindahl932bf602023-03-09 11:59:48 -07001058 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1059 // actually rendered.
1060 TrackedFrame frame;
1061 frame.number = qbo.nextFrameNumber - 1;
1062 frame.mediaTimeUs = mediaTimeUs;
1063 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1064 frame.latchTime = -1;
1065 frame.presentFence = nullptr;
1066 mTrackedFrames.push_back(frame);
1067}
1068
1069void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1070 // Grab the latch times and present fences from the frame event deltas
1071 for (const auto& delta : deltas) {
1072 for (auto& frame : mTrackedFrames) {
1073 if (delta.getFrameNumber() == frame.number) {
1074 delta.getLatchTime(&frame.latchTime);
1075 delta.getDisplayPresentFence(&frame.presentFence);
1076 }
1077 }
1078 }
1079
1080 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1081 // in fact, been rendered.
1082 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1083 while (!mTrackedFrames.empty()) {
1084 TrackedFrame & frame = mTrackedFrames.front();
1085 // Frames that should have been rendered at least 100ms in the past are checked
1086 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1087 break;
1088 }
1089
1090 // If we don't have a render time by now, then consider the frame as dropped
1091 int64_t renderTimeNs = getRenderTimeNs(frame);
1092 if (renderTimeNs != -1) {
1093 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1094 }
1095 mTrackedFrames.pop_front();
1096 }
1097}
1098
1099int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1100 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1101 if (!mHasPresentFenceTimes) {
1102 if (frame.latchTime == -1) {
1103 ALOGD("no latch time for frame %d", (int) frame.number);
1104 return -1;
1105 }
1106 return frame.latchTime;
1107 }
1108
1109 if (frame.presentFence == nullptr) {
1110 ALOGW("no present fence for frame %d", (int) frame.number);
1111 return -1;
1112 }
1113
1114 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1115
1116 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1117 ALOGW("invalid signal time for frame %d", (int) frame.number);
1118 return -1;
1119 }
1120
1121 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1122 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1123 return -1;
1124 }
1125
1126 return actualRenderTimeNs;
1127}
1128
1129void CCodecBufferChannel::pollForRenderedBuffers() {
1130 FrameEventHistoryDelta delta;
1131 mComponent->pollForRenderedFrames(&delta);
1132 processRenderedFrames(delta);
1133}
1134
Sungtak Lee214ce612023-11-01 10:01:13 +00001135void CCodecBufferChannel::onBufferReleasedFromOutputSurface(uint32_t generation) {
Sungtak Lee6700cc92023-11-22 18:04:05 +00001136 // Note: Since this is called asynchronously from IProducerListener not
1137 // knowing the internal state of CCodec/CCodecBufferChannel,
1138 // prevent mComponent from being destroyed by holding the shared reference
1139 // during this interface being executed.
1140 std::shared_ptr<Codec2Client::Component> comp = mComponent;
1141 if (comp) {
1142 comp->onBufferReleasedFromOutputSurface(generation);
1143 }
Sungtak Lee214ce612023-11-01 10:01:13 +00001144}
1145
Pawin Vongmasa36653902018-11-15 00:10:25 -08001146status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1147 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1148 bool released = false;
1149 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001150 Mutexed<Input>::Locked input(mInput);
1151 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001152 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001153 }
1154 }
1155 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001156 Mutexed<Output>::Locked output(mOutput);
1157 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001158 released = true;
1159 }
1160 }
1161 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001162 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001163 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001164 } else {
1165 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1166 }
1167 return OK;
1168}
1169
1170void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1171 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001172 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001173
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001174 if (!input->buffers) {
1175 ALOGE("getInputBufferArray: No Input Buffers allocated");
1176 return;
1177 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001178 if (!input->buffers->isArrayMode()) {
1179 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001180 }
1181
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001182 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001183}
1184
1185void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1186 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001187 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001188 if (!output->buffers) {
1189 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1190 return;
1191 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001192 if (!output->buffers->isArrayMode()) {
1193 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001194 }
1195
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001196 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001197}
1198
1199status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001200 const sp<AMessage> &inputFormat,
1201 const sp<AMessage> &outputFormat,
1202 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001203 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1204 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001205 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001206 C2PortReorderBufferDepthTuning::output reorderDepth;
1207 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001208 C2PortActualDelayTuning::input inputDelay(0);
1209 C2PortActualDelayTuning::output outputDelay(0);
1210 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001211 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001212
Pawin Vongmasa36653902018-11-15 00:10:25 -08001213 c2_status_t err = mComponent->query(
1214 {
1215 &iStreamFormat,
1216 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001217 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001218 &reorderDepth,
1219 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001220 &inputDelay,
1221 &pipelineDelay,
1222 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001223 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001224 },
1225 {},
1226 C2_DONT_BLOCK,
1227 nullptr);
1228 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001229 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001230 return UNKNOWN_ERROR;
1231 }
1232 } else if (err != C2_OK) {
1233 return UNKNOWN_ERROR;
1234 }
1235
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001236 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1237 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1238 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1239
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001240 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1241 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001242
Pawin Vongmasa36653902018-11-15 00:10:25 -08001243 // TODO: get this from input format
1244 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1245
Sungtak Lee04b30352020-07-27 13:57:25 -07001246 // secure mode is a static parameter (shall not change in the executing state)
1247 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1248
Pawin Vongmasa36653902018-11-15 00:10:25 -08001249 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001250 int poolMask = GetCodec2PoolMask();
1251 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001252
1253 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001254 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001255 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001256 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1257 API_REFLECTION |
1258 API_VALUES |
1259 API_CURRENT_VALUES |
1260 API_DEPENDENCY |
1261 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001262 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1263 C2StreamSampleRateInfo::input sampleRate(0u);
1264 C2StreamChannelCountInfo::input channelCount(0u);
1265 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001266 std::shared_ptr<C2BlockPool> pool;
1267 {
1268 Mutexed<BlockPools>::Locked pools(mBlockPools);
1269
1270 // set default allocator ID.
1271 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001272 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001273
1274 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1275 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1276 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001277 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001278 std::vector<C2Param *> stackParams({&featuresSetting});
1279 if (audioEncoder) {
1280 stackParams.push_back(&encoderFrameSize);
1281 stackParams.push_back(&sampleRate);
1282 stackParams.push_back(&channelCount);
1283 stackParams.push_back(&pcmEncoding);
1284 } else {
1285 encoderFrameSize.invalidate();
1286 sampleRate.invalidate();
1287 channelCount.invalidate();
1288 pcmEncoding.invalidate();
1289 }
1290 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001291 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1292 C2_DONT_BLOCK,
1293 &params);
1294 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1295 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1296 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001297 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001298 C2PortAllocatorsTuning::input *inputAllocators =
1299 C2PortAllocatorsTuning::input::From(params[0].get());
1300 if (inputAllocators && inputAllocators->flexCount() > 0) {
1301 std::shared_ptr<C2Allocator> allocator;
1302 // verify allocator IDs and resolve default allocator
1303 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1304 if (allocator) {
1305 pools->inputAllocatorId = allocator->getId();
1306 } else {
1307 ALOGD("[%s] component requested invalid input allocator ID %u",
1308 mName, inputAllocators->m.values[0]);
1309 }
1310 }
1311 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001312 if (featuresSetting) {
1313 apiFeatures = featuresSetting.value;
1314 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001315
1316 // TODO: use C2Component wrapper to associate this pool with ourselves
1317 if ((poolMask >> pools->inputAllocatorId) & 1) {
1318 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1319 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1320 mName, pools->inputAllocatorId,
1321 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1322 asString(err), err);
1323 } else {
1324 err = C2_NOT_FOUND;
1325 }
1326 if (err != C2_OK) {
1327 C2BlockPool::local_id_t inputPoolId =
1328 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1329 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1330 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1331 mName, (unsigned long long)inputPoolId,
1332 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1333 asString(err), err);
1334 if (err != C2_OK) {
1335 return NO_MEMORY;
1336 }
1337 }
1338 pools->inputPool = pool;
1339 }
1340
Wonsik Kim51051262018-11-28 13:59:05 -08001341 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001342 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001343 input->inputDelay = inputDelayValue;
1344 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001345 input->numSlots = numInputSlots;
1346 input->extraBuffers.flush();
1347 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001348 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001349 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1350 input->frameReassembler.init(
1351 pool,
1352 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1353 encoderFrameSize.value,
1354 sampleRate.value,
1355 channelCount.value,
1356 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1357 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001358 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1359 // For encrypted content, framework decrypts source buffer (ashmem) into
1360 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001361 if (!buffersBoundToCodec
1362 && !input->frameReassembler
1363 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001364 input->buffers.reset(new SlotInputBuffers(mName));
1365 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001366 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001367 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001368 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001369 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001370 // This is to ensure buffers do not get released prematurely.
1371 // TODO: handle this without going into array mode
1372 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001373 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001374 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001375 }
1376 } else {
1377 if (hasCryptoOrDescrambler()) {
1378 int32_t capacity = kLinearBufferSize;
1379 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1380 if ((size_t)capacity > kMaxLinearBufferSize) {
1381 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1382 capacity = kMaxLinearBufferSize;
1383 }
1384 if (mDealer == nullptr) {
1385 mDealer = new MemoryDealer(
1386 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001387 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001388 "EncryptedLinearInputBuffers");
1389 mDecryptDestination = mDealer->allocate((size_t)capacity);
1390 }
1391 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001392 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1393 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 } else {
1395 mHeapSeqNum = -1;
1396 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001397 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001398 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001399 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001400 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001401 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001402 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001403 }
1404 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001405 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001406
1407 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001408 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001409 } else {
1410 // TODO: error
1411 }
Wonsik Kim51051262018-11-28 13:59:05 -08001412
1413 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001414 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001415 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001416 }
1417
1418 if (outputFormat != nullptr) {
1419 sp<IGraphicBufferProducer> outputSurface;
1420 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001421 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001422 {
1423 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001424 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001425 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001426 outputSurface = output->surface ?
1427 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001428 if (outputSurface) {
1429 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1430 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001431 outputGeneration = output->generation;
1432 }
1433
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001434 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001435 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001436 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001437
1438 {
1439 Mutexed<BlockPools>::Locked pools(mBlockPools);
1440
David Stevensc3fbb282021-01-18 18:11:20 +09001441 prevOutputPoolId = pools->outputPoolId;
1442
Pawin Vongmasa36653902018-11-15 00:10:25 -08001443 // set default allocator ID.
1444 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001445 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001446
1447 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1448 // unsuccessful.
1449 std::vector<std::unique_ptr<C2Param>> params;
1450 err = mComponent->query({ },
1451 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1452 C2_DONT_BLOCK,
1453 &params);
1454 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1455 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1456 mName, params.size(), asString(err), err);
1457 } else if (err == C2_OK && params.size() == 1) {
1458 C2PortAllocatorsTuning::output *outputAllocators =
1459 C2PortAllocatorsTuning::output::From(params[0].get());
1460 if (outputAllocators && outputAllocators->flexCount() > 0) {
1461 std::shared_ptr<C2Allocator> allocator;
1462 // verify allocator IDs and resolve default allocator
1463 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1464 if (allocator) {
1465 pools->outputAllocatorId = allocator->getId();
1466 } else {
1467 ALOGD("[%s] component requested invalid output allocator ID %u",
1468 mName, outputAllocators->m.values[0]);
1469 }
1470 }
1471 }
1472
1473 // use bufferqueue if outputting to a surface.
1474 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1475 // if unsuccessful.
1476 if (outputSurface) {
1477 params.clear();
1478 err = mComponent->query({ },
1479 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1480 C2_DONT_BLOCK,
1481 &params);
1482 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1483 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1484 mName, params.size(), asString(err), err);
1485 } else if (err == C2_OK && params.size() == 1) {
1486 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1487 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1488 if (surfaceAllocator) {
1489 std::shared_ptr<C2Allocator> allocator;
1490 // verify allocator IDs and resolve default allocator
1491 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1492 if (allocator) {
1493 pools->outputAllocatorId = allocator->getId();
1494 } else {
1495 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1496 mName, surfaceAllocator->value);
1497 err = C2_BAD_VALUE;
1498 }
1499 }
1500 }
1501 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1502 && err != C2_OK
1503 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1504 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1505 }
1506 }
1507
1508 if ((poolMask >> pools->outputAllocatorId) & 1) {
1509 err = mComponent->createBlockPool(
1510 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1511 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1512 mName, pools->outputAllocatorId,
1513 (unsigned long long)pools->outputPoolId,
1514 asString(err));
1515 } else {
1516 err = C2_NOT_FOUND;
1517 }
1518 if (err != C2_OK) {
1519 // use basic pool instead
1520 pools->outputPoolId =
1521 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1522 }
1523
1524 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1525 // component.
1526 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1527 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1528
1529 std::vector<std::unique_ptr<C2SettingResult>> failures;
1530 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1531 ALOGD("[%s] Configured output block pool ids %llu => %s",
1532 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1533 outputPoolId_ = pools->outputPoolId;
1534 }
1535
David Stevensc3fbb282021-01-18 18:11:20 +09001536 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1537 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1538 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1539 if (err != C2_OK) {
1540 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1541 (unsigned long long) prevOutputPoolId, asString(err), err);
1542 }
1543 }
1544
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001545 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001546 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001547 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001548 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001549 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001550 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001551 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001552 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001553 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001554 }
1555 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001556 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001557 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001558 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001559
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001560 output->buffers->clearStash();
1561 if (reorderDepth) {
1562 output->buffers->setReorderDepth(reorderDepth.value);
1563 }
1564 if (reorderKey) {
1565 output->buffers->setReorderKey(reorderKey.value);
1566 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001567
1568 // Try to set output surface to created block pool if given.
1569 if (outputSurface) {
1570 mComponent->setOutputSurface(
1571 outputPoolId_,
1572 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001573 outputGeneration,
1574 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001575 } else {
1576 // configure CPU read consumer usage
1577 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1578 std::vector<std::unique_ptr<C2SettingResult>> failures;
1579 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1580 // do not print error message for now as most components may not yet
1581 // support this setting
1582 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1583 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001584 }
1585
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001586 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001587 if (buffersBoundToCodec) {
1588 // WORKAROUND: if we're using early CSD workaround we convert to
1589 // array mode, to appease apps assuming the output
1590 // buffers to be of the same size.
1591 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1592 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001593
1594 int32_t channelCount;
1595 int32_t sampleRate;
1596 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1597 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1598 int32_t delay = 0;
1599 int32_t padding = 0;;
1600 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1601 delay = 0;
1602 }
1603 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1604 padding = 0;
1605 }
1606 if (delay || padding) {
Arun Johnson52d323e2024-01-05 21:16:56 +00001607 // We need write access to the buffers, so turn them into array mode.
1608 // TODO: b/321930152 - define SkipCutOutputBuffers that takes output from
1609 // component, runs it through SkipCutBuffer and allocate local buffer to be
1610 // used by fwk. Make initSkipCutBuffer() return OutputBuffers similar to
1611 // toArrayMode().
1612 if (!output->buffers->isArrayMode()) {
1613 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1614 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001615 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001616 }
1617 }
1618 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001619
1620 int32_t tunneled = 0;
1621 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1622 tunneled = 0;
1623 }
1624 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001625 }
1626
1627 // Set up pipeline control. This has to be done after mInputBuffers and
1628 // mOutputBuffers are initialized to make sure that lingering callbacks
1629 // about buffers from the previous generation do not interfere with the
1630 // newly initialized pipeline capacity.
1631
Wonsik Kim62545252021-01-20 11:25:41 -08001632 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001633 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001634 watcher->inputDelay(inputDelayValue)
1635 .pipelineDelay(pipelineDelayValue)
1636 .outputDelay(outputDelayValue)
Houxiang Dai0b573282023-03-11 18:31:56 +08001637 .smoothnessFactor(kSmoothnessFactor)
1638 .tunneled(mTunneled);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001639 watcher->flush();
1640 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001641
1642 mInputMetEos = false;
1643 mSync.start();
1644 return OK;
1645}
1646
Wonsik Kim34b28b42022-05-20 15:49:32 -07001647status_t CCodecBufferChannel::prepareInitialInputBuffers(
Arun Johnson326166e2023-07-28 19:11:52 +00001648 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers, bool retry) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001649 if (mInputSurface) {
1650 return OK;
1651 }
1652
Wonsik Kim34b28b42022-05-20 15:49:32 -07001653 size_t numInputSlots = mInput.lock()->numSlots;
Arun Johnson326166e2023-07-28 19:11:52 +00001654 int retryCount = 1;
1655 for (; clientInputBuffers->empty() && retryCount >= 0; retryCount--) {
1656 {
1657 Mutexed<Input>::Locked input(mInput);
1658 while (clientInputBuffers->size() < numInputSlots) {
1659 size_t index;
1660 sp<MediaCodecBuffer> buffer;
1661 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1662 break;
1663 }
1664 clientInputBuffers->emplace(index, buffer);
Wonsik Kim34b28b42022-05-20 15:49:32 -07001665 }
Arun Johnson326166e2023-07-28 19:11:52 +00001666 }
1667 if (!retry || (retryCount <= 0)) {
1668 break;
1669 }
1670 if (clientInputBuffers->empty()) {
1671 // wait: buffer may be in transit from component.
1672 std::this_thread::sleep_for(std::chrono::milliseconds(4));
Wonsik Kim34b28b42022-05-20 15:49:32 -07001673 }
1674 }
1675 if (clientInputBuffers->empty()) {
1676 ALOGW("[%s] start: cannot allocate memory at all", mName);
1677 return NO_MEMORY;
1678 } else if (clientInputBuffers->size() < numInputSlots) {
1679 ALOGD("[%s] start: cannot allocate memory for all slots, "
1680 "only %zu buffers allocated",
1681 mName, clientInputBuffers->size());
1682 } else {
1683 ALOGV("[%s] %zu initial input buffers available",
1684 mName, clientInputBuffers->size());
1685 }
1686 return OK;
1687}
1688
1689status_t CCodecBufferChannel::requestInitialInputBuffers(
1690 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001691 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001692 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1693 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1694 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001695 return UNKNOWN_ERROR;
1696 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001697
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001698 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1699 mFlushedConfigs.lock()->swap(flushedConfigs);
1700 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001701 {
1702 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1703 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1704 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1705 watcher->onWorkQueued(
1706 work->input.ordinal.frameIndex.peeku(),
1707 std::vector(work->input.buffers),
1708 now);
1709 }
1710 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001711 err = mComponent->queue(&flushedConfigs);
1712 if (err != C2_OK) {
1713 ALOGW("[%s] Error while queueing a flushed config", mName);
1714 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001715 }
1716 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001717 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001718 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1719 !clientInputBuffers.empty()) {
1720 size_t minIndex = clientInputBuffers.begin()->first;
1721 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1722 for (const auto &[index, buffer] : clientInputBuffers) {
1723 if (minBuffer->capacity() > buffer->capacity()) {
1724 minIndex = index;
1725 minBuffer = buffer;
1726 }
1727 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001728 // WORKAROUND: Some apps expect CSD available without queueing
1729 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001730 minBuffer->setRange(0, 0);
1731 minBuffer->meta()->clear();
1732 minBuffer->meta()->setInt64("timeUs", 0);
1733 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001734 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1735 mName);
1736 return UNKNOWN_ERROR;
1737 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001738 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001739 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001740
Wonsik Kim34b28b42022-05-20 15:49:32 -07001741 for (const auto &[index, buffer] : clientInputBuffers) {
1742 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001743 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001744
Pawin Vongmasa36653902018-11-15 00:10:25 -08001745 return OK;
1746}
1747
1748void CCodecBufferChannel::stop() {
1749 mSync.stop();
1750 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001751}
1752
Sungtak Lee99144332023-01-26 11:03:14 +00001753void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
1754 sp<Surface> surface = mOutputSurface.lock()->surface;
1755 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00001756 C2BlockPool::local_id_t outputPoolId;
1757 {
1758 Mutexed<BlockPools>::Locked pools(mBlockPools);
1759 outputPoolId = pools->outputPoolId;
1760 }
1761 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00001762
1763 if (pushBlankBuffer) {
1764 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
1765 if (anw) {
1766 pushBlankBuffersToNativeWindow(anw.get());
1767 }
1768 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00001769 }
1770}
1771
Wonsik Kim936a89c2020-05-08 16:07:50 -07001772void CCodecBufferChannel::reset() {
1773 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001774 if (mInputSurface != nullptr) {
1775 mInputSurface.reset();
1776 }
1777 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001778 {
1779 Mutexed<Input>::Locked input(mInput);
1780 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001781 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001782 }
1783 {
1784 Mutexed<Output>::Locked output(mOutput);
1785 output->buffers.reset();
1786 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001787 // reset the frames that are being tracked for onFrameRendered callbacks
1788 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001789}
1790
1791void CCodecBufferChannel::release() {
1792 mComponent.reset();
1793 mInputAllocator.reset();
1794 mOutputSurface.lock()->surface.clear();
1795 {
1796 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1797 blockPools->inputPool.reset();
1798 blockPools->outputPoolIntf.reset();
1799 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001800 setCrypto(nullptr);
1801 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001802}
1803
Pawin Vongmasa36653902018-11-15 00:10:25 -08001804void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1805 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001806 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001807 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001808 {
1809 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1810 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1811 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1812 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1813 watcher->onWorkDone(frameIndex);
1814 continue;
1815 }
1816 if (work->input.buffers.empty()
1817 || work->input.buffers.front() == nullptr
1818 || work->input.buffers.front()->data().linearBlocks().empty()) {
1819 ALOGD("[%s] no linear codec config data found", mName);
1820 watcher->onWorkDone(frameIndex);
1821 continue;
1822 }
1823 std::unique_ptr<C2Work> copy(new C2Work);
1824 copy->input.flags = C2FrameData::flags_t(
1825 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1826 copy->input.ordinal = work->input.ordinal;
1827 copy->input.ordinal.frameIndex = mFrameIndex++;
1828 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1829 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1830 }
1831 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1832 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1833 }
1834 copy->input.infoBuffers.insert(
1835 copy->input.infoBuffers.begin(),
1836 work->input.infoBuffers.begin(),
1837 work->input.infoBuffers.end());
1838 copy->worklets.emplace_back(new C2Worklet);
1839 configs.push_back(std::move(copy));
1840 watcher->onWorkDone(frameIndex);
1841 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001842 }
1843 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001844 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001845 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001846 Mutexed<Input>::Locked input(mInput);
1847 input->buffers->flush();
1848 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001849 }
1850 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001851 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001852 if (output->buffers) {
1853 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001854 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001855 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001856 }
1857}
1858
1859void CCodecBufferChannel::onWorkDone(
1860 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001861 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001862 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001863 feedInputBufferIfAvailable();
1864 }
1865}
1866
1867void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001868 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001869 if (mInputSurface) {
1870 return;
1871 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001872 std::shared_ptr<C2Buffer> buffer =
1873 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001874 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001875 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001876 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001877 if (input->lastFlushIndex >= frameIndex) {
1878 ALOGD("[%s] Ignoring stale input buffer done callback: "
1879 "last flush index = %lld, frameIndex = %lld",
1880 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1881 } else {
1882 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1883 if (!newInputSlotAvailable) {
1884 (void)input->extraBuffers.expireComponentBuffer(buffer);
1885 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001886 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001887 }
1888 if (newInputSlotAvailable) {
1889 feedInputBufferIfAvailable();
1890 }
1891}
1892
1893bool CCodecBufferChannel::handleWork(
1894 std::unique_ptr<C2Work> work,
1895 const sp<AMessage> &outputFormat,
1896 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001897 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001898 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001899 if (!output->buffers) {
1900 return false;
1901 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001902 }
1903
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001904 // Whether the output buffer should be reported to the client or not.
1905 bool notifyClient = false;
1906
1907 if (work->result == C2_OK){
1908 notifyClient = true;
1909 } else if (work->result == C2_NOT_FOUND) {
1910 ALOGD("[%s] flushed work; ignored.", mName);
1911 } else {
1912 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1913 // the config update.
1914 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1915 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1916 return false;
1917 }
1918
1919 if ((work->input.ordinal.frameIndex -
1920 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001921 // Discard frames from previous generation.
1922 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001923 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001924 }
1925
Wonsik Kim524b0582019-03-12 11:28:57 -07001926 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001927 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001928 || !(work->worklets.front()->output.flags &
1929 C2FrameData::FLAG_INCOMPLETE))) {
1930 mPipelineWatcher.lock()->onWorkDone(
1931 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001932 }
1933
1934 // NOTE: MediaCodec usage supposedly have only one worklet
1935 if (work->worklets.size() != 1u) {
1936 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1937 mName, work->worklets.size());
1938 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1939 return false;
1940 }
1941
1942 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1943
1944 std::shared_ptr<C2Buffer> buffer;
1945 // NOTE: MediaCodec usage supposedly have only one output stream.
1946 if (worklet->output.buffers.size() > 1u) {
1947 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1948 mName, worklet->output.buffers.size());
1949 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1950 return false;
1951 } else if (worklet->output.buffers.size() == 1u) {
1952 buffer = worklet->output.buffers[0];
1953 if (!buffer) {
1954 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1955 }
1956 }
1957
Wonsik Kim3dedf682021-05-03 10:57:09 -07001958 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1959 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001960 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001961 while (!worklet->output.configUpdate.empty()) {
1962 std::unique_ptr<C2Param> param;
1963 worklet->output.configUpdate.back().swap(param);
1964 worklet->output.configUpdate.pop_back();
1965 switch (param->coreIndex().coreIndex()) {
1966 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1967 C2PortReorderBufferDepthTuning::output reorderDepth;
1968 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001969 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1970 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001971 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001972 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001973 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001974 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1975 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001976 }
1977 break;
1978 }
1979 case C2PortReorderKeySetting::CORE_INDEX: {
1980 C2PortReorderKeySetting::output reorderKey;
1981 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001982 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001983 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1984 mName, reorderKey.value);
1985 } else {
1986 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1987 }
1988 break;
1989 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001990 case C2PortActualDelayTuning::CORE_INDEX: {
1991 if (param->isGlobal()) {
1992 C2ActualPipelineDelayTuning pipelineDelay;
1993 if (pipelineDelay.updateFrom(*param)) {
1994 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1995 mName, pipelineDelay.value);
1996 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001997 (void)mPipelineWatcher.lock()->pipelineDelay(
1998 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001999 }
2000 }
2001 if (param->forInput()) {
2002 C2PortActualDelayTuning::input inputDelay;
2003 if (inputDelay.updateFrom(*param)) {
2004 ALOGV("[%s] onWorkDone: updating input delay %u",
2005 mName, inputDelay.value);
2006 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002007 (void)mPipelineWatcher.lock()->inputDelay(
2008 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002009 }
2010 }
2011 if (param->forOutput()) {
2012 C2PortActualDelayTuning::output outputDelay;
2013 if (outputDelay.updateFrom(*param)) {
2014 ALOGV("[%s] onWorkDone: updating output delay %u",
2015 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002016 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002017 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002018 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002019
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002020 }
2021 }
2022 break;
2023 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08002024 case C2PortTunnelSystemTime::CORE_INDEX: {
2025 C2PortTunnelSystemTime::output frameRenderTime;
2026 if (frameRenderTime.updateFrom(*param)) {
2027 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
2028 mName, (long long)frameRenderTime.value,
2029 (long long)worklet->output.ordinal.timestamp.peekll());
2030 mCCodecCallback->onOutputFramesRendered(
2031 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
2032 }
2033 break;
2034 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02002035 case C2StreamTunnelHoldRender::CORE_INDEX: {
2036 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
2037 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
2038 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
2039 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
2040 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
2041 mCCodecCallback->onFirstTunnelFrameReady();
2042 break;
2043 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002044 default:
2045 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2046 mName, param->index());
2047 break;
2048 }
2049 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002050 if (newInputDelay || newPipelineDelay) {
2051 Mutexed<Input>::Locked input(mInput);
2052 size_t newNumSlots =
2053 newInputDelay.value_or(input->inputDelay) +
2054 newPipelineDelay.value_or(input->pipelineDelay) +
2055 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08002056 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002057 if (input->buffers->isArrayMode()) {
2058 if (input->numSlots >= newNumSlots) {
2059 input->numExtraSlots = 0;
2060 } else {
2061 input->numExtraSlots = newNumSlots - input->numSlots;
2062 }
2063 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2064 mName, input->numExtraSlots);
2065 } else {
2066 input->numSlots = newNumSlots;
2067 }
2068 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002069 size_t numOutputSlots = 0;
2070 uint32_t reorderDepth = 0;
2071 bool outputBuffersChanged = false;
2072 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2073 Mutexed<Output>::Locked output(mOutput);
2074 if (!output->buffers) {
2075 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002076 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002077 numOutputSlots = output->numSlots;
2078 if (newReorderKey) {
2079 output->buffers->setReorderKey(newReorderKey.value());
2080 }
2081 if (newReorderDepth) {
2082 output->buffers->setReorderDepth(newReorderDepth.value());
2083 }
2084 reorderDepth = output->buffers->getReorderDepth();
2085 if (newOutputDelay) {
2086 output->outputDelay = newOutputDelay.value();
2087 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2088 if (output->numSlots < numOutputSlots) {
2089 output->numSlots = numOutputSlots;
2090 if (output->buffers->isArrayMode()) {
2091 OutputBuffersArray *array =
2092 (OutputBuffersArray *)output->buffers.get();
2093 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2094 mName, numOutputSlots);
2095 array->grow(numOutputSlots);
2096 outputBuffersChanged = true;
2097 }
2098 }
2099 }
2100 numOutputSlots = output->numSlots;
2101 }
2102 if (outputBuffersChanged) {
2103 mCCodecCallback->onOutputBuffersChanged();
2104 }
2105 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002106 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002107 {
2108 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2109 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002110 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002111 if (output->surface) {
2112 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2113 }
2114 }
2115 if (maxDequeueCount > 0) {
2116 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002117 }
2118 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002119
Pawin Vongmasa36653902018-11-15 00:10:25 -08002120 int32_t flags = 0;
2121 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002122 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002123 ALOGV("[%s] onWorkDone: output EOS", mName);
2124 }
2125
Pawin Vongmasa36653902018-11-15 00:10:25 -08002126 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2127 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2128 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2129 // shall correspond to the client input timesamp (in customOrdinal). By using the
2130 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2131 // produces multiple output.
2132 c2_cntr64_t timestamp =
2133 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2134 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002135 if (mInputSurface != nullptr) {
2136 // When using input surface we need to restore the original input timestamp.
2137 timestamp = work->input.ordinal.customOrdinal;
2138 }
My Name6bd9a7d2022-03-25 12:37:58 -07002139 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2140 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002141 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2142 mName,
2143 work->input.ordinal.customOrdinal.peekll(),
2144 work->input.ordinal.timestamp.peekll(),
2145 worklet->output.ordinal.timestamp.peekll(),
2146 timestamp.peekll());
2147
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002148 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002149 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002150 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002151 if (!output->buffers) {
2152 return false;
2153 }
2154 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002155 output->buffers->updateSkipCutBuffer(outputFormat);
2156 output->buffers->setFormat(outputFormat);
2157 }
2158 if (!notifyClient) {
2159 return false;
2160 }
2161 size_t index;
2162 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002163 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002164 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002165 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002166 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2167
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002168 // TRICKY: we want popped buffers reported in order, so sending
2169 // the callback while holding the lock here. This assumes that
2170 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2171 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002172 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002173 } else {
2174 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002175 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002176 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002177 return false;
2178 }
2179 }
2180
Wonsik Kimec585c32021-10-01 01:11:00 -07002181 bool drop = false;
2182 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2183 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2184 drop = true;
2185 }
2186
Marc Kassisec910342022-11-25 11:43:05 +01002187 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2188 // HAL, the flag is then removed in the corresponding output buffer.
2189 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2190 flags |= BUFFER_FLAG_DECODE_ONLY;
2191 }
2192
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002193 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002194 if (mTunneled && drop && outputFormat) {
Houxiang Daie74e5062022-05-19 15:32:54 +08002195 if (mOutputFormat != outputFormat) {
2196 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2197 mName, work->input.ordinal.frameIndex.peekull());
2198 mOutputFormat = outputFormat;
2199 } else {
2200 ALOGV("[%s] onWorkDone: Not reporting output buffer without format change (%lld)",
2201 mName, work->input.ordinal.frameIndex.peekull());
2202 notifyClient = false;
2203 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002204 } else {
2205 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2206 mName, work->input.ordinal.frameIndex.peekull());
2207 notifyClient = false;
2208 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002209 }
2210
2211 if (buffer) {
2212 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2213 // TODO: properly translate these to metadata
2214 switch (info->coreIndex().coreIndex()) {
2215 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002216 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002217 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002218 }
2219 break;
2220 default:
2221 break;
2222 }
2223 }
2224 }
2225
2226 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002227 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002228 if (!output->buffers) {
2229 return false;
2230 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002231 output->buffers->pushToStash(
2232 buffer,
2233 notifyClient,
2234 timestamp.peek(),
2235 flags,
2236 outputFormat,
2237 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002238 }
2239 sendOutputBuffers();
2240 return true;
2241}
2242
2243void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002244 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002245 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002246 sp<MediaCodecBuffer> outBuffer;
2247 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002248
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002249 constexpr int kMaxReallocTry = 5;
2250 int reallocTryNum = 0;
2251
Pawin Vongmasa36653902018-11-15 00:10:25 -08002252 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002253 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002254 if (!output->buffers) {
2255 return;
2256 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002257 action = output->buffers->popFromStashAndRegister(
2258 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002259 if (action != OutputBuffers::REALLOCATE) {
2260 reallocTryNum = 0;
2261 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002262 switch (action) {
2263 case OutputBuffers::SKIP:
2264 return;
2265 case OutputBuffers::DISCARD:
2266 break;
2267 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002268 // TRICKY: we want popped buffers reported in order, so sending
2269 // the callback while holding the lock here. This assumes that
2270 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2271 // callbacks are always sent with the Output lock held.
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002272 mCallback->onOutputBufferAvailable(index, outBuffer);
2273 break;
2274 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002275 if (++reallocTryNum > kMaxReallocTry) {
2276 output.unlock();
2277 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2278 mName, kMaxReallocTry);
2279 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2280 return;
2281 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002282 if (!output->buffers->isArrayMode()) {
2283 output->buffers =
2284 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002285 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002286 static_cast<OutputBuffersArray*>(output->buffers.get())->
2287 realloc(c2Buffer);
2288 output.unlock();
2289 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002290 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002291 case OutputBuffers::RETRY:
2292 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2293 mName);
2294 return;
2295 default:
2296 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2297 "corrupted BufferAction value (%d) "
2298 "returned from popFromStashAndRegister.",
2299 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002300 return;
2301 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002302 }
2303}
2304
Sungtak Lee214ce612023-11-01 10:01:13 +00002305status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface,
2306 uint32_t generation, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002307 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002308 int maxDequeueCount;
2309 sp<Surface> oldSurface;
2310 {
2311 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2312 maxDequeueCount = outputSurface->maxDequeueBuffers;
2313 oldSurface = outputSurface->surface;
2314 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002315 if (newSurface) {
2316 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002317 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002318 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002319 producer = newSurface->getIGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002320 } else {
2321 ALOGE("[%s] setting output surface to null", mName);
2322 return INVALID_OPERATION;
2323 }
2324
2325 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2326 C2BlockPool::local_id_t outputPoolId;
2327 {
2328 Mutexed<BlockPools>::Locked pools(mBlockPools);
2329 outputPoolId = pools->outputPoolId;
2330 outputPoolIntf = pools->outputPoolIntf;
2331 }
2332
2333 if (outputPoolIntf) {
2334 if (mComponent->setOutputSurface(
2335 outputPoolId,
2336 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002337 generation,
2338 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002339 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2340 return INVALID_OPERATION;
2341 }
2342 }
2343
2344 {
2345 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2346 output->surface = newSurface;
2347 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002348 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002349 }
2350
Sungtak Lee99144332023-01-26 11:03:14 +00002351 if (oldSurface && pushBlankBuffer) {
2352 // When ReleaseSurface was set from MediaCodec,
2353 // pushing a blank buffer at the end might be necessary.
2354 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2355 if (anw) {
2356 pushBlankBuffersToNativeWindow(anw.get());
2357 }
2358 }
2359
Pawin Vongmasa36653902018-11-15 00:10:25 -08002360 return OK;
2361}
2362
Wonsik Kimab34ed62019-01-31 15:28:46 -08002363PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002364 // Otherwise, component may have stalled work due to input starvation up to
2365 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002366 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2367 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002368 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002369 size_t outputDelay = mOutput.lock()->outputDelay;
2370 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002371 Mutexed<Input>::Locked input(mInput);
2372 n = input->inputDelay + input->pipelineDelay + outputDelay;
2373 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002374 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002375}
2376
Pawin Vongmasa36653902018-11-15 00:10:25 -08002377void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2378 mMetaMode = mode;
2379}
2380
Wonsik Kim596187e2019-10-25 12:44:10 -07002381void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002382 if (mCrypto != nullptr) {
2383 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2384 mCrypto->unsetHeap(entry.second);
2385 }
2386 mHeapSeqNumMap.clear();
2387 if (mHeapSeqNum >= 0) {
2388 mCrypto->unsetHeap(mHeapSeqNum);
2389 mHeapSeqNum = -1;
2390 }
2391 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002392 mCrypto = crypto;
2393}
2394
2395void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2396 mDescrambler = descrambler;
2397}
2398
Songyue Han1e6769b2023-08-30 18:09:27 +00002399uint32_t CCodecBufferChannel::getBuffersPixelFormat(bool isEncoder) {
2400 if (isEncoder) {
2401 return getInputBuffersPixelFormat();
2402 } else {
2403 return getOutputBuffersPixelFormat();
2404 }
2405}
2406
2407uint32_t CCodecBufferChannel::getInputBuffersPixelFormat() {
2408 Mutexed<Input>::Locked input(mInput);
2409 if (input->buffers == nullptr) {
2410 return PIXEL_FORMAT_UNKNOWN;
2411 }
2412 return input->buffers->getPixelFormatIfApplicable();
2413}
2414
2415uint32_t CCodecBufferChannel::getOutputBuffersPixelFormat() {
2416 Mutexed<Output>::Locked output(mOutput);
2417 if (output->buffers == nullptr) {
2418 return PIXEL_FORMAT_UNKNOWN;
2419 }
2420 return output->buffers->getPixelFormatIfApplicable();
2421}
2422
2423void CCodecBufferChannel::resetBuffersPixelFormat(bool isEncoder) {
2424 if (isEncoder) {
2425 Mutexed<Input>::Locked input(mInput);
2426 if (input->buffers == nullptr) {
2427 return;
2428 }
2429 input->buffers->resetPixelFormatIfApplicable();
2430 } else {
2431 Mutexed<Output>::Locked output(mOutput);
2432 if (output->buffers == nullptr) {
2433 return;
2434 }
2435 output->buffers->resetPixelFormatIfApplicable();
2436 }
2437}
2438
Pawin Vongmasa36653902018-11-15 00:10:25 -08002439status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2440 // C2_OK is always translated to OK.
2441 if (c2s == C2_OK) {
2442 return OK;
2443 }
2444
2445 // Operation-dependent translation
2446 // TODO: Add as necessary
2447 switch (c2op) {
2448 case C2_OPERATION_Component_start:
2449 switch (c2s) {
2450 case C2_NO_MEMORY:
2451 return NO_MEMORY;
2452 default:
2453 return UNKNOWN_ERROR;
2454 }
2455 default:
2456 break;
2457 }
2458
2459 // Backup operation-agnostic translation
2460 switch (c2s) {
2461 case C2_BAD_INDEX:
2462 return BAD_INDEX;
2463 case C2_BAD_VALUE:
2464 return BAD_VALUE;
2465 case C2_BLOCKING:
2466 return WOULD_BLOCK;
2467 case C2_DUPLICATE:
2468 return ALREADY_EXISTS;
2469 case C2_NO_INIT:
2470 return NO_INIT;
2471 case C2_NO_MEMORY:
2472 return NO_MEMORY;
2473 case C2_NOT_FOUND:
2474 return NAME_NOT_FOUND;
2475 case C2_TIMED_OUT:
2476 return TIMED_OUT;
2477 case C2_BAD_STATE:
2478 case C2_CANCELED:
2479 case C2_CANNOT_DO:
2480 case C2_CORRUPTED:
2481 case C2_OMITTED:
2482 case C2_REFUSED:
2483 return UNKNOWN_ERROR;
2484 default:
2485 return -static_cast<status_t>(c2s);
2486 }
2487}
2488
Pawin Vongmasa36653902018-11-15 00:10:25 -08002489} // namespace android