blob: 51082d14a905cd17113fdc1797a31f9c6bf845f3 [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright 2017, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010018#include <utils/Errors.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080019#define LOG_TAG "CCodecBufferChannel"
My Name6bd9a7d2022-03-25 12:37:58 -070020#define ATRACE_TAG ATRACE_TAG_VIDEO
Pawin Vongmasa36653902018-11-15 00:10:25 -080021#include <utils/Log.h>
My Name6bd9a7d2022-03-25 12:37:58 -070022#include <utils/Trace.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080023
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070024#include <algorithm>
Wonsik Kim6b2c8be2021-09-28 05:11:04 -070025#include <atomic>
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070026#include <list>
Pawin Vongmasa36653902018-11-15 00:10:25 -080027#include <numeric>
28
29#include <C2AllocatorGralloc.h>
30#include <C2PlatformSupport.h>
31#include <C2BlockInternal.h>
32#include <C2Config.h>
33#include <C2Debug.h>
34
35#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070036#include <android/hardware/drm/1.0/types.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070037#include <android-base/parseint.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080038#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080039#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080040#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080041#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070042#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080043#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070044#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080045#include <media/openmax/OMX_Core.h>
46#include <media/stagefright/foundation/ABuffer.h>
47#include <media/stagefright/foundation/ALookup.h>
48#include <media/stagefright/foundation/AMessage.h>
49#include <media/stagefright/foundation/AUtils.h>
50#include <media/stagefright/foundation/hexdump.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080051#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070052#include <media/stagefright/SkipCutBuffer.h>
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010053#include <media/stagefright/SurfaceUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080054#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070055#include <mediadrm/ICrypto.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070056#include <server_configurable_flags/get_flags.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080057#include <system/window.h>
58
59#include "CCodecBufferChannel.h"
60#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080061
62namespace android {
63
64using android::base::StringPrintf;
65using hardware::hidl_handle;
66using hardware::hidl_string;
67using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070068using hardware::fromHeap;
69using hardware::HidlMemory;
70
Pawin Vongmasa36653902018-11-15 00:10:25 -080071using namespace hardware::cas::V1_0;
72using namespace hardware::cas::native::V1_0;
73
74using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070075using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080076
Pawin Vongmasa36653902018-11-15 00:10:25 -080077namespace {
78
Wonsik Kim469c8342019-04-11 16:46:09 -070079constexpr size_t kSmoothnessFactor = 4;
Pawin Vongmasa36653902018-11-15 00:10:25 -080080
Sungtak Leeab6f2f32019-02-15 14:43:51 -080081// This is for keeping IGBP's buffer dropping logic in legacy mode other
82// than making it non-blocking. Do not change this value.
83const static size_t kDequeueTimeoutNs = 0;
84
Pawin Vongmasa36653902018-11-15 00:10:25 -080085} // namespace
86
87CCodecBufferChannel::QueueGuard::QueueGuard(
88 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
89 Mutex::Autolock l(mSync.mGuardLock);
90 // At this point it's guaranteed that mSync is not under state transition,
91 // as we are holding its mutex.
92
93 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
94 if (count->value == -1) {
95 mRunning = false;
96 } else {
97 ++count->value;
98 mRunning = true;
99 }
100}
101
102CCodecBufferChannel::QueueGuard::~QueueGuard() {
103 if (mRunning) {
104 // We are not holding mGuardLock at this point so that QueueSync::stop() can
105 // keep holding the lock until mCount reaches zero.
106 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
107 --count->value;
108 count->cond.broadcast();
109 }
110}
111
112void CCodecBufferChannel::QueueSync::start() {
113 Mutex::Autolock l(mGuardLock);
114 // If stopped, it goes to running state; otherwise no-op.
115 Mutexed<Counter>::Locked count(mCount);
116 if (count->value == -1) {
117 count->value = 0;
118 }
119}
120
121void CCodecBufferChannel::QueueSync::stop() {
122 Mutex::Autolock l(mGuardLock);
123 Mutexed<Counter>::Locked count(mCount);
124 if (count->value == -1) {
125 // no-op
126 return;
127 }
128 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
129 // mCount can only decrement. In other words, threads that acquired the lock
130 // are allowed to finish execution but additional threads trying to acquire
131 // the lock at this point will block, and then get QueueGuard at STOPPED
132 // state.
133 while (count->value != 0) {
134 count.waitForCondition(count->cond);
135 }
136 count->value = -1;
137}
138
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700139// Input
140
141CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
142
Pawin Vongmasa36653902018-11-15 00:10:25 -0800143// CCodecBufferChannel
144
145CCodecBufferChannel::CCodecBufferChannel(
146 const std::shared_ptr<CCodecCallback> &callback)
147 : mHeapSeqNum(-1),
148 mCCodecCallback(callback),
149 mFrameIndex(0u),
150 mFirstValidFrameIndex(0u),
Brian Lindahl2048d492023-04-05 08:49:23 -0600151 mIsSurfaceToDisplay(false),
152 mHasPresentFenceTimes(false),
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700153 mRenderingDepth(3u),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800154 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700155 mInputMetEos(false),
156 mSendEncryptedInfoBuffer(false) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700157 {
158 Mutexed<Input>::Locked input(mInput);
159 input->buffers.reset(new DummyInputBuffers(""));
160 input->extraBuffers.flush();
161 input->inputDelay = 0u;
162 input->pipelineDelay = 0u;
163 input->numSlots = kSmoothnessFactor;
164 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700165 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700166 }
167 {
168 Mutexed<Output>::Locked output(mOutput);
169 output->outputDelay = 0u;
170 output->numSlots = kSmoothnessFactor;
Wonsik Kim3722abc2023-05-17 13:26:31 -0700171 output->bounded = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700172 }
David Stevensc3fbb282021-01-18 18:11:20 +0900173 {
174 Mutexed<BlockPools>::Locked pools(mBlockPools);
175 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
176 }
Wonsik Kim3a692e62023-05-19 15:37:22 -0700177 std::string value = server_configurable_flags::GetServerConfigurableFlag(
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700178 "media_native", "ccodec_rendering_depth", "3");
Wonsik Kim3a692e62023-05-19 15:37:22 -0700179 android::base::ParseInt(value, &mRenderingDepth);
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700180 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800181}
182
183CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800184 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800185 mCrypto->unsetHeap(mHeapSeqNum);
186 }
187}
188
189void CCodecBufferChannel::setComponent(
190 const std::shared_ptr<Codec2Client::Component> &component) {
191 mComponent = component;
192 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
193 mName = mComponentName.c_str();
194}
195
196status_t CCodecBufferChannel::setInputSurface(
197 const std::shared_ptr<InputSurfaceWrapper> &surface) {
198 ALOGV("[%s] setInputSurface", mName);
199 mInputSurface = surface;
200 return mInputSurface->connect(mComponent);
201}
202
203status_t CCodecBufferChannel::signalEndOfInputStream() {
204 if (mInputSurface == nullptr) {
205 return INVALID_OPERATION;
206 }
207 return mInputSurface->signalEndOfInputStream();
208}
209
Sungtak Lee04b30352020-07-27 13:57:25 -0700210status_t CCodecBufferChannel::queueInputBufferInternal(
211 sp<MediaCodecBuffer> buffer,
212 std::shared_ptr<C2LinearBlock> encryptedBlock,
213 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800214 int64_t timeUs;
215 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
216
217 if (mInputMetEos) {
218 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
219 return OK;
220 }
221
222 int32_t flags = 0;
223 int32_t tmp = 0;
224 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200225 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800226 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
227 eos = true;
228 mInputMetEos = true;
229 ALOGV("[%s] input EOS", mName);
230 }
231 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
232 flags |= C2FrameData::FLAG_CODEC_CONFIG;
233 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200234 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
235 tunnelFirstFrame = true;
236 }
Marc Kassis96343b42022-12-09 11:49:44 +0100237 if (buffer->meta()->findInt32("decode-only", &tmp) && tmp) {
238 flags |= C2FrameData::FLAG_DROP_FRAME;
239 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800240 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800241 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800242 std::unique_ptr<C2Work> work(new C2Work);
243 work->input.ordinal.timestamp = timeUs;
244 work->input.ordinal.frameIndex = mFrameIndex++;
245 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
246 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
247 // Keep client timestamp in customOrdinal
248 work->input.ordinal.customOrdinal = timeUs;
249 work->input.buffers.clear();
250
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700251 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800252 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800253
Pawin Vongmasa36653902018-11-15 00:10:25 -0800254 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700255 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800256 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700257 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800258 return -ENOENT;
259 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700260 // TODO: we want to delay copying buffers.
261 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
262 copy = input->buffers->cloneAndReleaseBuffer(buffer);
263 if (copy != nullptr) {
264 (void)input->extraBuffers.assignSlot(copy);
265 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
266 return UNKNOWN_ERROR;
267 }
268 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
269 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
270 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700271 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700272 } else {
273 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
274 "buffer starvation on component.", mName);
275 }
276 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800277 if (input->frameReassembler) {
278 usesFrameReassembler = true;
279 input->frameReassembler.process(buffer, &items);
280 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900281 int32_t cvo = 0;
282 if (buffer->meta()->findInt32("cvo", &cvo)) {
283 int32_t rotation = cvo % 360;
284 // change rotation to counter-clock wise.
285 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
286
287 Mutexed<OutputSurface>::Locked output(mOutputSurface);
288 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
289 output->rotation[frameIndex] = rotation;
290 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800291 work->input.buffers.push_back(c2buffer);
292 if (encryptedBlock) {
293 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
294 kParamIndexEncryptedBuffer,
295 encryptedBlock->share(0, blockSize, C2Fence())));
296 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700297 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800298 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700299 Mutexed<Input>::Locked input(mInput);
300 if (input->frameReassembler) {
301 usesFrameReassembler = true;
302 // drain any pending items with eos
303 input->frameReassembler.process(buffer, &items);
304 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800305 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800306 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800307 if (usesFrameReassembler) {
308 if (!items.empty()) {
309 items.front()->input.configUpdate = std::move(mParamsToBeSet);
310 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
311 }
312 } else {
313 work->input.flags = (C2FrameData::flags_t)flags;
314 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800315
Wonsik Kime1104ca2020-11-24 15:01:33 -0800316 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200317 if (tunnelFirstFrame) {
318 C2StreamTunnelHoldRender::input tunnelHoldRender{
319 0u /* stream */,
320 C2_TRUE /* value */
321 };
322 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
323 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800324 work->worklets.clear();
325 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800326
Wonsik Kime1104ca2020-11-24 15:01:33 -0800327 items.push_back(std::move(work));
328
329 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800330 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800331 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800332 work.reset(new C2Work);
333 work->input.ordinal.timestamp = timeUs;
334 work->input.ordinal.frameIndex = mFrameIndex++;
335 // WORKAROUND: keep client timestamp in customOrdinal
336 work->input.ordinal.customOrdinal = timeUs;
337 work->input.buffers.clear();
338 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800339 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800340 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800341 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800342 c2_status_t err = C2_OK;
343 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700344 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
345 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800346 {
347 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
348 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
349 for (const std::unique_ptr<C2Work> &work : items) {
350 watcher->onWorkQueued(
351 work->input.ordinal.frameIndex.peeku(),
352 std::vector(work->input.buffers),
353 now);
354 }
355 }
356 err = mComponent->queue(&items);
357 }
358 if (err != C2_OK) {
359 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
360 for (const std::unique_ptr<C2Work> &work : items) {
361 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
362 }
363 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700364 Mutexed<Input>::Locked input(mInput);
365 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700366 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700367 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700368 } else if (buffer) {
369 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700370 }
371 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
372 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800373 }
374
375 feedInputBufferIfAvailableInternal();
376 return err;
377}
378
379status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
380 QueueGuard guard(mSync);
381 if (!guard.isRunning()) {
382 ALOGD("[%s] setParameters is only supported in the running state.", mName);
383 return -ENOSYS;
384 }
385 mParamsToBeSet.insert(mParamsToBeSet.end(),
386 std::make_move_iterator(params.begin()),
387 std::make_move_iterator(params.end()));
388 params.clear();
389 return OK;
390}
391
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800392status_t CCodecBufferChannel::attachBuffer(
393 const std::shared_ptr<C2Buffer> &c2Buffer,
394 const sp<MediaCodecBuffer> &buffer) {
395 if (!buffer->copy(c2Buffer)) {
396 return -ENOSYS;
397 }
398 return OK;
399}
400
401void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
402 if (!mDecryptDestination || mDecryptDestination->size() < size) {
403 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
404 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
405 mCrypto->unsetHeap(mHeapSeqNum);
406 }
407 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
408 if (mCrypto) {
409 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
410 }
411 }
412}
413
414int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
415 CHECK(mCrypto);
416 auto it = mHeapSeqNumMap.find(memory);
417 int32_t heapSeqNum = -1;
418 if (it == mHeapSeqNumMap.end()) {
419 heapSeqNum = mCrypto->setHeap(memory);
420 mHeapSeqNumMap.emplace(memory, heapSeqNum);
421 } else {
422 heapSeqNum = it->second;
423 }
424 return heapSeqNum;
425}
426
427status_t CCodecBufferChannel::attachEncryptedBuffer(
428 const sp<hardware::HidlMemory> &memory,
429 bool secure,
430 const uint8_t *key,
431 const uint8_t *iv,
432 CryptoPlugin::Mode mode,
433 CryptoPlugin::Pattern pattern,
434 size_t offset,
435 const CryptoPlugin::SubSample *subSamples,
436 size_t numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000437 const sp<MediaCodecBuffer> &buffer,
438 AString* errorDetailMsg) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800439 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
440 static const C2MemoryUsage kDefaultReadWriteUsage{
441 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
442
443 size_t size = 0;
444 for (size_t i = 0; i < numSubSamples; ++i) {
445 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
446 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700447 if (size == 0) {
448 buffer->setRange(0, 0);
449 return OK;
450 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800451 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
452 std::shared_ptr<C2LinearBlock> block;
453 c2_status_t err = pool->fetchLinearBlock(
454 size,
455 secure ? kSecureUsage : kDefaultReadWriteUsage,
456 &block);
457 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700458 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
459 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800460 return NO_MEMORY;
461 }
462 if (!secure) {
463 ensureDecryptDestination(size);
464 }
465 ssize_t result = -1;
466 ssize_t codecDataOffset = 0;
467 if (mCrypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800468 int32_t heapSeqNum = getHeapSeqNum(memory);
469 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
470 hardware::drm::V1_0::DestinationBuffer dst;
471 if (secure) {
472 dst.type = DrmBufferType::NATIVE_HANDLE;
473 dst.secureMemory = hardware::hidl_handle(block->handle());
474 } else {
475 dst.type = DrmBufferType::SHARED_MEMORY;
476 IMemoryToSharedBuffer(
477 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
478 }
479 result = mCrypto->decrypt(
480 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000481 dst, errorDetailMsg);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800482 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700483 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800484 return result;
485 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800486 } else {
487 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
488 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
489 hidl_vec<SubSample> hidlSubSamples;
490 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
491
492 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
493 hardware::cas::native::V1_0::DestinationBuffer dst;
494 if (secure) {
495 dst.type = BufferType::NATIVE_HANDLE;
496 dst.secureMemory = hardware::hidl_handle(block->handle());
497 } else {
498 dst.type = BufferType::SHARED_MEMORY;
499 dst.nonsecureMemory = src;
500 }
501
502 CasStatus status = CasStatus::OK;
503 hidl_string detailedError;
504 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
505
506 if (key != nullptr) {
507 sctrl = (ScramblingControl)key[0];
508 // Adjust for the PES offset
509 codecDataOffset = key[2] | (key[3] << 8);
510 }
511
512 auto returnVoid = mDescrambler->descramble(
513 sctrl,
514 hidlSubSamples,
515 src,
516 0,
517 dst,
518 0,
519 [&status, &result, &detailedError] (
520 CasStatus _status, uint32_t _bytesWritten,
521 const hidl_string& _detailedError) {
522 status = _status;
523 result = (ssize_t)_bytesWritten;
524 detailedError = _detailedError;
525 });
Arun Johnson634d0802023-02-14 22:07:51 +0000526 if (errorDetailMsg) {
527 errorDetailMsg->setTo(detailedError.c_str(), detailedError.size());
528 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800529 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
530 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
531 mName, returnVoid.description().c_str(), status, result);
532 return UNKNOWN_ERROR;
533 }
534
535 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700536 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
537 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800538 return BAD_VALUE;
539 }
540 }
541 if (!secure) {
542 C2WriteView view = block->map().get();
543 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700544 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
545 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800546 return UNKNOWN_ERROR;
547 }
548 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700549 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
550 "(non-secure)",
551 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800552 return UNKNOWN_ERROR;
553 }
554 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
555 }
556 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
557 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
558 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700559 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800560 return -ENOSYS;
561 }
562 return OK;
563}
564
Pawin Vongmasa36653902018-11-15 00:10:25 -0800565status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
566 QueueGuard guard(mSync);
567 if (!guard.isRunning()) {
568 ALOGD("[%s] No more buffers should be queued at current state.", mName);
569 return -ENOSYS;
570 }
571 return queueInputBufferInternal(buffer);
572}
573
574status_t CCodecBufferChannel::queueSecureInputBuffer(
575 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
576 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
577 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
578 AString *errorDetailMsg) {
579 QueueGuard guard(mSync);
580 if (!guard.isRunning()) {
581 ALOGD("[%s] No more buffers should be queued at current state.", mName);
582 return -ENOSYS;
583 }
584
585 if (!hasCryptoOrDescrambler()) {
586 return -ENOSYS;
587 }
588 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
589
Sungtak Lee04b30352020-07-27 13:57:25 -0700590 std::shared_ptr<C2LinearBlock> block;
591 size_t allocSize = buffer->size();
592 size_t bufferSize = 0;
593 c2_status_t blockRes = C2_OK;
594 bool copied = false;
595 if (mSendEncryptedInfoBuffer) {
596 static const C2MemoryUsage kDefaultReadWriteUsage{
597 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
598 constexpr int kAllocGranule0 = 1024 * 64;
599 constexpr int kAllocGranule1 = 1024 * 1024;
600 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
601 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
602 if (allocSize <= kAllocGranule1) {
603 bufferSize = align(allocSize, kAllocGranule0);
604 } else {
605 bufferSize = align(allocSize, kAllocGranule1);
606 }
607 blockRes = pool->fetchLinearBlock(
608 bufferSize, kDefaultReadWriteUsage, &block);
609
610 if (blockRes == C2_OK) {
611 C2WriteView view = block->map().get();
612 if (view.error() == C2_OK && view.size() == bufferSize) {
613 copied = true;
614 // TODO: only copy clear sections
615 memcpy(view.data(), buffer->data(), allocSize);
616 }
617 }
618 }
619
620 if (!copied) {
621 block.reset();
622 }
623
Pawin Vongmasa36653902018-11-15 00:10:25 -0800624 ssize_t result = -1;
625 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700626 if (numSubSamples == 1
627 && subSamples[0].mNumBytesOfClearData == 0
628 && subSamples[0].mNumBytesOfEncryptedData == 0) {
629 // We don't need to go through crypto or descrambler if the input is empty.
630 result = 0;
631 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700632 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800633 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700634 destination.type = DrmBufferType::NATIVE_HANDLE;
635 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800636 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700637 destination.type = DrmBufferType::SHARED_MEMORY;
638 IMemoryToSharedBuffer(
639 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800640 }
Robert Shih895fba92019-07-16 16:29:44 -0700641 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800642 encryptedBuffer->fillSourceBuffer(&source);
643 result = mCrypto->decrypt(
644 key, iv, mode, pattern, source, buffer->offset(),
645 subSamples, numSubSamples, destination, errorDetailMsg);
646 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700647 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800648 return result;
649 }
Robert Shih895fba92019-07-16 16:29:44 -0700650 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800651 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
652 }
653 } else {
654 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
655 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
656 hidl_vec<SubSample> hidlSubSamples;
657 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
658
659 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
660 encryptedBuffer->fillSourceBuffer(&srcBuffer);
661
662 DestinationBuffer dstBuffer;
663 if (secure) {
664 dstBuffer.type = BufferType::NATIVE_HANDLE;
665 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
666 } else {
667 dstBuffer.type = BufferType::SHARED_MEMORY;
668 dstBuffer.nonsecureMemory = srcBuffer;
669 }
670
671 CasStatus status = CasStatus::OK;
672 hidl_string detailedError;
673 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
674
675 if (key != nullptr) {
676 sctrl = (ScramblingControl)key[0];
677 // Adjust for the PES offset
678 codecDataOffset = key[2] | (key[3] << 8);
679 }
680
681 auto returnVoid = mDescrambler->descramble(
682 sctrl,
683 hidlSubSamples,
684 srcBuffer,
685 0,
686 dstBuffer,
687 0,
688 [&status, &result, &detailedError] (
689 CasStatus _status, uint32_t _bytesWritten,
690 const hidl_string& _detailedError) {
691 status = _status;
692 result = (ssize_t)_bytesWritten;
693 detailedError = _detailedError;
694 });
695
696 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
697 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
698 mName, returnVoid.description().c_str(), status, result);
699 return UNKNOWN_ERROR;
700 }
701
702 if (result < codecDataOffset) {
703 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
704 return BAD_VALUE;
705 }
706
707 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
708
709 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
710 encryptedBuffer->copyDecryptedContentFromMemory(result);
711 }
712 }
713
714 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700715
716 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800717}
718
719void CCodecBufferChannel::feedInputBufferIfAvailable() {
720 QueueGuard guard(mSync);
721 if (!guard.isRunning()) {
722 ALOGV("[%s] We're not running --- no input buffer reported", mName);
723 return;
724 }
725 feedInputBufferIfAvailableInternal();
726}
727
728void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900729 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800730 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700731 }
732 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700733 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700734 if (!output->buffers ||
735 output->buffers->hasPending() ||
Wonsik Kim3722abc2023-05-17 13:26:31 -0700736 (!output->bounded && output->buffers->numActiveSlots() >= output->numSlots)) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800737 return;
738 }
739 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700740 size_t numActiveSlots = 0;
741 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800742 sp<MediaCodecBuffer> inBuffer;
743 size_t index;
744 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700745 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700746 numActiveSlots = input->buffers->numActiveSlots();
747 if (numActiveSlots >= input->numSlots) {
748 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800749 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700750 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800751 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800752 break;
753 }
754 }
755 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
756 mCallback->onInputBufferAvailable(index, inBuffer);
757 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700758 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759}
760
761status_t CCodecBufferChannel::renderOutputBuffer(
762 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800763 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800764 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800765 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800766 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700767 Mutexed<Output>::Locked output(mOutput);
768 if (output->buffers) {
769 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800770 }
771 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800772 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
773 // set to true.
774 sendOutputBuffers();
775 // input buffer feeding may have been gated by pending output buffers
776 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800777 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800778 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700779 std::call_once(mRenderWarningFlag, [this] {
780 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
781 "timestamp or render=true with non-video buffers. Apps should "
782 "call releaseOutputBuffer() with render=false for those.",
783 mName);
784 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800785 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800786 return INVALID_OPERATION;
787 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800788
789#if 0
790 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
791 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
792 for (const std::shared_ptr<const C2Info> &info : infoParams) {
793 AString res;
794 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
795 if (ix) res.append(", ");
796 res.append(*((int32_t*)info.get() + (ix / 4)));
797 }
798 ALOGV(" [%s]", res.c_str());
799 }
800#endif
801 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
802 std::static_pointer_cast<const C2StreamRotationInfo::output>(
803 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
804 bool flip = rotation && (rotation->flip & 1);
805 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900806
807 {
808 Mutexed<OutputSurface>::Locked output(mOutputSurface);
809 if (output->surface == nullptr) {
810 ALOGI("[%s] cannot render buffer without surface", mName);
811 return OK;
812 }
813 int64_t frameIndex;
814 buffer->meta()->findInt64("frameIndex", &frameIndex);
815 if (output->rotation.count(frameIndex) != 0) {
816 auto it = output->rotation.find(frameIndex);
817 quarters = (it->second / 90) & 3;
818 output->rotation.erase(it);
819 }
820 }
821
Pawin Vongmasa36653902018-11-15 00:10:25 -0800822 uint32_t transform = 0;
823 switch (quarters) {
824 case 0: // no rotation
825 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
826 break;
827 case 1: // 90 degrees counter-clockwise
828 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
829 : HAL_TRANSFORM_ROT_270;
830 break;
831 case 2: // 180 degrees
832 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
833 break;
834 case 3: // 90 degrees clockwise
835 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
836 : HAL_TRANSFORM_ROT_90;
837 break;
838 }
839
840 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
841 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
842 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
843 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
844 if (surfaceScaling) {
845 videoScalingMode = surfaceScaling->value;
846 }
847
848 // Use dataspace from format as it has the default aspects already applied
849 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
850 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
851
852 // HDR static info
853 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
854 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
855 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
856
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800857 // HDR10 plus info
858 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
859 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
860 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800861 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
862 hdr10PlusInfo.reset();
863 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800864
Wonsik Kima79c5522022-01-18 16:29:24 -0800865 // HDR dynamic info
866 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
867 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
868 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
869 // TODO: make this sticky & enable unset
870 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
871 hdrDynamicInfo.reset();
872 }
873
874 if (hdr10PlusInfo) {
875 // C2StreamHdr10PlusInfo is deprecated; components should use
876 // C2StreamHdrDynamicMetadataInfo
877 // TODO: #metric
878 if (hdrDynamicInfo) {
879 // It is unexpected that C2StreamHdr10PlusInfo and
880 // C2StreamHdrDynamicMetadataInfo is both present.
881 // C2StreamHdrDynamicMetadataInfo takes priority.
882 // TODO: #metric
883 } else {
884 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
885 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
886 hdr10PlusInfo->flexCount(),
887 0u,
888 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
889 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
890 hdrDynamicInfo = info;
891 }
892 }
893
Pawin Vongmasa36653902018-11-15 00:10:25 -0800894 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
895 if (blocks.size() != 1u) {
896 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
897 return UNKNOWN_ERROR;
898 }
899 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700900 C2Fence c2fence = block.fence();
901 sp<Fence> fence = Fence::NO_FENCE;
902 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
903 // Once C2Fence::type() is added, check the exact C2Fence type
904 if (c2fence.isHW()) {
905 int fenceFd = c2fence.fd();
906 fence = sp<Fence>::make(fenceFd);
907 if (!fence) {
908 ALOGE("[%s] Failed to allocate a fence", mName);
909 close(fenceFd);
910 return NO_MEMORY;
911 }
912 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800913
914 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -0700915 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800916 timestampNs,
917 false, // droppable
918 dataSpace,
919 Rect(blocks.front().crop().left,
920 blocks.front().crop().top,
921 blocks.front().crop().right(),
922 blocks.front().crop().bottom()),
923 videoScalingMode,
924 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700925 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800926 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800927 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800928 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800929 // If mastering max and min luminance fields are 0, do not use them.
930 // It indicates the value may not be present in the stream.
931 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
932 hdrStaticInfo->mastering.minLuminance > 0.0f) {
933 struct android_smpte2086_metadata smpte2086_meta = {
934 .displayPrimaryRed = {
935 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
936 },
937 .displayPrimaryGreen = {
938 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
939 },
940 .displayPrimaryBlue = {
941 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
942 },
943 .whitePoint = {
944 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
945 },
946 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
947 .minLuminance = hdrStaticInfo->mastering.minLuminance,
948 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800949 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800950 hdr.smpte2086 = smpte2086_meta;
951 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700952 // If the content light level fields are 0, do not use them, it
953 // indicates the value may not be present in the stream.
954 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
955 struct android_cta861_3_metadata cta861_meta = {
956 .maxContentLightLevel = hdrStaticInfo->maxCll,
957 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
958 };
959 hdr.validTypes |= HdrMetadata::CTA861_3;
960 hdr.cta8613 = cta861_meta;
961 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900962
963 // does not have valid info
964 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
965 hdrStaticInfo.reset();
966 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800967 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800968 if (hdrDynamicInfo
969 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800970 hdr.validTypes |= HdrMetadata::HDR10PLUS;
971 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800972 hdrDynamicInfo->m.data,
973 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800974 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800975 qbi.setHdrMetadata(hdr);
976 }
Hongguangfc1478a2022-07-20 22:56:06 -0700977 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
978
Brian Lindahl932bf602023-03-09 11:59:48 -0700979 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
980 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
981 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800982 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
983 if (result != OK) {
984 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800985 if (result == NO_INIT) {
986 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
987 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800988 return result;
989 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800990
991 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
992 ALOGD("[%s] queue buffer successful", mName);
993 } else {
994 ALOGV("[%s] queue buffer successful", mName);
995 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800996
997 int64_t mediaTimeUs = 0;
998 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahl2048d492023-04-05 08:49:23 -0600999 if (mIsSurfaceToDisplay) {
1000 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
1001 processRenderedFrames(qbo.frameTimestamps);
1002 } else {
1003 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
1004 // when the frame is queued to the non-display surface
1005 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1006 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001007
1008 return OK;
1009}
1010
Brian Lindahl932bf602023-03-09 11:59:48 -07001011void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001012 mTrackedFrames.clear();
1013
1014 int isSurfaceToDisplay = 0;
1015 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1016 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1017 // No frame tracking is needed if we're not sending frames to the display
1018 if (!mIsSurfaceToDisplay) {
1019 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1020 return;
1021 }
1022
Brian Lindahl932bf602023-03-09 11:59:48 -07001023 int hasPresentFenceTimes = 0;
1024 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1025 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
Brian Lindahl119e0c22023-05-19 15:42:13 -06001026 if (!mHasPresentFenceTimes) {
Brian Lindahl932bf602023-03-09 11:59:48 -07001027 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1028 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001029}
1030
1031void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1032 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1033 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1034 // so track the frame as if the desired render time is now.
1035 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1036 if (desiredRenderTimeNs < nowNs) {
1037 desiredRenderTimeNs = nowNs;
1038 }
1039 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1040 // actually rendered.
1041 TrackedFrame frame;
1042 frame.number = qbo.nextFrameNumber - 1;
1043 frame.mediaTimeUs = mediaTimeUs;
1044 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1045 frame.latchTime = -1;
1046 frame.presentFence = nullptr;
1047 mTrackedFrames.push_back(frame);
1048}
1049
1050void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1051 // Grab the latch times and present fences from the frame event deltas
1052 for (const auto& delta : deltas) {
1053 for (auto& frame : mTrackedFrames) {
1054 if (delta.getFrameNumber() == frame.number) {
1055 delta.getLatchTime(&frame.latchTime);
1056 delta.getDisplayPresentFence(&frame.presentFence);
1057 }
1058 }
1059 }
1060
1061 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1062 // in fact, been rendered.
1063 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1064 while (!mTrackedFrames.empty()) {
1065 TrackedFrame & frame = mTrackedFrames.front();
1066 // Frames that should have been rendered at least 100ms in the past are checked
1067 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1068 break;
1069 }
1070
1071 // If we don't have a render time by now, then consider the frame as dropped
1072 int64_t renderTimeNs = getRenderTimeNs(frame);
1073 if (renderTimeNs != -1) {
1074 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1075 }
1076 mTrackedFrames.pop_front();
1077 }
1078}
1079
1080int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1081 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1082 if (!mHasPresentFenceTimes) {
1083 if (frame.latchTime == -1) {
1084 ALOGD("no latch time for frame %d", (int) frame.number);
1085 return -1;
1086 }
1087 return frame.latchTime;
1088 }
1089
1090 if (frame.presentFence == nullptr) {
1091 ALOGW("no present fence for frame %d", (int) frame.number);
1092 return -1;
1093 }
1094
1095 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1096
1097 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1098 ALOGW("invalid signal time for frame %d", (int) frame.number);
1099 return -1;
1100 }
1101
1102 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1103 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1104 return -1;
1105 }
1106
1107 return actualRenderTimeNs;
1108}
1109
1110void CCodecBufferChannel::pollForRenderedBuffers() {
1111 FrameEventHistoryDelta delta;
1112 mComponent->pollForRenderedFrames(&delta);
1113 processRenderedFrames(delta);
1114}
1115
Pawin Vongmasa36653902018-11-15 00:10:25 -08001116status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1117 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1118 bool released = false;
1119 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001120 Mutexed<Input>::Locked input(mInput);
1121 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001122 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001123 }
1124 }
1125 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001126 Mutexed<Output>::Locked output(mOutput);
1127 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001128 released = true;
1129 }
1130 }
1131 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001132 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001133 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001134 } else {
1135 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1136 }
1137 return OK;
1138}
1139
1140void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1141 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001142 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001143
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001144 if (!input->buffers) {
1145 ALOGE("getInputBufferArray: No Input Buffers allocated");
1146 return;
1147 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001148 if (!input->buffers->isArrayMode()) {
1149 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001150 }
1151
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001152 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001153}
1154
1155void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1156 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001157 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001158 if (!output->buffers) {
1159 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1160 return;
1161 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001162 if (!output->buffers->isArrayMode()) {
1163 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001164 }
1165
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001166 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001167}
1168
1169status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001170 const sp<AMessage> &inputFormat,
1171 const sp<AMessage> &outputFormat,
1172 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001173 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1174 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001175 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001176 C2PortReorderBufferDepthTuning::output reorderDepth;
1177 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001178 C2PortActualDelayTuning::input inputDelay(0);
1179 C2PortActualDelayTuning::output outputDelay(0);
1180 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001181 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001182
Pawin Vongmasa36653902018-11-15 00:10:25 -08001183 c2_status_t err = mComponent->query(
1184 {
1185 &iStreamFormat,
1186 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001187 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001188 &reorderDepth,
1189 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001190 &inputDelay,
1191 &pipelineDelay,
1192 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001193 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001194 },
1195 {},
1196 C2_DONT_BLOCK,
1197 nullptr);
1198 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001199 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001200 return UNKNOWN_ERROR;
1201 }
1202 } else if (err != C2_OK) {
1203 return UNKNOWN_ERROR;
1204 }
1205
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001206 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1207 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1208 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1209
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001210 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1211 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001212
Pawin Vongmasa36653902018-11-15 00:10:25 -08001213 // TODO: get this from input format
1214 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1215
Sungtak Lee04b30352020-07-27 13:57:25 -07001216 // secure mode is a static parameter (shall not change in the executing state)
1217 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1218
Pawin Vongmasa36653902018-11-15 00:10:25 -08001219 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001220 int poolMask = GetCodec2PoolMask();
1221 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001222
1223 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001224 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001225 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001226 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1227 API_REFLECTION |
1228 API_VALUES |
1229 API_CURRENT_VALUES |
1230 API_DEPENDENCY |
1231 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001232 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1233 C2StreamSampleRateInfo::input sampleRate(0u);
1234 C2StreamChannelCountInfo::input channelCount(0u);
1235 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001236 std::shared_ptr<C2BlockPool> pool;
1237 {
1238 Mutexed<BlockPools>::Locked pools(mBlockPools);
1239
1240 // set default allocator ID.
1241 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001242 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001243
1244 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1245 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1246 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001247 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001248 std::vector<C2Param *> stackParams({&featuresSetting});
1249 if (audioEncoder) {
1250 stackParams.push_back(&encoderFrameSize);
1251 stackParams.push_back(&sampleRate);
1252 stackParams.push_back(&channelCount);
1253 stackParams.push_back(&pcmEncoding);
1254 } else {
1255 encoderFrameSize.invalidate();
1256 sampleRate.invalidate();
1257 channelCount.invalidate();
1258 pcmEncoding.invalidate();
1259 }
1260 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001261 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1262 C2_DONT_BLOCK,
1263 &params);
1264 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1265 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1266 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001267 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001268 C2PortAllocatorsTuning::input *inputAllocators =
1269 C2PortAllocatorsTuning::input::From(params[0].get());
1270 if (inputAllocators && inputAllocators->flexCount() > 0) {
1271 std::shared_ptr<C2Allocator> allocator;
1272 // verify allocator IDs and resolve default allocator
1273 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1274 if (allocator) {
1275 pools->inputAllocatorId = allocator->getId();
1276 } else {
1277 ALOGD("[%s] component requested invalid input allocator ID %u",
1278 mName, inputAllocators->m.values[0]);
1279 }
1280 }
1281 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001282 if (featuresSetting) {
1283 apiFeatures = featuresSetting.value;
1284 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001285
1286 // TODO: use C2Component wrapper to associate this pool with ourselves
1287 if ((poolMask >> pools->inputAllocatorId) & 1) {
1288 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1289 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1290 mName, pools->inputAllocatorId,
1291 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1292 asString(err), err);
1293 } else {
1294 err = C2_NOT_FOUND;
1295 }
1296 if (err != C2_OK) {
1297 C2BlockPool::local_id_t inputPoolId =
1298 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1299 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1300 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1301 mName, (unsigned long long)inputPoolId,
1302 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1303 asString(err), err);
1304 if (err != C2_OK) {
1305 return NO_MEMORY;
1306 }
1307 }
1308 pools->inputPool = pool;
1309 }
1310
Wonsik Kim51051262018-11-28 13:59:05 -08001311 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001312 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001313 input->inputDelay = inputDelayValue;
1314 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001315 input->numSlots = numInputSlots;
1316 input->extraBuffers.flush();
1317 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001318 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001319 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1320 input->frameReassembler.init(
1321 pool,
1322 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1323 encoderFrameSize.value,
1324 sampleRate.value,
1325 channelCount.value,
1326 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1327 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001328 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1329 // For encrypted content, framework decrypts source buffer (ashmem) into
1330 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001331 if (!buffersBoundToCodec
1332 && !input->frameReassembler
1333 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001334 input->buffers.reset(new SlotInputBuffers(mName));
1335 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001336 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001337 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001338 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001339 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001340 // This is to ensure buffers do not get released prematurely.
1341 // TODO: handle this without going into array mode
1342 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001343 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001344 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001345 }
1346 } else {
1347 if (hasCryptoOrDescrambler()) {
1348 int32_t capacity = kLinearBufferSize;
1349 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1350 if ((size_t)capacity > kMaxLinearBufferSize) {
1351 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1352 capacity = kMaxLinearBufferSize;
1353 }
1354 if (mDealer == nullptr) {
1355 mDealer = new MemoryDealer(
1356 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001357 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001358 "EncryptedLinearInputBuffers");
1359 mDecryptDestination = mDealer->allocate((size_t)capacity);
1360 }
1361 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001362 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1363 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001364 } else {
1365 mHeapSeqNum = -1;
1366 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001367 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001368 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001369 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001370 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001371 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001372 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001373 }
1374 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001375 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001376
1377 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001378 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001379 } else {
1380 // TODO: error
1381 }
Wonsik Kim51051262018-11-28 13:59:05 -08001382
1383 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001384 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001385 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001386 }
1387
1388 if (outputFormat != nullptr) {
1389 sp<IGraphicBufferProducer> outputSurface;
1390 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001391 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001392 {
1393 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001394 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001395 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001396 outputSurface = output->surface ?
1397 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001398 if (outputSurface) {
1399 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1400 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001401 outputGeneration = output->generation;
1402 }
1403
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001404 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001405 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001406 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001407
1408 {
1409 Mutexed<BlockPools>::Locked pools(mBlockPools);
1410
David Stevensc3fbb282021-01-18 18:11:20 +09001411 prevOutputPoolId = pools->outputPoolId;
1412
Pawin Vongmasa36653902018-11-15 00:10:25 -08001413 // set default allocator ID.
1414 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001415 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001416
1417 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1418 // unsuccessful.
1419 std::vector<std::unique_ptr<C2Param>> params;
1420 err = mComponent->query({ },
1421 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1422 C2_DONT_BLOCK,
1423 &params);
1424 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1425 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1426 mName, params.size(), asString(err), err);
1427 } else if (err == C2_OK && params.size() == 1) {
1428 C2PortAllocatorsTuning::output *outputAllocators =
1429 C2PortAllocatorsTuning::output::From(params[0].get());
1430 if (outputAllocators && outputAllocators->flexCount() > 0) {
1431 std::shared_ptr<C2Allocator> allocator;
1432 // verify allocator IDs and resolve default allocator
1433 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1434 if (allocator) {
1435 pools->outputAllocatorId = allocator->getId();
1436 } else {
1437 ALOGD("[%s] component requested invalid output allocator ID %u",
1438 mName, outputAllocators->m.values[0]);
1439 }
1440 }
1441 }
1442
1443 // use bufferqueue if outputting to a surface.
1444 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1445 // if unsuccessful.
1446 if (outputSurface) {
1447 params.clear();
1448 err = mComponent->query({ },
1449 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1450 C2_DONT_BLOCK,
1451 &params);
1452 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1453 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1454 mName, params.size(), asString(err), err);
1455 } else if (err == C2_OK && params.size() == 1) {
1456 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1457 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1458 if (surfaceAllocator) {
1459 std::shared_ptr<C2Allocator> allocator;
1460 // verify allocator IDs and resolve default allocator
1461 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1462 if (allocator) {
1463 pools->outputAllocatorId = allocator->getId();
1464 } else {
1465 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1466 mName, surfaceAllocator->value);
1467 err = C2_BAD_VALUE;
1468 }
1469 }
1470 }
1471 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1472 && err != C2_OK
1473 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1474 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1475 }
1476 }
1477
1478 if ((poolMask >> pools->outputAllocatorId) & 1) {
1479 err = mComponent->createBlockPool(
1480 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1481 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1482 mName, pools->outputAllocatorId,
1483 (unsigned long long)pools->outputPoolId,
1484 asString(err));
1485 } else {
1486 err = C2_NOT_FOUND;
1487 }
1488 if (err != C2_OK) {
1489 // use basic pool instead
1490 pools->outputPoolId =
1491 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1492 }
1493
1494 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1495 // component.
1496 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1497 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1498
1499 std::vector<std::unique_ptr<C2SettingResult>> failures;
1500 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1501 ALOGD("[%s] Configured output block pool ids %llu => %s",
1502 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1503 outputPoolId_ = pools->outputPoolId;
1504 }
1505
David Stevensc3fbb282021-01-18 18:11:20 +09001506 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1507 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1508 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1509 if (err != C2_OK) {
1510 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1511 (unsigned long long) prevOutputPoolId, asString(err), err);
1512 }
1513 }
1514
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001515 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001516 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001517 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001518 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001519 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001520 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001521 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001522 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001523 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001524 }
1525 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001526 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001527 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001528 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001529
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001530 output->buffers->clearStash();
1531 if (reorderDepth) {
1532 output->buffers->setReorderDepth(reorderDepth.value);
1533 }
1534 if (reorderKey) {
1535 output->buffers->setReorderKey(reorderKey.value);
1536 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001537
1538 // Try to set output surface to created block pool if given.
1539 if (outputSurface) {
1540 mComponent->setOutputSurface(
1541 outputPoolId_,
1542 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001543 outputGeneration,
1544 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001545 } else {
1546 // configure CPU read consumer usage
1547 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1548 std::vector<std::unique_ptr<C2SettingResult>> failures;
1549 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1550 // do not print error message for now as most components may not yet
1551 // support this setting
1552 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1553 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001554 }
1555
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001556 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001557 if (buffersBoundToCodec) {
1558 // WORKAROUND: if we're using early CSD workaround we convert to
1559 // array mode, to appease apps assuming the output
1560 // buffers to be of the same size.
1561 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1562 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001563
1564 int32_t channelCount;
1565 int32_t sampleRate;
1566 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1567 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1568 int32_t delay = 0;
1569 int32_t padding = 0;;
1570 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1571 delay = 0;
1572 }
1573 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1574 padding = 0;
1575 }
1576 if (delay || padding) {
1577 // We need write access to the buffers, and we're already in
1578 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001579 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001580 }
1581 }
1582 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001583
1584 int32_t tunneled = 0;
1585 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1586 tunneled = 0;
1587 }
1588 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001589 }
1590
1591 // Set up pipeline control. This has to be done after mInputBuffers and
1592 // mOutputBuffers are initialized to make sure that lingering callbacks
1593 // about buffers from the previous generation do not interfere with the
1594 // newly initialized pipeline capacity.
1595
Wonsik Kim62545252021-01-20 11:25:41 -08001596 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001597 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001598 watcher->inputDelay(inputDelayValue)
1599 .pipelineDelay(pipelineDelayValue)
1600 .outputDelay(outputDelayValue)
Houxiang Dai0b573282023-03-11 18:31:56 +08001601 .smoothnessFactor(kSmoothnessFactor)
1602 .tunneled(mTunneled);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001603 watcher->flush();
1604 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001605
1606 mInputMetEos = false;
1607 mSync.start();
1608 return OK;
1609}
1610
Wonsik Kim34b28b42022-05-20 15:49:32 -07001611status_t CCodecBufferChannel::prepareInitialInputBuffers(
1612 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001613 if (mInputSurface) {
1614 return OK;
1615 }
1616
Wonsik Kim34b28b42022-05-20 15:49:32 -07001617 size_t numInputSlots = mInput.lock()->numSlots;
1618
1619 {
1620 Mutexed<Input>::Locked input(mInput);
1621 while (clientInputBuffers->size() < numInputSlots) {
1622 size_t index;
1623 sp<MediaCodecBuffer> buffer;
1624 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1625 break;
1626 }
1627 clientInputBuffers->emplace(index, buffer);
1628 }
1629 }
1630 if (clientInputBuffers->empty()) {
1631 ALOGW("[%s] start: cannot allocate memory at all", mName);
1632 return NO_MEMORY;
1633 } else if (clientInputBuffers->size() < numInputSlots) {
1634 ALOGD("[%s] start: cannot allocate memory for all slots, "
1635 "only %zu buffers allocated",
1636 mName, clientInputBuffers->size());
1637 } else {
1638 ALOGV("[%s] %zu initial input buffers available",
1639 mName, clientInputBuffers->size());
1640 }
1641 return OK;
1642}
1643
1644status_t CCodecBufferChannel::requestInitialInputBuffers(
1645 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001646 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001647 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1648 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1649 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001650 return UNKNOWN_ERROR;
1651 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001652
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001653 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1654 mFlushedConfigs.lock()->swap(flushedConfigs);
1655 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001656 {
1657 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1658 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1659 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1660 watcher->onWorkQueued(
1661 work->input.ordinal.frameIndex.peeku(),
1662 std::vector(work->input.buffers),
1663 now);
1664 }
1665 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001666 err = mComponent->queue(&flushedConfigs);
1667 if (err != C2_OK) {
1668 ALOGW("[%s] Error while queueing a flushed config", mName);
1669 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001670 }
1671 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001672 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001673 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1674 !clientInputBuffers.empty()) {
1675 size_t minIndex = clientInputBuffers.begin()->first;
1676 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1677 for (const auto &[index, buffer] : clientInputBuffers) {
1678 if (minBuffer->capacity() > buffer->capacity()) {
1679 minIndex = index;
1680 minBuffer = buffer;
1681 }
1682 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001683 // WORKAROUND: Some apps expect CSD available without queueing
1684 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001685 minBuffer->setRange(0, 0);
1686 minBuffer->meta()->clear();
1687 minBuffer->meta()->setInt64("timeUs", 0);
1688 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001689 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1690 mName);
1691 return UNKNOWN_ERROR;
1692 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001693 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001694 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001695
Wonsik Kim34b28b42022-05-20 15:49:32 -07001696 for (const auto &[index, buffer] : clientInputBuffers) {
1697 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001698 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001699
Pawin Vongmasa36653902018-11-15 00:10:25 -08001700 return OK;
1701}
1702
1703void CCodecBufferChannel::stop() {
1704 mSync.stop();
1705 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001706}
1707
Sungtak Lee99144332023-01-26 11:03:14 +00001708void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
1709 sp<Surface> surface = mOutputSurface.lock()->surface;
1710 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00001711 C2BlockPool::local_id_t outputPoolId;
1712 {
1713 Mutexed<BlockPools>::Locked pools(mBlockPools);
1714 outputPoolId = pools->outputPoolId;
1715 }
1716 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00001717
1718 if (pushBlankBuffer) {
1719 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
1720 if (anw) {
1721 pushBlankBuffersToNativeWindow(anw.get());
1722 }
1723 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00001724 }
1725}
1726
Wonsik Kim936a89c2020-05-08 16:07:50 -07001727void CCodecBufferChannel::reset() {
1728 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001729 if (mInputSurface != nullptr) {
1730 mInputSurface.reset();
1731 }
1732 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001733 {
1734 Mutexed<Input>::Locked input(mInput);
1735 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001736 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001737 }
1738 {
1739 Mutexed<Output>::Locked output(mOutput);
1740 output->buffers.reset();
1741 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001742 // reset the frames that are being tracked for onFrameRendered callbacks
1743 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001744}
1745
1746void CCodecBufferChannel::release() {
1747 mComponent.reset();
1748 mInputAllocator.reset();
1749 mOutputSurface.lock()->surface.clear();
1750 {
1751 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1752 blockPools->inputPool.reset();
1753 blockPools->outputPoolIntf.reset();
1754 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001755 setCrypto(nullptr);
1756 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001757}
1758
Pawin Vongmasa36653902018-11-15 00:10:25 -08001759void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1760 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001761 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001762 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001763 {
1764 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1765 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1766 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1767 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1768 watcher->onWorkDone(frameIndex);
1769 continue;
1770 }
1771 if (work->input.buffers.empty()
1772 || work->input.buffers.front() == nullptr
1773 || work->input.buffers.front()->data().linearBlocks().empty()) {
1774 ALOGD("[%s] no linear codec config data found", mName);
1775 watcher->onWorkDone(frameIndex);
1776 continue;
1777 }
1778 std::unique_ptr<C2Work> copy(new C2Work);
1779 copy->input.flags = C2FrameData::flags_t(
1780 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1781 copy->input.ordinal = work->input.ordinal;
1782 copy->input.ordinal.frameIndex = mFrameIndex++;
1783 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1784 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1785 }
1786 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1787 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1788 }
1789 copy->input.infoBuffers.insert(
1790 copy->input.infoBuffers.begin(),
1791 work->input.infoBuffers.begin(),
1792 work->input.infoBuffers.end());
1793 copy->worklets.emplace_back(new C2Worklet);
1794 configs.push_back(std::move(copy));
1795 watcher->onWorkDone(frameIndex);
1796 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001797 }
1798 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001799 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001800 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001801 Mutexed<Input>::Locked input(mInput);
1802 input->buffers->flush();
1803 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001804 }
1805 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001806 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001807 if (output->buffers) {
1808 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001809 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001810 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001811 }
1812}
1813
1814void CCodecBufferChannel::onWorkDone(
1815 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001816 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001817 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001818 feedInputBufferIfAvailable();
1819 }
1820}
1821
1822void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001823 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001824 if (mInputSurface) {
1825 return;
1826 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001827 std::shared_ptr<C2Buffer> buffer =
1828 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001829 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001830 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001831 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001832 if (input->lastFlushIndex >= frameIndex) {
1833 ALOGD("[%s] Ignoring stale input buffer done callback: "
1834 "last flush index = %lld, frameIndex = %lld",
1835 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1836 } else {
1837 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1838 if (!newInputSlotAvailable) {
1839 (void)input->extraBuffers.expireComponentBuffer(buffer);
1840 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001841 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001842 }
1843 if (newInputSlotAvailable) {
1844 feedInputBufferIfAvailable();
1845 }
1846}
1847
1848bool CCodecBufferChannel::handleWork(
1849 std::unique_ptr<C2Work> work,
1850 const sp<AMessage> &outputFormat,
1851 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001852 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001853 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001854 if (!output->buffers) {
1855 return false;
1856 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001857 }
1858
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001859 // Whether the output buffer should be reported to the client or not.
1860 bool notifyClient = false;
1861
1862 if (work->result == C2_OK){
1863 notifyClient = true;
1864 } else if (work->result == C2_NOT_FOUND) {
1865 ALOGD("[%s] flushed work; ignored.", mName);
1866 } else {
1867 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1868 // the config update.
1869 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1870 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1871 return false;
1872 }
1873
1874 if ((work->input.ordinal.frameIndex -
1875 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001876 // Discard frames from previous generation.
1877 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001878 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001879 }
1880
Wonsik Kim524b0582019-03-12 11:28:57 -07001881 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001882 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001883 || !(work->worklets.front()->output.flags &
1884 C2FrameData::FLAG_INCOMPLETE))) {
1885 mPipelineWatcher.lock()->onWorkDone(
1886 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001887 }
1888
1889 // NOTE: MediaCodec usage supposedly have only one worklet
1890 if (work->worklets.size() != 1u) {
1891 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1892 mName, work->worklets.size());
1893 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1894 return false;
1895 }
1896
1897 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1898
1899 std::shared_ptr<C2Buffer> buffer;
1900 // NOTE: MediaCodec usage supposedly have only one output stream.
1901 if (worklet->output.buffers.size() > 1u) {
1902 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1903 mName, worklet->output.buffers.size());
1904 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1905 return false;
1906 } else if (worklet->output.buffers.size() == 1u) {
1907 buffer = worklet->output.buffers[0];
1908 if (!buffer) {
1909 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1910 }
1911 }
1912
Wonsik Kim3dedf682021-05-03 10:57:09 -07001913 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1914 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001915 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001916 while (!worklet->output.configUpdate.empty()) {
1917 std::unique_ptr<C2Param> param;
1918 worklet->output.configUpdate.back().swap(param);
1919 worklet->output.configUpdate.pop_back();
1920 switch (param->coreIndex().coreIndex()) {
1921 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1922 C2PortReorderBufferDepthTuning::output reorderDepth;
1923 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001924 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1925 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001926 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001927 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001928 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001929 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1930 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001931 }
1932 break;
1933 }
1934 case C2PortReorderKeySetting::CORE_INDEX: {
1935 C2PortReorderKeySetting::output reorderKey;
1936 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001937 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001938 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1939 mName, reorderKey.value);
1940 } else {
1941 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1942 }
1943 break;
1944 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001945 case C2PortActualDelayTuning::CORE_INDEX: {
1946 if (param->isGlobal()) {
1947 C2ActualPipelineDelayTuning pipelineDelay;
1948 if (pipelineDelay.updateFrom(*param)) {
1949 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1950 mName, pipelineDelay.value);
1951 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001952 (void)mPipelineWatcher.lock()->pipelineDelay(
1953 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001954 }
1955 }
1956 if (param->forInput()) {
1957 C2PortActualDelayTuning::input inputDelay;
1958 if (inputDelay.updateFrom(*param)) {
1959 ALOGV("[%s] onWorkDone: updating input delay %u",
1960 mName, inputDelay.value);
1961 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001962 (void)mPipelineWatcher.lock()->inputDelay(
1963 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001964 }
1965 }
1966 if (param->forOutput()) {
1967 C2PortActualDelayTuning::output outputDelay;
1968 if (outputDelay.updateFrom(*param)) {
1969 ALOGV("[%s] onWorkDone: updating output delay %u",
1970 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001971 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001972 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001973 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001974
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001975 }
1976 }
1977 break;
1978 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001979 case C2PortTunnelSystemTime::CORE_INDEX: {
1980 C2PortTunnelSystemTime::output frameRenderTime;
1981 if (frameRenderTime.updateFrom(*param)) {
1982 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1983 mName, (long long)frameRenderTime.value,
1984 (long long)worklet->output.ordinal.timestamp.peekll());
1985 mCCodecCallback->onOutputFramesRendered(
1986 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1987 }
1988 break;
1989 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001990 case C2StreamTunnelHoldRender::CORE_INDEX: {
1991 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1992 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1993 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1994 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1995 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1996 mCCodecCallback->onFirstTunnelFrameReady();
1997 break;
1998 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001999 default:
2000 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2001 mName, param->index());
2002 break;
2003 }
2004 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002005 if (newInputDelay || newPipelineDelay) {
2006 Mutexed<Input>::Locked input(mInput);
2007 size_t newNumSlots =
2008 newInputDelay.value_or(input->inputDelay) +
2009 newPipelineDelay.value_or(input->pipelineDelay) +
2010 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08002011 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002012 if (input->buffers->isArrayMode()) {
2013 if (input->numSlots >= newNumSlots) {
2014 input->numExtraSlots = 0;
2015 } else {
2016 input->numExtraSlots = newNumSlots - input->numSlots;
2017 }
2018 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2019 mName, input->numExtraSlots);
2020 } else {
2021 input->numSlots = newNumSlots;
2022 }
2023 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002024 size_t numOutputSlots = 0;
2025 uint32_t reorderDepth = 0;
2026 bool outputBuffersChanged = false;
2027 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2028 Mutexed<Output>::Locked output(mOutput);
2029 if (!output->buffers) {
2030 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002031 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002032 numOutputSlots = output->numSlots;
2033 if (newReorderKey) {
2034 output->buffers->setReorderKey(newReorderKey.value());
2035 }
2036 if (newReorderDepth) {
2037 output->buffers->setReorderDepth(newReorderDepth.value());
2038 }
2039 reorderDepth = output->buffers->getReorderDepth();
2040 if (newOutputDelay) {
2041 output->outputDelay = newOutputDelay.value();
2042 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2043 if (output->numSlots < numOutputSlots) {
2044 output->numSlots = numOutputSlots;
2045 if (output->buffers->isArrayMode()) {
2046 OutputBuffersArray *array =
2047 (OutputBuffersArray *)output->buffers.get();
2048 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2049 mName, numOutputSlots);
2050 array->grow(numOutputSlots);
2051 outputBuffersChanged = true;
2052 }
2053 }
2054 }
2055 numOutputSlots = output->numSlots;
2056 }
2057 if (outputBuffersChanged) {
2058 mCCodecCallback->onOutputBuffersChanged();
2059 }
2060 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002061 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002062 {
2063 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2064 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002065 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002066 if (output->surface) {
2067 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2068 }
2069 }
2070 if (maxDequeueCount > 0) {
2071 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002072 }
2073 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002074
Pawin Vongmasa36653902018-11-15 00:10:25 -08002075 int32_t flags = 0;
2076 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002077 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002078 ALOGV("[%s] onWorkDone: output EOS", mName);
2079 }
2080
Pawin Vongmasa36653902018-11-15 00:10:25 -08002081 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2082 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2083 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2084 // shall correspond to the client input timesamp (in customOrdinal). By using the
2085 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2086 // produces multiple output.
2087 c2_cntr64_t timestamp =
2088 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2089 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002090 if (mInputSurface != nullptr) {
2091 // When using input surface we need to restore the original input timestamp.
2092 timestamp = work->input.ordinal.customOrdinal;
2093 }
My Name6bd9a7d2022-03-25 12:37:58 -07002094 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2095 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002096 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2097 mName,
2098 work->input.ordinal.customOrdinal.peekll(),
2099 work->input.ordinal.timestamp.peekll(),
2100 worklet->output.ordinal.timestamp.peekll(),
2101 timestamp.peekll());
2102
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002103 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002104 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002105 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002106 if (!output->buffers) {
2107 return false;
2108 }
2109 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002110 output->buffers->updateSkipCutBuffer(outputFormat);
2111 output->buffers->setFormat(outputFormat);
2112 }
2113 if (!notifyClient) {
2114 return false;
2115 }
2116 size_t index;
2117 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002118 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002119 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002120 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002121 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2122
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002123 // TRICKY: we want popped buffers reported in order, so sending
2124 // the callback while holding the lock here. This assumes that
2125 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2126 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002127 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002128 } else {
2129 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002130 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002131 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002132 return false;
2133 }
2134 }
2135
Wonsik Kimec585c32021-10-01 01:11:00 -07002136 bool drop = false;
2137 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2138 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2139 drop = true;
2140 }
2141
Marc Kassisec910342022-11-25 11:43:05 +01002142 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2143 // HAL, the flag is then removed in the corresponding output buffer.
2144 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2145 flags |= BUFFER_FLAG_DECODE_ONLY;
2146 }
2147
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002148 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002149 if (mTunneled && drop && outputFormat) {
2150 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2151 mName, work->input.ordinal.frameIndex.peekull());
2152 } else {
2153 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2154 mName, work->input.ordinal.frameIndex.peekull());
2155 notifyClient = false;
2156 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002157 }
2158
2159 if (buffer) {
2160 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2161 // TODO: properly translate these to metadata
2162 switch (info->coreIndex().coreIndex()) {
2163 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002164 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002165 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002166 }
2167 break;
2168 default:
2169 break;
2170 }
2171 }
2172 }
2173
2174 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002175 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002176 if (!output->buffers) {
2177 return false;
2178 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002179 output->buffers->pushToStash(
2180 buffer,
2181 notifyClient,
2182 timestamp.peek(),
2183 flags,
2184 outputFormat,
2185 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002186 }
2187 sendOutputBuffers();
2188 return true;
2189}
2190
2191void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002192 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002193 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002194 sp<MediaCodecBuffer> outBuffer;
2195 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002196
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002197 constexpr int kMaxReallocTry = 5;
2198 int reallocTryNum = 0;
2199
Pawin Vongmasa36653902018-11-15 00:10:25 -08002200 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002201 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002202 if (!output->buffers) {
2203 return;
2204 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002205 action = output->buffers->popFromStashAndRegister(
2206 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002207 if (action != OutputBuffers::REALLOCATE) {
2208 reallocTryNum = 0;
2209 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002210 switch (action) {
2211 case OutputBuffers::SKIP:
2212 return;
2213 case OutputBuffers::DISCARD:
2214 break;
2215 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002216 // TRICKY: we want popped buffers reported in order, so sending
2217 // the callback while holding the lock here. This assumes that
2218 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2219 // callbacks are always sent with the Output lock held.
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002220 mCallback->onOutputBufferAvailable(index, outBuffer);
2221 break;
2222 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002223 if (++reallocTryNum > kMaxReallocTry) {
2224 output.unlock();
2225 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2226 mName, kMaxReallocTry);
2227 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2228 return;
2229 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002230 if (!output->buffers->isArrayMode()) {
2231 output->buffers =
2232 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002233 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002234 static_cast<OutputBuffersArray*>(output->buffers.get())->
2235 realloc(c2Buffer);
2236 output.unlock();
2237 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002238 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002239 case OutputBuffers::RETRY:
2240 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2241 mName);
2242 return;
2243 default:
2244 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2245 "corrupted BufferAction value (%d) "
2246 "returned from popFromStashAndRegister.",
2247 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002248 return;
2249 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002250 }
2251}
2252
Sungtak Lee99144332023-01-26 11:03:14 +00002253status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002254 static std::atomic_uint32_t surfaceGeneration{0};
2255 uint32_t generation = (getpid() << 10) |
2256 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2257 & ((1 << 10) - 1));
2258
2259 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002260 int maxDequeueCount;
2261 sp<Surface> oldSurface;
2262 {
2263 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2264 maxDequeueCount = outputSurface->maxDequeueBuffers;
2265 oldSurface = outputSurface->surface;
2266 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002267 if (newSurface) {
2268 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002269 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002270 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002271 producer = newSurface->getIGraphicBufferProducer();
2272 producer->setGenerationNumber(generation);
2273 } else {
2274 ALOGE("[%s] setting output surface to null", mName);
2275 return INVALID_OPERATION;
2276 }
2277
2278 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2279 C2BlockPool::local_id_t outputPoolId;
2280 {
2281 Mutexed<BlockPools>::Locked pools(mBlockPools);
2282 outputPoolId = pools->outputPoolId;
2283 outputPoolIntf = pools->outputPoolIntf;
2284 }
2285
2286 if (outputPoolIntf) {
2287 if (mComponent->setOutputSurface(
2288 outputPoolId,
2289 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002290 generation,
2291 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002292 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2293 return INVALID_OPERATION;
2294 }
2295 }
2296
2297 {
2298 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2299 output->surface = newSurface;
2300 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002301 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002302 }
2303
Sungtak Lee99144332023-01-26 11:03:14 +00002304 if (oldSurface && pushBlankBuffer) {
2305 // When ReleaseSurface was set from MediaCodec,
2306 // pushing a blank buffer at the end might be necessary.
2307 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2308 if (anw) {
2309 pushBlankBuffersToNativeWindow(anw.get());
2310 }
2311 }
2312
Pawin Vongmasa36653902018-11-15 00:10:25 -08002313 return OK;
2314}
2315
Wonsik Kimab34ed62019-01-31 15:28:46 -08002316PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002317 // Otherwise, component may have stalled work due to input starvation up to
2318 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002319 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2320 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002321 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002322 size_t outputDelay = mOutput.lock()->outputDelay;
2323 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002324 Mutexed<Input>::Locked input(mInput);
2325 n = input->inputDelay + input->pipelineDelay + outputDelay;
2326 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002327 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002328}
2329
Pawin Vongmasa36653902018-11-15 00:10:25 -08002330void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2331 mMetaMode = mode;
2332}
2333
Wonsik Kim596187e2019-10-25 12:44:10 -07002334void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002335 if (mCrypto != nullptr) {
2336 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2337 mCrypto->unsetHeap(entry.second);
2338 }
2339 mHeapSeqNumMap.clear();
2340 if (mHeapSeqNum >= 0) {
2341 mCrypto->unsetHeap(mHeapSeqNum);
2342 mHeapSeqNum = -1;
2343 }
2344 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002345 mCrypto = crypto;
2346}
2347
2348void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2349 mDescrambler = descrambler;
2350}
2351
Pawin Vongmasa36653902018-11-15 00:10:25 -08002352status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2353 // C2_OK is always translated to OK.
2354 if (c2s == C2_OK) {
2355 return OK;
2356 }
2357
2358 // Operation-dependent translation
2359 // TODO: Add as necessary
2360 switch (c2op) {
2361 case C2_OPERATION_Component_start:
2362 switch (c2s) {
2363 case C2_NO_MEMORY:
2364 return NO_MEMORY;
2365 default:
2366 return UNKNOWN_ERROR;
2367 }
2368 default:
2369 break;
2370 }
2371
2372 // Backup operation-agnostic translation
2373 switch (c2s) {
2374 case C2_BAD_INDEX:
2375 return BAD_INDEX;
2376 case C2_BAD_VALUE:
2377 return BAD_VALUE;
2378 case C2_BLOCKING:
2379 return WOULD_BLOCK;
2380 case C2_DUPLICATE:
2381 return ALREADY_EXISTS;
2382 case C2_NO_INIT:
2383 return NO_INIT;
2384 case C2_NO_MEMORY:
2385 return NO_MEMORY;
2386 case C2_NOT_FOUND:
2387 return NAME_NOT_FOUND;
2388 case C2_TIMED_OUT:
2389 return TIMED_OUT;
2390 case C2_BAD_STATE:
2391 case C2_CANCELED:
2392 case C2_CANNOT_DO:
2393 case C2_CORRUPTED:
2394 case C2_OMITTED:
2395 case C2_REFUSED:
2396 return UNKNOWN_ERROR;
2397 default:
2398 return -static_cast<status_t>(c2s);
2399 }
2400}
2401
Pawin Vongmasa36653902018-11-15 00:10:25 -08002402} // namespace android