blob: e800ccd973c19ad2d502703bc1f5b01c32fb4c22 [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>
Josh Hou8eddf4b2021-02-02 16:26:53 +080037#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080038#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080039#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080040#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070041#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080042#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070043#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080044#include <media/openmax/OMX_Core.h>
45#include <media/stagefright/foundation/ABuffer.h>
46#include <media/stagefright/foundation/ALookup.h>
47#include <media/stagefright/foundation/AMessage.h>
48#include <media/stagefright/foundation/AUtils.h>
49#include <media/stagefright/foundation/hexdump.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080050#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070051#include <media/stagefright/SkipCutBuffer.h>
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010052#include <media/stagefright/SurfaceUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080053#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070054#include <mediadrm/ICrypto.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080055#include <system/window.h>
56
57#include "CCodecBufferChannel.h"
58#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080059
60namespace android {
61
62using android::base::StringPrintf;
63using hardware::hidl_handle;
64using hardware::hidl_string;
65using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070066using hardware::fromHeap;
67using hardware::HidlMemory;
68
Pawin Vongmasa36653902018-11-15 00:10:25 -080069using namespace hardware::cas::V1_0;
70using namespace hardware::cas::native::V1_0;
71
72using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070073using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080074
Pawin Vongmasa36653902018-11-15 00:10:25 -080075namespace {
76
Wonsik Kim469c8342019-04-11 16:46:09 -070077constexpr size_t kSmoothnessFactor = 4;
78constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080079
Sungtak Leeab6f2f32019-02-15 14:43:51 -080080// This is for keeping IGBP's buffer dropping logic in legacy mode other
81// than making it non-blocking. Do not change this value.
82const static size_t kDequeueTimeoutNs = 0;
83
Pawin Vongmasa36653902018-11-15 00:10:25 -080084} // namespace
85
86CCodecBufferChannel::QueueGuard::QueueGuard(
87 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
88 Mutex::Autolock l(mSync.mGuardLock);
89 // At this point it's guaranteed that mSync is not under state transition,
90 // as we are holding its mutex.
91
92 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
93 if (count->value == -1) {
94 mRunning = false;
95 } else {
96 ++count->value;
97 mRunning = true;
98 }
99}
100
101CCodecBufferChannel::QueueGuard::~QueueGuard() {
102 if (mRunning) {
103 // We are not holding mGuardLock at this point so that QueueSync::stop() can
104 // keep holding the lock until mCount reaches zero.
105 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
106 --count->value;
107 count->cond.broadcast();
108 }
109}
110
111void CCodecBufferChannel::QueueSync::start() {
112 Mutex::Autolock l(mGuardLock);
113 // If stopped, it goes to running state; otherwise no-op.
114 Mutexed<Counter>::Locked count(mCount);
115 if (count->value == -1) {
116 count->value = 0;
117 }
118}
119
120void CCodecBufferChannel::QueueSync::stop() {
121 Mutex::Autolock l(mGuardLock);
122 Mutexed<Counter>::Locked count(mCount);
123 if (count->value == -1) {
124 // no-op
125 return;
126 }
127 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
128 // mCount can only decrement. In other words, threads that acquired the lock
129 // are allowed to finish execution but additional threads trying to acquire
130 // the lock at this point will block, and then get QueueGuard at STOPPED
131 // state.
132 while (count->value != 0) {
133 count.waitForCondition(count->cond);
134 }
135 count->value = -1;
136}
137
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700138// Input
139
140CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
141
Pawin Vongmasa36653902018-11-15 00:10:25 -0800142// CCodecBufferChannel
143
144CCodecBufferChannel::CCodecBufferChannel(
145 const std::shared_ptr<CCodecCallback> &callback)
146 : mHeapSeqNum(-1),
147 mCCodecCallback(callback),
148 mFrameIndex(0u),
149 mFirstValidFrameIndex(0u),
150 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700151 mInputMetEos(false),
152 mSendEncryptedInfoBuffer(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700153 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700154 {
155 Mutexed<Input>::Locked input(mInput);
156 input->buffers.reset(new DummyInputBuffers(""));
157 input->extraBuffers.flush();
158 input->inputDelay = 0u;
159 input->pipelineDelay = 0u;
160 input->numSlots = kSmoothnessFactor;
161 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700162 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700163 }
164 {
165 Mutexed<Output>::Locked output(mOutput);
166 output->outputDelay = 0u;
167 output->numSlots = kSmoothnessFactor;
168 }
David Stevensc3fbb282021-01-18 18:11:20 +0900169 {
170 Mutexed<BlockPools>::Locked pools(mBlockPools);
171 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
172 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800173}
174
175CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800176 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800177 mCrypto->unsetHeap(mHeapSeqNum);
178 }
179}
180
181void CCodecBufferChannel::setComponent(
182 const std::shared_ptr<Codec2Client::Component> &component) {
183 mComponent = component;
184 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
185 mName = mComponentName.c_str();
186}
187
188status_t CCodecBufferChannel::setInputSurface(
189 const std::shared_ptr<InputSurfaceWrapper> &surface) {
190 ALOGV("[%s] setInputSurface", mName);
191 mInputSurface = surface;
192 return mInputSurface->connect(mComponent);
193}
194
195status_t CCodecBufferChannel::signalEndOfInputStream() {
196 if (mInputSurface == nullptr) {
197 return INVALID_OPERATION;
198 }
199 return mInputSurface->signalEndOfInputStream();
200}
201
Sungtak Lee04b30352020-07-27 13:57:25 -0700202status_t CCodecBufferChannel::queueInputBufferInternal(
203 sp<MediaCodecBuffer> buffer,
204 std::shared_ptr<C2LinearBlock> encryptedBlock,
205 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800206 int64_t timeUs;
207 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
208
209 if (mInputMetEos) {
210 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
211 return OK;
212 }
213
214 int32_t flags = 0;
215 int32_t tmp = 0;
216 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200217 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800218 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
219 eos = true;
220 mInputMetEos = true;
221 ALOGV("[%s] input EOS", mName);
222 }
223 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
224 flags |= C2FrameData::FLAG_CODEC_CONFIG;
225 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200226 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
227 tunnelFirstFrame = true;
228 }
Marc Kassis96343b42022-12-09 11:49:44 +0100229 if (buffer->meta()->findInt32("decode-only", &tmp) && tmp) {
230 flags |= C2FrameData::FLAG_DROP_FRAME;
231 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800232 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800233 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800234 std::unique_ptr<C2Work> work(new C2Work);
235 work->input.ordinal.timestamp = timeUs;
236 work->input.ordinal.frameIndex = mFrameIndex++;
237 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
238 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
239 // Keep client timestamp in customOrdinal
240 work->input.ordinal.customOrdinal = timeUs;
241 work->input.buffers.clear();
242
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700243 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800244 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800245
Pawin Vongmasa36653902018-11-15 00:10:25 -0800246 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700247 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800248 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700249 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800250 return -ENOENT;
251 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700252 // TODO: we want to delay copying buffers.
253 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
254 copy = input->buffers->cloneAndReleaseBuffer(buffer);
255 if (copy != nullptr) {
256 (void)input->extraBuffers.assignSlot(copy);
257 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
258 return UNKNOWN_ERROR;
259 }
260 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
261 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
262 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700263 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700264 } else {
265 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
266 "buffer starvation on component.", mName);
267 }
268 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800269 if (input->frameReassembler) {
270 usesFrameReassembler = true;
271 input->frameReassembler.process(buffer, &items);
272 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900273 int32_t cvo = 0;
274 if (buffer->meta()->findInt32("cvo", &cvo)) {
275 int32_t rotation = cvo % 360;
276 // change rotation to counter-clock wise.
277 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
278
279 Mutexed<OutputSurface>::Locked output(mOutputSurface);
280 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
281 output->rotation[frameIndex] = rotation;
282 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800283 work->input.buffers.push_back(c2buffer);
284 if (encryptedBlock) {
285 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
286 kParamIndexEncryptedBuffer,
287 encryptedBlock->share(0, blockSize, C2Fence())));
288 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700289 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800290 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700291 Mutexed<Input>::Locked input(mInput);
292 if (input->frameReassembler) {
293 usesFrameReassembler = true;
294 // drain any pending items with eos
295 input->frameReassembler.process(buffer, &items);
296 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800297 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800298 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800299 if (usesFrameReassembler) {
300 if (!items.empty()) {
301 items.front()->input.configUpdate = std::move(mParamsToBeSet);
302 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
303 }
304 } else {
305 work->input.flags = (C2FrameData::flags_t)flags;
306 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800307
Wonsik Kime1104ca2020-11-24 15:01:33 -0800308 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200309 if (tunnelFirstFrame) {
310 C2StreamTunnelHoldRender::input tunnelHoldRender{
311 0u /* stream */,
312 C2_TRUE /* value */
313 };
314 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
315 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800316 work->worklets.clear();
317 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800318
Wonsik Kime1104ca2020-11-24 15:01:33 -0800319 items.push_back(std::move(work));
320
321 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800322 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800323 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800324 work.reset(new C2Work);
325 work->input.ordinal.timestamp = timeUs;
326 work->input.ordinal.frameIndex = mFrameIndex++;
327 // WORKAROUND: keep client timestamp in customOrdinal
328 work->input.ordinal.customOrdinal = timeUs;
329 work->input.buffers.clear();
330 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800331 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800332 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800333 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800334 c2_status_t err = C2_OK;
335 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700336 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
337 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800338 {
339 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
340 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
341 for (const std::unique_ptr<C2Work> &work : items) {
342 watcher->onWorkQueued(
343 work->input.ordinal.frameIndex.peeku(),
344 std::vector(work->input.buffers),
345 now);
346 }
347 }
348 err = mComponent->queue(&items);
349 }
350 if (err != C2_OK) {
351 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
352 for (const std::unique_ptr<C2Work> &work : items) {
353 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
354 }
355 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700356 Mutexed<Input>::Locked input(mInput);
357 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700358 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700359 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700360 } else if (buffer) {
361 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700362 }
363 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
364 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800365 }
366
367 feedInputBufferIfAvailableInternal();
368 return err;
369}
370
371status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
372 QueueGuard guard(mSync);
373 if (!guard.isRunning()) {
374 ALOGD("[%s] setParameters is only supported in the running state.", mName);
375 return -ENOSYS;
376 }
377 mParamsToBeSet.insert(mParamsToBeSet.end(),
378 std::make_move_iterator(params.begin()),
379 std::make_move_iterator(params.end()));
380 params.clear();
381 return OK;
382}
383
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800384status_t CCodecBufferChannel::attachBuffer(
385 const std::shared_ptr<C2Buffer> &c2Buffer,
386 const sp<MediaCodecBuffer> &buffer) {
387 if (!buffer->copy(c2Buffer)) {
388 return -ENOSYS;
389 }
390 return OK;
391}
392
393void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
394 if (!mDecryptDestination || mDecryptDestination->size() < size) {
395 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
396 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
397 mCrypto->unsetHeap(mHeapSeqNum);
398 }
399 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
400 if (mCrypto) {
401 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
402 }
403 }
404}
405
406int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
407 CHECK(mCrypto);
408 auto it = mHeapSeqNumMap.find(memory);
409 int32_t heapSeqNum = -1;
410 if (it == mHeapSeqNumMap.end()) {
411 heapSeqNum = mCrypto->setHeap(memory);
412 mHeapSeqNumMap.emplace(memory, heapSeqNum);
413 } else {
414 heapSeqNum = it->second;
415 }
416 return heapSeqNum;
417}
418
419status_t CCodecBufferChannel::attachEncryptedBuffer(
420 const sp<hardware::HidlMemory> &memory,
421 bool secure,
422 const uint8_t *key,
423 const uint8_t *iv,
424 CryptoPlugin::Mode mode,
425 CryptoPlugin::Pattern pattern,
426 size_t offset,
427 const CryptoPlugin::SubSample *subSamples,
428 size_t numSubSamples,
429 const sp<MediaCodecBuffer> &buffer) {
430 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
431 static const C2MemoryUsage kDefaultReadWriteUsage{
432 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
433
434 size_t size = 0;
435 for (size_t i = 0; i < numSubSamples; ++i) {
436 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
437 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700438 if (size == 0) {
439 buffer->setRange(0, 0);
440 return OK;
441 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800442 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
443 std::shared_ptr<C2LinearBlock> block;
444 c2_status_t err = pool->fetchLinearBlock(
445 size,
446 secure ? kSecureUsage : kDefaultReadWriteUsage,
447 &block);
448 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700449 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
450 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800451 return NO_MEMORY;
452 }
453 if (!secure) {
454 ensureDecryptDestination(size);
455 }
456 ssize_t result = -1;
457 ssize_t codecDataOffset = 0;
458 if (mCrypto) {
459 AString errorDetailMsg;
460 int32_t heapSeqNum = getHeapSeqNum(memory);
461 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
462 hardware::drm::V1_0::DestinationBuffer dst;
463 if (secure) {
464 dst.type = DrmBufferType::NATIVE_HANDLE;
465 dst.secureMemory = hardware::hidl_handle(block->handle());
466 } else {
467 dst.type = DrmBufferType::SHARED_MEMORY;
468 IMemoryToSharedBuffer(
469 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
470 }
471 result = mCrypto->decrypt(
472 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
473 dst, &errorDetailMsg);
474 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700475 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800476 return result;
477 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800478 } else {
479 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
480 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
481 hidl_vec<SubSample> hidlSubSamples;
482 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
483
484 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
485 hardware::cas::native::V1_0::DestinationBuffer dst;
486 if (secure) {
487 dst.type = BufferType::NATIVE_HANDLE;
488 dst.secureMemory = hardware::hidl_handle(block->handle());
489 } else {
490 dst.type = BufferType::SHARED_MEMORY;
491 dst.nonsecureMemory = src;
492 }
493
494 CasStatus status = CasStatus::OK;
495 hidl_string detailedError;
496 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
497
498 if (key != nullptr) {
499 sctrl = (ScramblingControl)key[0];
500 // Adjust for the PES offset
501 codecDataOffset = key[2] | (key[3] << 8);
502 }
503
504 auto returnVoid = mDescrambler->descramble(
505 sctrl,
506 hidlSubSamples,
507 src,
508 0,
509 dst,
510 0,
511 [&status, &result, &detailedError] (
512 CasStatus _status, uint32_t _bytesWritten,
513 const hidl_string& _detailedError) {
514 status = _status;
515 result = (ssize_t)_bytesWritten;
516 detailedError = _detailedError;
517 });
518
519 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
520 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
521 mName, returnVoid.description().c_str(), status, result);
522 return UNKNOWN_ERROR;
523 }
524
525 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700526 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
527 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800528 return BAD_VALUE;
529 }
530 }
531 if (!secure) {
532 C2WriteView view = block->map().get();
533 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700534 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
535 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800536 return UNKNOWN_ERROR;
537 }
538 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700539 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
540 "(non-secure)",
541 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800542 return UNKNOWN_ERROR;
543 }
544 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
545 }
546 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
547 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
548 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700549 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800550 return -ENOSYS;
551 }
552 return OK;
553}
554
Pawin Vongmasa36653902018-11-15 00:10:25 -0800555status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
556 QueueGuard guard(mSync);
557 if (!guard.isRunning()) {
558 ALOGD("[%s] No more buffers should be queued at current state.", mName);
559 return -ENOSYS;
560 }
561 return queueInputBufferInternal(buffer);
562}
563
564status_t CCodecBufferChannel::queueSecureInputBuffer(
565 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
566 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
567 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
568 AString *errorDetailMsg) {
569 QueueGuard guard(mSync);
570 if (!guard.isRunning()) {
571 ALOGD("[%s] No more buffers should be queued at current state.", mName);
572 return -ENOSYS;
573 }
574
575 if (!hasCryptoOrDescrambler()) {
576 return -ENOSYS;
577 }
578 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
579
Sungtak Lee04b30352020-07-27 13:57:25 -0700580 std::shared_ptr<C2LinearBlock> block;
581 size_t allocSize = buffer->size();
582 size_t bufferSize = 0;
583 c2_status_t blockRes = C2_OK;
584 bool copied = false;
585 if (mSendEncryptedInfoBuffer) {
586 static const C2MemoryUsage kDefaultReadWriteUsage{
587 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
588 constexpr int kAllocGranule0 = 1024 * 64;
589 constexpr int kAllocGranule1 = 1024 * 1024;
590 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
591 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
592 if (allocSize <= kAllocGranule1) {
593 bufferSize = align(allocSize, kAllocGranule0);
594 } else {
595 bufferSize = align(allocSize, kAllocGranule1);
596 }
597 blockRes = pool->fetchLinearBlock(
598 bufferSize, kDefaultReadWriteUsage, &block);
599
600 if (blockRes == C2_OK) {
601 C2WriteView view = block->map().get();
602 if (view.error() == C2_OK && view.size() == bufferSize) {
603 copied = true;
604 // TODO: only copy clear sections
605 memcpy(view.data(), buffer->data(), allocSize);
606 }
607 }
608 }
609
610 if (!copied) {
611 block.reset();
612 }
613
Pawin Vongmasa36653902018-11-15 00:10:25 -0800614 ssize_t result = -1;
615 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700616 if (numSubSamples == 1
617 && subSamples[0].mNumBytesOfClearData == 0
618 && subSamples[0].mNumBytesOfEncryptedData == 0) {
619 // We don't need to go through crypto or descrambler if the input is empty.
620 result = 0;
621 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700622 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800623 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700624 destination.type = DrmBufferType::NATIVE_HANDLE;
625 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800626 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700627 destination.type = DrmBufferType::SHARED_MEMORY;
628 IMemoryToSharedBuffer(
629 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800630 }
Robert Shih895fba92019-07-16 16:29:44 -0700631 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800632 encryptedBuffer->fillSourceBuffer(&source);
633 result = mCrypto->decrypt(
634 key, iv, mode, pattern, source, buffer->offset(),
635 subSamples, numSubSamples, destination, errorDetailMsg);
636 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700637 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800638 return result;
639 }
Robert Shih895fba92019-07-16 16:29:44 -0700640 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800641 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
642 }
643 } else {
644 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
645 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
646 hidl_vec<SubSample> hidlSubSamples;
647 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
648
649 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
650 encryptedBuffer->fillSourceBuffer(&srcBuffer);
651
652 DestinationBuffer dstBuffer;
653 if (secure) {
654 dstBuffer.type = BufferType::NATIVE_HANDLE;
655 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
656 } else {
657 dstBuffer.type = BufferType::SHARED_MEMORY;
658 dstBuffer.nonsecureMemory = srcBuffer;
659 }
660
661 CasStatus status = CasStatus::OK;
662 hidl_string detailedError;
663 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
664
665 if (key != nullptr) {
666 sctrl = (ScramblingControl)key[0];
667 // Adjust for the PES offset
668 codecDataOffset = key[2] | (key[3] << 8);
669 }
670
671 auto returnVoid = mDescrambler->descramble(
672 sctrl,
673 hidlSubSamples,
674 srcBuffer,
675 0,
676 dstBuffer,
677 0,
678 [&status, &result, &detailedError] (
679 CasStatus _status, uint32_t _bytesWritten,
680 const hidl_string& _detailedError) {
681 status = _status;
682 result = (ssize_t)_bytesWritten;
683 detailedError = _detailedError;
684 });
685
686 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
687 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
688 mName, returnVoid.description().c_str(), status, result);
689 return UNKNOWN_ERROR;
690 }
691
692 if (result < codecDataOffset) {
693 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
694 return BAD_VALUE;
695 }
696
697 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
698
699 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
700 encryptedBuffer->copyDecryptedContentFromMemory(result);
701 }
702 }
703
704 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700705
706 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800707}
708
709void CCodecBufferChannel::feedInputBufferIfAvailable() {
710 QueueGuard guard(mSync);
711 if (!guard.isRunning()) {
712 ALOGV("[%s] We're not running --- no input buffer reported", mName);
713 return;
714 }
715 feedInputBufferIfAvailableInternal();
716}
717
718void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900719 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800720 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700721 }
722 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700723 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700724 if (!output->buffers ||
725 output->buffers->hasPending() ||
Wonsik Kim0487b782020-10-28 11:45:50 -0700726 output->buffers->numActiveSlots() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800727 return;
728 }
729 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700730 size_t numActiveSlots = 0;
731 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800732 sp<MediaCodecBuffer> inBuffer;
733 size_t index;
734 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700735 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700736 numActiveSlots = input->buffers->numActiveSlots();
737 if (numActiveSlots >= input->numSlots) {
738 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800739 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700740 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800741 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800742 break;
743 }
744 }
745 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
746 mCallback->onInputBufferAvailable(index, inBuffer);
747 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700748 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800749}
750
751status_t CCodecBufferChannel::renderOutputBuffer(
752 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800753 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800754 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800755 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800756 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700757 Mutexed<Output>::Locked output(mOutput);
758 if (output->buffers) {
759 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800760 }
761 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800762 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
763 // set to true.
764 sendOutputBuffers();
765 // input buffer feeding may have been gated by pending output buffers
766 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800767 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800768 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700769 std::call_once(mRenderWarningFlag, [this] {
770 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
771 "timestamp or render=true with non-video buffers. Apps should "
772 "call releaseOutputBuffer() with render=false for those.",
773 mName);
774 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800775 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800776 return INVALID_OPERATION;
777 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800778
779#if 0
780 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
781 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
782 for (const std::shared_ptr<const C2Info> &info : infoParams) {
783 AString res;
784 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
785 if (ix) res.append(", ");
786 res.append(*((int32_t*)info.get() + (ix / 4)));
787 }
788 ALOGV(" [%s]", res.c_str());
789 }
790#endif
791 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
792 std::static_pointer_cast<const C2StreamRotationInfo::output>(
793 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
794 bool flip = rotation && (rotation->flip & 1);
795 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900796
797 {
798 Mutexed<OutputSurface>::Locked output(mOutputSurface);
799 if (output->surface == nullptr) {
800 ALOGI("[%s] cannot render buffer without surface", mName);
801 return OK;
802 }
803 int64_t frameIndex;
804 buffer->meta()->findInt64("frameIndex", &frameIndex);
805 if (output->rotation.count(frameIndex) != 0) {
806 auto it = output->rotation.find(frameIndex);
807 quarters = (it->second / 90) & 3;
808 output->rotation.erase(it);
809 }
810 }
811
Pawin Vongmasa36653902018-11-15 00:10:25 -0800812 uint32_t transform = 0;
813 switch (quarters) {
814 case 0: // no rotation
815 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
816 break;
817 case 1: // 90 degrees counter-clockwise
818 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
819 : HAL_TRANSFORM_ROT_270;
820 break;
821 case 2: // 180 degrees
822 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
823 break;
824 case 3: // 90 degrees clockwise
825 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
826 : HAL_TRANSFORM_ROT_90;
827 break;
828 }
829
830 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
831 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
832 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
833 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
834 if (surfaceScaling) {
835 videoScalingMode = surfaceScaling->value;
836 }
837
838 // Use dataspace from format as it has the default aspects already applied
839 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
840 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
841
842 // HDR static info
843 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
844 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
845 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
846
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800847 // HDR10 plus info
848 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
849 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
850 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800851 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
852 hdr10PlusInfo.reset();
853 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800854
Wonsik Kima79c5522022-01-18 16:29:24 -0800855 // HDR dynamic info
856 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
857 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
858 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
859 // TODO: make this sticky & enable unset
860 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
861 hdrDynamicInfo.reset();
862 }
863
864 if (hdr10PlusInfo) {
865 // C2StreamHdr10PlusInfo is deprecated; components should use
866 // C2StreamHdrDynamicMetadataInfo
867 // TODO: #metric
868 if (hdrDynamicInfo) {
869 // It is unexpected that C2StreamHdr10PlusInfo and
870 // C2StreamHdrDynamicMetadataInfo is both present.
871 // C2StreamHdrDynamicMetadataInfo takes priority.
872 // TODO: #metric
873 } else {
874 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
875 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
876 hdr10PlusInfo->flexCount(),
877 0u,
878 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
879 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
880 hdrDynamicInfo = info;
881 }
882 }
883
Pawin Vongmasa36653902018-11-15 00:10:25 -0800884 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
885 if (blocks.size() != 1u) {
886 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
887 return UNKNOWN_ERROR;
888 }
889 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700890 C2Fence c2fence = block.fence();
891 sp<Fence> fence = Fence::NO_FENCE;
892 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
893 // Once C2Fence::type() is added, check the exact C2Fence type
894 if (c2fence.isHW()) {
895 int fenceFd = c2fence.fd();
896 fence = sp<Fence>::make(fenceFd);
897 if (!fence) {
898 ALOGE("[%s] Failed to allocate a fence", mName);
899 close(fenceFd);
900 return NO_MEMORY;
901 }
902 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800903
904 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -0700905 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800906 timestampNs,
907 false, // droppable
908 dataSpace,
909 Rect(blocks.front().crop().left,
910 blocks.front().crop().top,
911 blocks.front().crop().right(),
912 blocks.front().crop().bottom()),
913 videoScalingMode,
914 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700915 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800916 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800917 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800918 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800919 // If mastering max and min luminance fields are 0, do not use them.
920 // It indicates the value may not be present in the stream.
921 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
922 hdrStaticInfo->mastering.minLuminance > 0.0f) {
923 struct android_smpte2086_metadata smpte2086_meta = {
924 .displayPrimaryRed = {
925 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
926 },
927 .displayPrimaryGreen = {
928 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
929 },
930 .displayPrimaryBlue = {
931 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
932 },
933 .whitePoint = {
934 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
935 },
936 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
937 .minLuminance = hdrStaticInfo->mastering.minLuminance,
938 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800939 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800940 hdr.smpte2086 = smpte2086_meta;
941 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700942 // If the content light level fields are 0, do not use them, it
943 // indicates the value may not be present in the stream.
944 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
945 struct android_cta861_3_metadata cta861_meta = {
946 .maxContentLightLevel = hdrStaticInfo->maxCll,
947 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
948 };
949 hdr.validTypes |= HdrMetadata::CTA861_3;
950 hdr.cta8613 = cta861_meta;
951 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900952
953 // does not have valid info
954 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
955 hdrStaticInfo.reset();
956 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800957 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800958 if (hdrDynamicInfo
959 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800960 hdr.validTypes |= HdrMetadata::HDR10PLUS;
961 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800962 hdrDynamicInfo->m.data,
963 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800964 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800965 qbi.setHdrMetadata(hdr);
966 }
Hongguangfc1478a2022-07-20 22:56:06 -0700967 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
968
Brian Lindahl932bf602023-03-09 11:59:48 -0700969 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
970 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
971 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800972 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
973 if (result != OK) {
974 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800975 if (result == NO_INIT) {
976 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
977 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800978 return result;
979 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800980
981 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
982 ALOGD("[%s] queue buffer successful", mName);
983 } else {
984 ALOGV("[%s] queue buffer successful", mName);
985 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800986
987 int64_t mediaTimeUs = 0;
988 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahl932bf602023-03-09 11:59:48 -0700989 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
990 processRenderedFrames(qbo.frameTimestamps);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800991
992 return OK;
993}
994
Brian Lindahl932bf602023-03-09 11:59:48 -0700995void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
996 int hasPresentFenceTimes = 0;
997 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
998 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
999 if (mHasPresentFenceTimes) {
1000 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1001 }
1002 mTrackedFrames.clear();
1003}
1004
1005void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1006 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1007 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1008 // so track the frame as if the desired render time is now.
1009 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1010 if (desiredRenderTimeNs < nowNs) {
1011 desiredRenderTimeNs = nowNs;
1012 }
1013 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1014 // actually rendered.
1015 TrackedFrame frame;
1016 frame.number = qbo.nextFrameNumber - 1;
1017 frame.mediaTimeUs = mediaTimeUs;
1018 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1019 frame.latchTime = -1;
1020 frame.presentFence = nullptr;
1021 mTrackedFrames.push_back(frame);
1022}
1023
1024void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1025 // Grab the latch times and present fences from the frame event deltas
1026 for (const auto& delta : deltas) {
1027 for (auto& frame : mTrackedFrames) {
1028 if (delta.getFrameNumber() == frame.number) {
1029 delta.getLatchTime(&frame.latchTime);
1030 delta.getDisplayPresentFence(&frame.presentFence);
1031 }
1032 }
1033 }
1034
1035 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1036 // in fact, been rendered.
1037 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1038 while (!mTrackedFrames.empty()) {
1039 TrackedFrame & frame = mTrackedFrames.front();
1040 // Frames that should have been rendered at least 100ms in the past are checked
1041 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1042 break;
1043 }
1044
1045 // If we don't have a render time by now, then consider the frame as dropped
1046 int64_t renderTimeNs = getRenderTimeNs(frame);
1047 if (renderTimeNs != -1) {
1048 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1049 }
1050 mTrackedFrames.pop_front();
1051 }
1052}
1053
1054int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1055 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1056 if (!mHasPresentFenceTimes) {
1057 if (frame.latchTime == -1) {
1058 ALOGD("no latch time for frame %d", (int) frame.number);
1059 return -1;
1060 }
1061 return frame.latchTime;
1062 }
1063
1064 if (frame.presentFence == nullptr) {
1065 ALOGW("no present fence for frame %d", (int) frame.number);
1066 return -1;
1067 }
1068
1069 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1070
1071 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1072 ALOGW("invalid signal time for frame %d", (int) frame.number);
1073 return -1;
1074 }
1075
1076 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1077 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1078 return -1;
1079 }
1080
1081 return actualRenderTimeNs;
1082}
1083
1084void CCodecBufferChannel::pollForRenderedBuffers() {
1085 FrameEventHistoryDelta delta;
1086 mComponent->pollForRenderedFrames(&delta);
1087 processRenderedFrames(delta);
1088}
1089
Pawin Vongmasa36653902018-11-15 00:10:25 -08001090status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1091 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1092 bool released = false;
1093 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001094 Mutexed<Input>::Locked input(mInput);
1095 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001096 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001097 }
1098 }
1099 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001100 Mutexed<Output>::Locked output(mOutput);
1101 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001102 released = true;
1103 }
1104 }
1105 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001106 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001107 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001108 } else {
1109 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1110 }
1111 return OK;
1112}
1113
1114void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1115 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001116 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001117
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001118 if (!input->buffers) {
1119 ALOGE("getInputBufferArray: No Input Buffers allocated");
1120 return;
1121 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001122 if (!input->buffers->isArrayMode()) {
1123 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001124 }
1125
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001126 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001127}
1128
1129void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1130 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001131 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001132 if (!output->buffers) {
1133 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1134 return;
1135 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001136 if (!output->buffers->isArrayMode()) {
1137 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001138 }
1139
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001140 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001141}
1142
1143status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001144 const sp<AMessage> &inputFormat,
1145 const sp<AMessage> &outputFormat,
1146 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001147 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1148 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001149 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001150 C2PortReorderBufferDepthTuning::output reorderDepth;
1151 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001152 C2PortActualDelayTuning::input inputDelay(0);
1153 C2PortActualDelayTuning::output outputDelay(0);
1154 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001155 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001156
Pawin Vongmasa36653902018-11-15 00:10:25 -08001157 c2_status_t err = mComponent->query(
1158 {
1159 &iStreamFormat,
1160 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001161 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001162 &reorderDepth,
1163 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001164 &inputDelay,
1165 &pipelineDelay,
1166 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001167 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001168 },
1169 {},
1170 C2_DONT_BLOCK,
1171 nullptr);
1172 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001173 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001174 return UNKNOWN_ERROR;
1175 }
1176 } else if (err != C2_OK) {
1177 return UNKNOWN_ERROR;
1178 }
1179
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001180 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1181 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1182 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1183
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001184 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1185 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001186
Pawin Vongmasa36653902018-11-15 00:10:25 -08001187 // TODO: get this from input format
1188 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1189
Sungtak Lee04b30352020-07-27 13:57:25 -07001190 // secure mode is a static parameter (shall not change in the executing state)
1191 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1192
Pawin Vongmasa36653902018-11-15 00:10:25 -08001193 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001194 int poolMask = GetCodec2PoolMask();
1195 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001196
1197 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001198 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001199 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001200 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1201 API_REFLECTION |
1202 API_VALUES |
1203 API_CURRENT_VALUES |
1204 API_DEPENDENCY |
1205 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001206 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1207 C2StreamSampleRateInfo::input sampleRate(0u);
1208 C2StreamChannelCountInfo::input channelCount(0u);
1209 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001210 std::shared_ptr<C2BlockPool> pool;
1211 {
1212 Mutexed<BlockPools>::Locked pools(mBlockPools);
1213
1214 // set default allocator ID.
1215 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001216 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001217
1218 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1219 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1220 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001221 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001222 std::vector<C2Param *> stackParams({&featuresSetting});
1223 if (audioEncoder) {
1224 stackParams.push_back(&encoderFrameSize);
1225 stackParams.push_back(&sampleRate);
1226 stackParams.push_back(&channelCount);
1227 stackParams.push_back(&pcmEncoding);
1228 } else {
1229 encoderFrameSize.invalidate();
1230 sampleRate.invalidate();
1231 channelCount.invalidate();
1232 pcmEncoding.invalidate();
1233 }
1234 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001235 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1236 C2_DONT_BLOCK,
1237 &params);
1238 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1239 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1240 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001241 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001242 C2PortAllocatorsTuning::input *inputAllocators =
1243 C2PortAllocatorsTuning::input::From(params[0].get());
1244 if (inputAllocators && inputAllocators->flexCount() > 0) {
1245 std::shared_ptr<C2Allocator> allocator;
1246 // verify allocator IDs and resolve default allocator
1247 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1248 if (allocator) {
1249 pools->inputAllocatorId = allocator->getId();
1250 } else {
1251 ALOGD("[%s] component requested invalid input allocator ID %u",
1252 mName, inputAllocators->m.values[0]);
1253 }
1254 }
1255 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001256 if (featuresSetting) {
1257 apiFeatures = featuresSetting.value;
1258 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001259
1260 // TODO: use C2Component wrapper to associate this pool with ourselves
1261 if ((poolMask >> pools->inputAllocatorId) & 1) {
1262 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1263 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1264 mName, pools->inputAllocatorId,
1265 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1266 asString(err), err);
1267 } else {
1268 err = C2_NOT_FOUND;
1269 }
1270 if (err != C2_OK) {
1271 C2BlockPool::local_id_t inputPoolId =
1272 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1273 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1274 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1275 mName, (unsigned long long)inputPoolId,
1276 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1277 asString(err), err);
1278 if (err != C2_OK) {
1279 return NO_MEMORY;
1280 }
1281 }
1282 pools->inputPool = pool;
1283 }
1284
Wonsik Kim51051262018-11-28 13:59:05 -08001285 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001286 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001287 input->inputDelay = inputDelayValue;
1288 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001289 input->numSlots = numInputSlots;
1290 input->extraBuffers.flush();
1291 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001292 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001293 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1294 input->frameReassembler.init(
1295 pool,
1296 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1297 encoderFrameSize.value,
1298 sampleRate.value,
1299 channelCount.value,
1300 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1301 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001302 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1303 // For encrypted content, framework decrypts source buffer (ashmem) into
1304 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001305 if (!buffersBoundToCodec
1306 && !input->frameReassembler
1307 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001308 input->buffers.reset(new SlotInputBuffers(mName));
1309 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001310 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001311 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001312 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001313 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001314 // This is to ensure buffers do not get released prematurely.
1315 // TODO: handle this without going into array mode
1316 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001317 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001318 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001319 }
1320 } else {
1321 if (hasCryptoOrDescrambler()) {
1322 int32_t capacity = kLinearBufferSize;
1323 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1324 if ((size_t)capacity > kMaxLinearBufferSize) {
1325 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1326 capacity = kMaxLinearBufferSize;
1327 }
1328 if (mDealer == nullptr) {
1329 mDealer = new MemoryDealer(
1330 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001331 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001332 "EncryptedLinearInputBuffers");
1333 mDecryptDestination = mDealer->allocate((size_t)capacity);
1334 }
1335 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001336 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1337 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001338 } else {
1339 mHeapSeqNum = -1;
1340 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001341 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001342 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001343 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001344 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001345 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001346 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001347 }
1348 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001349 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001350
1351 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001352 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001353 } else {
1354 // TODO: error
1355 }
Wonsik Kim51051262018-11-28 13:59:05 -08001356
1357 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001358 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001359 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001360 }
1361
1362 if (outputFormat != nullptr) {
1363 sp<IGraphicBufferProducer> outputSurface;
1364 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001365 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001366 {
1367 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001368 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001369 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001370 outputSurface = output->surface ?
1371 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001372 if (outputSurface) {
1373 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1374 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001375 outputGeneration = output->generation;
1376 }
1377
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001378 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001379 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001380 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001381
1382 {
1383 Mutexed<BlockPools>::Locked pools(mBlockPools);
1384
David Stevensc3fbb282021-01-18 18:11:20 +09001385 prevOutputPoolId = pools->outputPoolId;
1386
Pawin Vongmasa36653902018-11-15 00:10:25 -08001387 // set default allocator ID.
1388 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001389 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001390
1391 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1392 // unsuccessful.
1393 std::vector<std::unique_ptr<C2Param>> params;
1394 err = mComponent->query({ },
1395 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1396 C2_DONT_BLOCK,
1397 &params);
1398 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1399 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1400 mName, params.size(), asString(err), err);
1401 } else if (err == C2_OK && params.size() == 1) {
1402 C2PortAllocatorsTuning::output *outputAllocators =
1403 C2PortAllocatorsTuning::output::From(params[0].get());
1404 if (outputAllocators && outputAllocators->flexCount() > 0) {
1405 std::shared_ptr<C2Allocator> allocator;
1406 // verify allocator IDs and resolve default allocator
1407 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1408 if (allocator) {
1409 pools->outputAllocatorId = allocator->getId();
1410 } else {
1411 ALOGD("[%s] component requested invalid output allocator ID %u",
1412 mName, outputAllocators->m.values[0]);
1413 }
1414 }
1415 }
1416
1417 // use bufferqueue if outputting to a surface.
1418 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1419 // if unsuccessful.
1420 if (outputSurface) {
1421 params.clear();
1422 err = mComponent->query({ },
1423 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1424 C2_DONT_BLOCK,
1425 &params);
1426 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1427 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1428 mName, params.size(), asString(err), err);
1429 } else if (err == C2_OK && params.size() == 1) {
1430 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1431 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1432 if (surfaceAllocator) {
1433 std::shared_ptr<C2Allocator> allocator;
1434 // verify allocator IDs and resolve default allocator
1435 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1436 if (allocator) {
1437 pools->outputAllocatorId = allocator->getId();
1438 } else {
1439 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1440 mName, surfaceAllocator->value);
1441 err = C2_BAD_VALUE;
1442 }
1443 }
1444 }
1445 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1446 && err != C2_OK
1447 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1448 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1449 }
1450 }
1451
1452 if ((poolMask >> pools->outputAllocatorId) & 1) {
1453 err = mComponent->createBlockPool(
1454 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1455 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1456 mName, pools->outputAllocatorId,
1457 (unsigned long long)pools->outputPoolId,
1458 asString(err));
1459 } else {
1460 err = C2_NOT_FOUND;
1461 }
1462 if (err != C2_OK) {
1463 // use basic pool instead
1464 pools->outputPoolId =
1465 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1466 }
1467
1468 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1469 // component.
1470 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1471 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1472
1473 std::vector<std::unique_ptr<C2SettingResult>> failures;
1474 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1475 ALOGD("[%s] Configured output block pool ids %llu => %s",
1476 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1477 outputPoolId_ = pools->outputPoolId;
1478 }
1479
David Stevensc3fbb282021-01-18 18:11:20 +09001480 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1481 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1482 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1483 if (err != C2_OK) {
1484 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1485 (unsigned long long) prevOutputPoolId, asString(err), err);
1486 }
1487 }
1488
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001489 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001490 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001491 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001492 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001493 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001494 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001495 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001496 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001497 }
1498 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001499 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001500 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001501 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001502
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001503 output->buffers->clearStash();
1504 if (reorderDepth) {
1505 output->buffers->setReorderDepth(reorderDepth.value);
1506 }
1507 if (reorderKey) {
1508 output->buffers->setReorderKey(reorderKey.value);
1509 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001510
1511 // Try to set output surface to created block pool if given.
1512 if (outputSurface) {
1513 mComponent->setOutputSurface(
1514 outputPoolId_,
1515 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001516 outputGeneration,
1517 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001518 } else {
1519 // configure CPU read consumer usage
1520 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1521 std::vector<std::unique_ptr<C2SettingResult>> failures;
1522 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1523 // do not print error message for now as most components may not yet
1524 // support this setting
1525 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1526 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001527 }
1528
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001529 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001530 if (buffersBoundToCodec) {
1531 // WORKAROUND: if we're using early CSD workaround we convert to
1532 // array mode, to appease apps assuming the output
1533 // buffers to be of the same size.
1534 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1535 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001536
1537 int32_t channelCount;
1538 int32_t sampleRate;
1539 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1540 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1541 int32_t delay = 0;
1542 int32_t padding = 0;;
1543 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1544 delay = 0;
1545 }
1546 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1547 padding = 0;
1548 }
1549 if (delay || padding) {
1550 // We need write access to the buffers, and we're already in
1551 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001552 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001553 }
1554 }
1555 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001556
1557 int32_t tunneled = 0;
1558 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1559 tunneled = 0;
1560 }
1561 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001562 }
1563
1564 // Set up pipeline control. This has to be done after mInputBuffers and
1565 // mOutputBuffers are initialized to make sure that lingering callbacks
1566 // about buffers from the previous generation do not interfere with the
1567 // newly initialized pipeline capacity.
1568
Wonsik Kim62545252021-01-20 11:25:41 -08001569 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001570 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001571 watcher->inputDelay(inputDelayValue)
1572 .pipelineDelay(pipelineDelayValue)
1573 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001574 .smoothnessFactor(kSmoothnessFactor);
1575 watcher->flush();
1576 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001577
1578 mInputMetEos = false;
1579 mSync.start();
1580 return OK;
1581}
1582
Wonsik Kim34b28b42022-05-20 15:49:32 -07001583status_t CCodecBufferChannel::prepareInitialInputBuffers(
1584 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001585 if (mInputSurface) {
1586 return OK;
1587 }
1588
Wonsik Kim34b28b42022-05-20 15:49:32 -07001589 size_t numInputSlots = mInput.lock()->numSlots;
1590
1591 {
1592 Mutexed<Input>::Locked input(mInput);
1593 while (clientInputBuffers->size() < numInputSlots) {
1594 size_t index;
1595 sp<MediaCodecBuffer> buffer;
1596 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1597 break;
1598 }
1599 clientInputBuffers->emplace(index, buffer);
1600 }
1601 }
1602 if (clientInputBuffers->empty()) {
1603 ALOGW("[%s] start: cannot allocate memory at all", mName);
1604 return NO_MEMORY;
1605 } else if (clientInputBuffers->size() < numInputSlots) {
1606 ALOGD("[%s] start: cannot allocate memory for all slots, "
1607 "only %zu buffers allocated",
1608 mName, clientInputBuffers->size());
1609 } else {
1610 ALOGV("[%s] %zu initial input buffers available",
1611 mName, clientInputBuffers->size());
1612 }
1613 return OK;
1614}
1615
1616status_t CCodecBufferChannel::requestInitialInputBuffers(
1617 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001618 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001619 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1620 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1621 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001622 return UNKNOWN_ERROR;
1623 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001624
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001625 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1626 mFlushedConfigs.lock()->swap(flushedConfigs);
1627 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001628 {
1629 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1630 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1631 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1632 watcher->onWorkQueued(
1633 work->input.ordinal.frameIndex.peeku(),
1634 std::vector(work->input.buffers),
1635 now);
1636 }
1637 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001638 err = mComponent->queue(&flushedConfigs);
1639 if (err != C2_OK) {
1640 ALOGW("[%s] Error while queueing a flushed config", mName);
1641 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001642 }
1643 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001644 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001645 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1646 !clientInputBuffers.empty()) {
1647 size_t minIndex = clientInputBuffers.begin()->first;
1648 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1649 for (const auto &[index, buffer] : clientInputBuffers) {
1650 if (minBuffer->capacity() > buffer->capacity()) {
1651 minIndex = index;
1652 minBuffer = buffer;
1653 }
1654 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001655 // WORKAROUND: Some apps expect CSD available without queueing
1656 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001657 minBuffer->setRange(0, 0);
1658 minBuffer->meta()->clear();
1659 minBuffer->meta()->setInt64("timeUs", 0);
1660 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001661 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1662 mName);
1663 return UNKNOWN_ERROR;
1664 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001665 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001666 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001667
Wonsik Kim34b28b42022-05-20 15:49:32 -07001668 for (const auto &[index, buffer] : clientInputBuffers) {
1669 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001670 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001671
Pawin Vongmasa36653902018-11-15 00:10:25 -08001672 return OK;
1673}
1674
1675void CCodecBufferChannel::stop() {
1676 mSync.stop();
1677 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001678}
1679
Sungtak Lee99144332023-01-26 11:03:14 +00001680void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
1681 sp<Surface> surface = mOutputSurface.lock()->surface;
1682 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00001683 C2BlockPool::local_id_t outputPoolId;
1684 {
1685 Mutexed<BlockPools>::Locked pools(mBlockPools);
1686 outputPoolId = pools->outputPoolId;
1687 }
1688 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00001689
1690 if (pushBlankBuffer) {
1691 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
1692 if (anw) {
1693 pushBlankBuffersToNativeWindow(anw.get());
1694 }
1695 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00001696 }
1697}
1698
Wonsik Kim936a89c2020-05-08 16:07:50 -07001699void CCodecBufferChannel::reset() {
1700 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001701 if (mInputSurface != nullptr) {
1702 mInputSurface.reset();
1703 }
1704 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001705 {
1706 Mutexed<Input>::Locked input(mInput);
1707 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001708 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001709 }
1710 {
1711 Mutexed<Output>::Locked output(mOutput);
1712 output->buffers.reset();
1713 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001714 // reset the frames that are being tracked for onFrameRendered callbacks
1715 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001716}
1717
1718void CCodecBufferChannel::release() {
1719 mComponent.reset();
1720 mInputAllocator.reset();
1721 mOutputSurface.lock()->surface.clear();
1722 {
1723 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1724 blockPools->inputPool.reset();
1725 blockPools->outputPoolIntf.reset();
1726 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001727 setCrypto(nullptr);
1728 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001729}
1730
Pawin Vongmasa36653902018-11-15 00:10:25 -08001731void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1732 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001733 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001734 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001735 {
1736 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1737 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1738 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1739 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1740 watcher->onWorkDone(frameIndex);
1741 continue;
1742 }
1743 if (work->input.buffers.empty()
1744 || work->input.buffers.front() == nullptr
1745 || work->input.buffers.front()->data().linearBlocks().empty()) {
1746 ALOGD("[%s] no linear codec config data found", mName);
1747 watcher->onWorkDone(frameIndex);
1748 continue;
1749 }
1750 std::unique_ptr<C2Work> copy(new C2Work);
1751 copy->input.flags = C2FrameData::flags_t(
1752 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1753 copy->input.ordinal = work->input.ordinal;
1754 copy->input.ordinal.frameIndex = mFrameIndex++;
1755 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1756 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1757 }
1758 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1759 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1760 }
1761 copy->input.infoBuffers.insert(
1762 copy->input.infoBuffers.begin(),
1763 work->input.infoBuffers.begin(),
1764 work->input.infoBuffers.end());
1765 copy->worklets.emplace_back(new C2Worklet);
1766 configs.push_back(std::move(copy));
1767 watcher->onWorkDone(frameIndex);
1768 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001769 }
1770 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001771 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001772 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001773 Mutexed<Input>::Locked input(mInput);
1774 input->buffers->flush();
1775 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001776 }
1777 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001778 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001779 if (output->buffers) {
1780 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001781 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001782 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001783 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001784 // reset the frames that are being tracked for onFrameRendered callbacks
1785 mTrackedFrames.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001786}
1787
1788void CCodecBufferChannel::onWorkDone(
1789 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001790 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001791 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001792 feedInputBufferIfAvailable();
1793 }
1794}
1795
1796void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001797 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001798 if (mInputSurface) {
1799 return;
1800 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001801 std::shared_ptr<C2Buffer> buffer =
1802 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001803 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001804 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001805 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001806 if (input->lastFlushIndex >= frameIndex) {
1807 ALOGD("[%s] Ignoring stale input buffer done callback: "
1808 "last flush index = %lld, frameIndex = %lld",
1809 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1810 } else {
1811 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1812 if (!newInputSlotAvailable) {
1813 (void)input->extraBuffers.expireComponentBuffer(buffer);
1814 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001815 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001816 }
1817 if (newInputSlotAvailable) {
1818 feedInputBufferIfAvailable();
1819 }
1820}
1821
1822bool CCodecBufferChannel::handleWork(
1823 std::unique_ptr<C2Work> work,
1824 const sp<AMessage> &outputFormat,
1825 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001826 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001827 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001828 if (!output->buffers) {
1829 return false;
1830 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001831 }
1832
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001833 // Whether the output buffer should be reported to the client or not.
1834 bool notifyClient = false;
1835
1836 if (work->result == C2_OK){
1837 notifyClient = true;
1838 } else if (work->result == C2_NOT_FOUND) {
1839 ALOGD("[%s] flushed work; ignored.", mName);
1840 } else {
1841 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1842 // the config update.
1843 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1844 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1845 return false;
1846 }
1847
1848 if ((work->input.ordinal.frameIndex -
1849 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001850 // Discard frames from previous generation.
1851 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001852 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001853 }
1854
Wonsik Kim524b0582019-03-12 11:28:57 -07001855 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001856 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001857 || !(work->worklets.front()->output.flags &
1858 C2FrameData::FLAG_INCOMPLETE))) {
1859 mPipelineWatcher.lock()->onWorkDone(
1860 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001861 }
1862
1863 // NOTE: MediaCodec usage supposedly have only one worklet
1864 if (work->worklets.size() != 1u) {
1865 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1866 mName, work->worklets.size());
1867 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1868 return false;
1869 }
1870
1871 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1872
1873 std::shared_ptr<C2Buffer> buffer;
1874 // NOTE: MediaCodec usage supposedly have only one output stream.
1875 if (worklet->output.buffers.size() > 1u) {
1876 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1877 mName, worklet->output.buffers.size());
1878 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1879 return false;
1880 } else if (worklet->output.buffers.size() == 1u) {
1881 buffer = worklet->output.buffers[0];
1882 if (!buffer) {
1883 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1884 }
1885 }
1886
Wonsik Kim3dedf682021-05-03 10:57:09 -07001887 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1888 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001889 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001890 while (!worklet->output.configUpdate.empty()) {
1891 std::unique_ptr<C2Param> param;
1892 worklet->output.configUpdate.back().swap(param);
1893 worklet->output.configUpdate.pop_back();
1894 switch (param->coreIndex().coreIndex()) {
1895 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1896 C2PortReorderBufferDepthTuning::output reorderDepth;
1897 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001898 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1899 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001900 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001901 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001902 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001903 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1904 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001905 }
1906 break;
1907 }
1908 case C2PortReorderKeySetting::CORE_INDEX: {
1909 C2PortReorderKeySetting::output reorderKey;
1910 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001911 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001912 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1913 mName, reorderKey.value);
1914 } else {
1915 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1916 }
1917 break;
1918 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001919 case C2PortActualDelayTuning::CORE_INDEX: {
1920 if (param->isGlobal()) {
1921 C2ActualPipelineDelayTuning pipelineDelay;
1922 if (pipelineDelay.updateFrom(*param)) {
1923 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1924 mName, pipelineDelay.value);
1925 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001926 (void)mPipelineWatcher.lock()->pipelineDelay(
1927 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001928 }
1929 }
1930 if (param->forInput()) {
1931 C2PortActualDelayTuning::input inputDelay;
1932 if (inputDelay.updateFrom(*param)) {
1933 ALOGV("[%s] onWorkDone: updating input delay %u",
1934 mName, inputDelay.value);
1935 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001936 (void)mPipelineWatcher.lock()->inputDelay(
1937 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001938 }
1939 }
1940 if (param->forOutput()) {
1941 C2PortActualDelayTuning::output outputDelay;
1942 if (outputDelay.updateFrom(*param)) {
1943 ALOGV("[%s] onWorkDone: updating output delay %u",
1944 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001945 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001946 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001947 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001948
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001949 }
1950 }
1951 break;
1952 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001953 case C2PortTunnelSystemTime::CORE_INDEX: {
1954 C2PortTunnelSystemTime::output frameRenderTime;
1955 if (frameRenderTime.updateFrom(*param)) {
1956 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1957 mName, (long long)frameRenderTime.value,
1958 (long long)worklet->output.ordinal.timestamp.peekll());
1959 mCCodecCallback->onOutputFramesRendered(
1960 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1961 }
1962 break;
1963 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001964 case C2StreamTunnelHoldRender::CORE_INDEX: {
1965 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1966 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1967 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1968 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1969 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1970 mCCodecCallback->onFirstTunnelFrameReady();
1971 break;
1972 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001973 default:
1974 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1975 mName, param->index());
1976 break;
1977 }
1978 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001979 if (newInputDelay || newPipelineDelay) {
1980 Mutexed<Input>::Locked input(mInput);
1981 size_t newNumSlots =
1982 newInputDelay.value_or(input->inputDelay) +
1983 newPipelineDelay.value_or(input->pipelineDelay) +
1984 kSmoothnessFactor;
1985 if (input->buffers->isArrayMode()) {
1986 if (input->numSlots >= newNumSlots) {
1987 input->numExtraSlots = 0;
1988 } else {
1989 input->numExtraSlots = newNumSlots - input->numSlots;
1990 }
1991 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1992 mName, input->numExtraSlots);
1993 } else {
1994 input->numSlots = newNumSlots;
1995 }
1996 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001997 size_t numOutputSlots = 0;
1998 uint32_t reorderDepth = 0;
1999 bool outputBuffersChanged = false;
2000 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2001 Mutexed<Output>::Locked output(mOutput);
2002 if (!output->buffers) {
2003 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002004 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002005 numOutputSlots = output->numSlots;
2006 if (newReorderKey) {
2007 output->buffers->setReorderKey(newReorderKey.value());
2008 }
2009 if (newReorderDepth) {
2010 output->buffers->setReorderDepth(newReorderDepth.value());
2011 }
2012 reorderDepth = output->buffers->getReorderDepth();
2013 if (newOutputDelay) {
2014 output->outputDelay = newOutputDelay.value();
2015 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2016 if (output->numSlots < numOutputSlots) {
2017 output->numSlots = numOutputSlots;
2018 if (output->buffers->isArrayMode()) {
2019 OutputBuffersArray *array =
2020 (OutputBuffersArray *)output->buffers.get();
2021 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2022 mName, numOutputSlots);
2023 array->grow(numOutputSlots);
2024 outputBuffersChanged = true;
2025 }
2026 }
2027 }
2028 numOutputSlots = output->numSlots;
2029 }
2030 if (outputBuffersChanged) {
2031 mCCodecCallback->onOutputBuffersChanged();
2032 }
2033 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002034 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002035 {
2036 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2037 maxDequeueCount = output->maxDequeueBuffers =
2038 numOutputSlots + reorderDepth + kRenderingDepth;
2039 if (output->surface) {
2040 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2041 }
2042 }
2043 if (maxDequeueCount > 0) {
2044 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002045 }
2046 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002047
Pawin Vongmasa36653902018-11-15 00:10:25 -08002048 int32_t flags = 0;
2049 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002050 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002051 ALOGV("[%s] onWorkDone: output EOS", mName);
2052 }
2053
Pawin Vongmasa36653902018-11-15 00:10:25 -08002054 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2055 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2056 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2057 // shall correspond to the client input timesamp (in customOrdinal). By using the
2058 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2059 // produces multiple output.
2060 c2_cntr64_t timestamp =
2061 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2062 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002063 if (mInputSurface != nullptr) {
2064 // When using input surface we need to restore the original input timestamp.
2065 timestamp = work->input.ordinal.customOrdinal;
2066 }
My Name6bd9a7d2022-03-25 12:37:58 -07002067 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2068 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002069 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2070 mName,
2071 work->input.ordinal.customOrdinal.peekll(),
2072 work->input.ordinal.timestamp.peekll(),
2073 worklet->output.ordinal.timestamp.peekll(),
2074 timestamp.peekll());
2075
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002076 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002077 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002078 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002079 if (output->buffers && outputFormat) {
2080 output->buffers->updateSkipCutBuffer(outputFormat);
2081 output->buffers->setFormat(outputFormat);
2082 }
2083 if (!notifyClient) {
2084 return false;
2085 }
2086 size_t index;
2087 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07002088 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002089 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002090 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002091 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2092
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002093 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002094 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002095 } else {
2096 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002097 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002098 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002099 return false;
2100 }
2101 }
2102
Wonsik Kimec585c32021-10-01 01:11:00 -07002103 bool drop = false;
2104 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2105 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2106 drop = true;
2107 }
2108
Marc Kassisec910342022-11-25 11:43:05 +01002109 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2110 // HAL, the flag is then removed in the corresponding output buffer.
2111 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2112 flags |= BUFFER_FLAG_DECODE_ONLY;
2113 }
2114
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002115 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002116 if (mTunneled && drop && outputFormat) {
2117 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2118 mName, work->input.ordinal.frameIndex.peekull());
2119 } else {
2120 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2121 mName, work->input.ordinal.frameIndex.peekull());
2122 notifyClient = false;
2123 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002124 }
2125
2126 if (buffer) {
2127 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2128 // TODO: properly translate these to metadata
2129 switch (info->coreIndex().coreIndex()) {
2130 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002131 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002132 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002133 }
2134 break;
2135 default:
2136 break;
2137 }
2138 }
2139 }
2140
2141 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002142 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002143 if (!output->buffers) {
2144 return false;
2145 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002146 output->buffers->pushToStash(
2147 buffer,
2148 notifyClient,
2149 timestamp.peek(),
2150 flags,
2151 outputFormat,
2152 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002153 }
2154 sendOutputBuffers();
2155 return true;
2156}
2157
2158void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002159 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002160 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002161 sp<MediaCodecBuffer> outBuffer;
2162 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002163
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002164 constexpr int kMaxReallocTry = 5;
2165 int reallocTryNum = 0;
2166
Pawin Vongmasa36653902018-11-15 00:10:25 -08002167 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002168 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002169 if (!output->buffers) {
2170 return;
2171 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002172 action = output->buffers->popFromStashAndRegister(
2173 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002174 if (action != OutputBuffers::REALLOCATE) {
2175 reallocTryNum = 0;
2176 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002177 switch (action) {
2178 case OutputBuffers::SKIP:
2179 return;
2180 case OutputBuffers::DISCARD:
2181 break;
2182 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00002183 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002184 mCallback->onOutputBufferAvailable(index, outBuffer);
2185 break;
2186 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002187 if (++reallocTryNum > kMaxReallocTry) {
2188 output.unlock();
2189 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2190 mName, kMaxReallocTry);
2191 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2192 return;
2193 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002194 if (!output->buffers->isArrayMode()) {
2195 output->buffers =
2196 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002197 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002198 static_cast<OutputBuffersArray*>(output->buffers.get())->
2199 realloc(c2Buffer);
2200 output.unlock();
2201 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002202 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002203 case OutputBuffers::RETRY:
2204 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2205 mName);
2206 return;
2207 default:
2208 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2209 "corrupted BufferAction value (%d) "
2210 "returned from popFromStashAndRegister.",
2211 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002212 return;
2213 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002214 }
2215}
2216
Sungtak Lee99144332023-01-26 11:03:14 +00002217status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002218 static std::atomic_uint32_t surfaceGeneration{0};
2219 uint32_t generation = (getpid() << 10) |
2220 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2221 & ((1 << 10) - 1));
2222
2223 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002224 int maxDequeueCount;
2225 sp<Surface> oldSurface;
2226 {
2227 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2228 maxDequeueCount = outputSurface->maxDequeueBuffers;
2229 oldSurface = outputSurface->surface;
2230 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002231 if (newSurface) {
2232 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002233 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002234 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002235 producer = newSurface->getIGraphicBufferProducer();
2236 producer->setGenerationNumber(generation);
2237 } else {
2238 ALOGE("[%s] setting output surface to null", mName);
2239 return INVALID_OPERATION;
2240 }
2241
2242 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2243 C2BlockPool::local_id_t outputPoolId;
2244 {
2245 Mutexed<BlockPools>::Locked pools(mBlockPools);
2246 outputPoolId = pools->outputPoolId;
2247 outputPoolIntf = pools->outputPoolIntf;
2248 }
2249
2250 if (outputPoolIntf) {
2251 if (mComponent->setOutputSurface(
2252 outputPoolId,
2253 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002254 generation,
2255 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002256 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2257 return INVALID_OPERATION;
2258 }
2259 }
2260
2261 {
2262 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2263 output->surface = newSurface;
2264 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002265 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002266 }
2267
Sungtak Lee99144332023-01-26 11:03:14 +00002268 if (oldSurface && pushBlankBuffer) {
2269 // When ReleaseSurface was set from MediaCodec,
2270 // pushing a blank buffer at the end might be necessary.
2271 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2272 if (anw) {
2273 pushBlankBuffersToNativeWindow(anw.get());
2274 }
2275 }
2276
Pawin Vongmasa36653902018-11-15 00:10:25 -08002277 return OK;
2278}
2279
Wonsik Kimab34ed62019-01-31 15:28:46 -08002280PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002281 // Otherwise, component may have stalled work due to input starvation up to
2282 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002283 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2284 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002285 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002286 size_t outputDelay = mOutput.lock()->outputDelay;
2287 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002288 Mutexed<Input>::Locked input(mInput);
2289 n = input->inputDelay + input->pipelineDelay + outputDelay;
2290 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002291 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002292}
2293
Pawin Vongmasa36653902018-11-15 00:10:25 -08002294void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2295 mMetaMode = mode;
2296}
2297
Wonsik Kim596187e2019-10-25 12:44:10 -07002298void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002299 if (mCrypto != nullptr) {
2300 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2301 mCrypto->unsetHeap(entry.second);
2302 }
2303 mHeapSeqNumMap.clear();
2304 if (mHeapSeqNum >= 0) {
2305 mCrypto->unsetHeap(mHeapSeqNum);
2306 mHeapSeqNum = -1;
2307 }
2308 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002309 mCrypto = crypto;
2310}
2311
2312void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2313 mDescrambler = descrambler;
2314}
2315
Pawin Vongmasa36653902018-11-15 00:10:25 -08002316status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2317 // C2_OK is always translated to OK.
2318 if (c2s == C2_OK) {
2319 return OK;
2320 }
2321
2322 // Operation-dependent translation
2323 // TODO: Add as necessary
2324 switch (c2op) {
2325 case C2_OPERATION_Component_start:
2326 switch (c2s) {
2327 case C2_NO_MEMORY:
2328 return NO_MEMORY;
2329 default:
2330 return UNKNOWN_ERROR;
2331 }
2332 default:
2333 break;
2334 }
2335
2336 // Backup operation-agnostic translation
2337 switch (c2s) {
2338 case C2_BAD_INDEX:
2339 return BAD_INDEX;
2340 case C2_BAD_VALUE:
2341 return BAD_VALUE;
2342 case C2_BLOCKING:
2343 return WOULD_BLOCK;
2344 case C2_DUPLICATE:
2345 return ALREADY_EXISTS;
2346 case C2_NO_INIT:
2347 return NO_INIT;
2348 case C2_NO_MEMORY:
2349 return NO_MEMORY;
2350 case C2_NOT_FOUND:
2351 return NAME_NOT_FOUND;
2352 case C2_TIMED_OUT:
2353 return TIMED_OUT;
2354 case C2_BAD_STATE:
2355 case C2_CANCELED:
2356 case C2_CANNOT_DO:
2357 case C2_CORRUPTED:
2358 case C2_OMITTED:
2359 case C2_REFUSED:
2360 return UNKNOWN_ERROR;
2361 default:
2362 return -static_cast<status_t>(c2s);
2363 }
2364}
2365
Pawin Vongmasa36653902018-11-15 00:10:25 -08002366} // namespace android