blob: d2df4f3eb842c06cfb309d9578e0cd242b00da2f [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,
Arun Johnson634d0802023-02-14 22:07:51 +0000429 const sp<MediaCodecBuffer> &buffer,
430 AString* errorDetailMsg) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800431 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
432 static const C2MemoryUsage kDefaultReadWriteUsage{
433 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
434
435 size_t size = 0;
436 for (size_t i = 0; i < numSubSamples; ++i) {
437 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
438 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700439 if (size == 0) {
440 buffer->setRange(0, 0);
441 return OK;
442 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800443 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
444 std::shared_ptr<C2LinearBlock> block;
445 c2_status_t err = pool->fetchLinearBlock(
446 size,
447 secure ? kSecureUsage : kDefaultReadWriteUsage,
448 &block);
449 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700450 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
451 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800452 return NO_MEMORY;
453 }
454 if (!secure) {
455 ensureDecryptDestination(size);
456 }
457 ssize_t result = -1;
458 ssize_t codecDataOffset = 0;
459 if (mCrypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800460 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,
Arun Johnson634d0802023-02-14 22:07:51 +0000473 dst, errorDetailMsg);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800474 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 });
Arun Johnson634d0802023-02-14 22:07:51 +0000518 if (errorDetailMsg) {
519 errorDetailMsg->setTo(detailedError.c_str(), detailedError.size());
520 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800521 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
522 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
523 mName, returnVoid.description().c_str(), status, result);
524 return UNKNOWN_ERROR;
525 }
526
527 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700528 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
529 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800530 return BAD_VALUE;
531 }
532 }
533 if (!secure) {
534 C2WriteView view = block->map().get();
535 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700536 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
537 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800538 return UNKNOWN_ERROR;
539 }
540 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700541 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
542 "(non-secure)",
543 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800544 return UNKNOWN_ERROR;
545 }
546 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
547 }
548 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
549 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
550 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700551 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800552 return -ENOSYS;
553 }
554 return OK;
555}
556
Pawin Vongmasa36653902018-11-15 00:10:25 -0800557status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
558 QueueGuard guard(mSync);
559 if (!guard.isRunning()) {
560 ALOGD("[%s] No more buffers should be queued at current state.", mName);
561 return -ENOSYS;
562 }
563 return queueInputBufferInternal(buffer);
564}
565
566status_t CCodecBufferChannel::queueSecureInputBuffer(
567 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
568 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
569 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
570 AString *errorDetailMsg) {
571 QueueGuard guard(mSync);
572 if (!guard.isRunning()) {
573 ALOGD("[%s] No more buffers should be queued at current state.", mName);
574 return -ENOSYS;
575 }
576
577 if (!hasCryptoOrDescrambler()) {
578 return -ENOSYS;
579 }
580 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
581
Sungtak Lee04b30352020-07-27 13:57:25 -0700582 std::shared_ptr<C2LinearBlock> block;
583 size_t allocSize = buffer->size();
584 size_t bufferSize = 0;
585 c2_status_t blockRes = C2_OK;
586 bool copied = false;
587 if (mSendEncryptedInfoBuffer) {
588 static const C2MemoryUsage kDefaultReadWriteUsage{
589 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
590 constexpr int kAllocGranule0 = 1024 * 64;
591 constexpr int kAllocGranule1 = 1024 * 1024;
592 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
593 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
594 if (allocSize <= kAllocGranule1) {
595 bufferSize = align(allocSize, kAllocGranule0);
596 } else {
597 bufferSize = align(allocSize, kAllocGranule1);
598 }
599 blockRes = pool->fetchLinearBlock(
600 bufferSize, kDefaultReadWriteUsage, &block);
601
602 if (blockRes == C2_OK) {
603 C2WriteView view = block->map().get();
604 if (view.error() == C2_OK && view.size() == bufferSize) {
605 copied = true;
606 // TODO: only copy clear sections
607 memcpy(view.data(), buffer->data(), allocSize);
608 }
609 }
610 }
611
612 if (!copied) {
613 block.reset();
614 }
615
Pawin Vongmasa36653902018-11-15 00:10:25 -0800616 ssize_t result = -1;
617 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700618 if (numSubSamples == 1
619 && subSamples[0].mNumBytesOfClearData == 0
620 && subSamples[0].mNumBytesOfEncryptedData == 0) {
621 // We don't need to go through crypto or descrambler if the input is empty.
622 result = 0;
623 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700624 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800625 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700626 destination.type = DrmBufferType::NATIVE_HANDLE;
627 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800628 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700629 destination.type = DrmBufferType::SHARED_MEMORY;
630 IMemoryToSharedBuffer(
631 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800632 }
Robert Shih895fba92019-07-16 16:29:44 -0700633 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800634 encryptedBuffer->fillSourceBuffer(&source);
635 result = mCrypto->decrypt(
636 key, iv, mode, pattern, source, buffer->offset(),
637 subSamples, numSubSamples, destination, errorDetailMsg);
638 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700639 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800640 return result;
641 }
Robert Shih895fba92019-07-16 16:29:44 -0700642 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800643 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
644 }
645 } else {
646 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
647 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
648 hidl_vec<SubSample> hidlSubSamples;
649 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
650
651 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
652 encryptedBuffer->fillSourceBuffer(&srcBuffer);
653
654 DestinationBuffer dstBuffer;
655 if (secure) {
656 dstBuffer.type = BufferType::NATIVE_HANDLE;
657 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
658 } else {
659 dstBuffer.type = BufferType::SHARED_MEMORY;
660 dstBuffer.nonsecureMemory = srcBuffer;
661 }
662
663 CasStatus status = CasStatus::OK;
664 hidl_string detailedError;
665 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
666
667 if (key != nullptr) {
668 sctrl = (ScramblingControl)key[0];
669 // Adjust for the PES offset
670 codecDataOffset = key[2] | (key[3] << 8);
671 }
672
673 auto returnVoid = mDescrambler->descramble(
674 sctrl,
675 hidlSubSamples,
676 srcBuffer,
677 0,
678 dstBuffer,
679 0,
680 [&status, &result, &detailedError] (
681 CasStatus _status, uint32_t _bytesWritten,
682 const hidl_string& _detailedError) {
683 status = _status;
684 result = (ssize_t)_bytesWritten;
685 detailedError = _detailedError;
686 });
687
688 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
689 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
690 mName, returnVoid.description().c_str(), status, result);
691 return UNKNOWN_ERROR;
692 }
693
694 if (result < codecDataOffset) {
695 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
696 return BAD_VALUE;
697 }
698
699 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
700
701 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
702 encryptedBuffer->copyDecryptedContentFromMemory(result);
703 }
704 }
705
706 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700707
708 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800709}
710
711void CCodecBufferChannel::feedInputBufferIfAvailable() {
712 QueueGuard guard(mSync);
713 if (!guard.isRunning()) {
714 ALOGV("[%s] We're not running --- no input buffer reported", mName);
715 return;
716 }
717 feedInputBufferIfAvailableInternal();
718}
719
720void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900721 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800722 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700723 }
724 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700725 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700726 if (!output->buffers ||
727 output->buffers->hasPending() ||
Wonsik Kim0487b782020-10-28 11:45:50 -0700728 output->buffers->numActiveSlots() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800729 return;
730 }
731 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700732 size_t numActiveSlots = 0;
733 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800734 sp<MediaCodecBuffer> inBuffer;
735 size_t index;
736 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700737 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700738 numActiveSlots = input->buffers->numActiveSlots();
739 if (numActiveSlots >= input->numSlots) {
740 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800741 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700742 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800743 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800744 break;
745 }
746 }
747 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
748 mCallback->onInputBufferAvailable(index, inBuffer);
749 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700750 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800751}
752
753status_t CCodecBufferChannel::renderOutputBuffer(
754 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800755 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800756 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800757 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800758 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700759 Mutexed<Output>::Locked output(mOutput);
760 if (output->buffers) {
761 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800762 }
763 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800764 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
765 // set to true.
766 sendOutputBuffers();
767 // input buffer feeding may have been gated by pending output buffers
768 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800769 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800770 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700771 std::call_once(mRenderWarningFlag, [this] {
772 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
773 "timestamp or render=true with non-video buffers. Apps should "
774 "call releaseOutputBuffer() with render=false for those.",
775 mName);
776 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800777 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800778 return INVALID_OPERATION;
779 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800780
781#if 0
782 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
783 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
784 for (const std::shared_ptr<const C2Info> &info : infoParams) {
785 AString res;
786 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
787 if (ix) res.append(", ");
788 res.append(*((int32_t*)info.get() + (ix / 4)));
789 }
790 ALOGV(" [%s]", res.c_str());
791 }
792#endif
793 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
794 std::static_pointer_cast<const C2StreamRotationInfo::output>(
795 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
796 bool flip = rotation && (rotation->flip & 1);
797 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900798
799 {
800 Mutexed<OutputSurface>::Locked output(mOutputSurface);
801 if (output->surface == nullptr) {
802 ALOGI("[%s] cannot render buffer without surface", mName);
803 return OK;
804 }
805 int64_t frameIndex;
806 buffer->meta()->findInt64("frameIndex", &frameIndex);
807 if (output->rotation.count(frameIndex) != 0) {
808 auto it = output->rotation.find(frameIndex);
809 quarters = (it->second / 90) & 3;
810 output->rotation.erase(it);
811 }
812 }
813
Pawin Vongmasa36653902018-11-15 00:10:25 -0800814 uint32_t transform = 0;
815 switch (quarters) {
816 case 0: // no rotation
817 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
818 break;
819 case 1: // 90 degrees counter-clockwise
820 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
821 : HAL_TRANSFORM_ROT_270;
822 break;
823 case 2: // 180 degrees
824 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
825 break;
826 case 3: // 90 degrees clockwise
827 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
828 : HAL_TRANSFORM_ROT_90;
829 break;
830 }
831
832 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
833 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
834 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
835 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
836 if (surfaceScaling) {
837 videoScalingMode = surfaceScaling->value;
838 }
839
840 // Use dataspace from format as it has the default aspects already applied
841 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
842 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
843
844 // HDR static info
845 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
846 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
847 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
848
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800849 // HDR10 plus info
850 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
851 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
852 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800853 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
854 hdr10PlusInfo.reset();
855 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800856
Wonsik Kima79c5522022-01-18 16:29:24 -0800857 // HDR dynamic info
858 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
859 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
860 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
861 // TODO: make this sticky & enable unset
862 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
863 hdrDynamicInfo.reset();
864 }
865
866 if (hdr10PlusInfo) {
867 // C2StreamHdr10PlusInfo is deprecated; components should use
868 // C2StreamHdrDynamicMetadataInfo
869 // TODO: #metric
870 if (hdrDynamicInfo) {
871 // It is unexpected that C2StreamHdr10PlusInfo and
872 // C2StreamHdrDynamicMetadataInfo is both present.
873 // C2StreamHdrDynamicMetadataInfo takes priority.
874 // TODO: #metric
875 } else {
876 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
877 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
878 hdr10PlusInfo->flexCount(),
879 0u,
880 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
881 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
882 hdrDynamicInfo = info;
883 }
884 }
885
Pawin Vongmasa36653902018-11-15 00:10:25 -0800886 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
887 if (blocks.size() != 1u) {
888 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
889 return UNKNOWN_ERROR;
890 }
891 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700892 C2Fence c2fence = block.fence();
893 sp<Fence> fence = Fence::NO_FENCE;
894 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
895 // Once C2Fence::type() is added, check the exact C2Fence type
896 if (c2fence.isHW()) {
897 int fenceFd = c2fence.fd();
898 fence = sp<Fence>::make(fenceFd);
899 if (!fence) {
900 ALOGE("[%s] Failed to allocate a fence", mName);
901 close(fenceFd);
902 return NO_MEMORY;
903 }
904 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800905
906 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -0700907 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800908 timestampNs,
909 false, // droppable
910 dataSpace,
911 Rect(blocks.front().crop().left,
912 blocks.front().crop().top,
913 blocks.front().crop().right(),
914 blocks.front().crop().bottom()),
915 videoScalingMode,
916 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700917 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800918 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800919 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800920 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800921 // If mastering max and min luminance fields are 0, do not use them.
922 // It indicates the value may not be present in the stream.
923 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
924 hdrStaticInfo->mastering.minLuminance > 0.0f) {
925 struct android_smpte2086_metadata smpte2086_meta = {
926 .displayPrimaryRed = {
927 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
928 },
929 .displayPrimaryGreen = {
930 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
931 },
932 .displayPrimaryBlue = {
933 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
934 },
935 .whitePoint = {
936 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
937 },
938 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
939 .minLuminance = hdrStaticInfo->mastering.minLuminance,
940 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800941 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800942 hdr.smpte2086 = smpte2086_meta;
943 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700944 // If the content light level fields are 0, do not use them, it
945 // indicates the value may not be present in the stream.
946 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
947 struct android_cta861_3_metadata cta861_meta = {
948 .maxContentLightLevel = hdrStaticInfo->maxCll,
949 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
950 };
951 hdr.validTypes |= HdrMetadata::CTA861_3;
952 hdr.cta8613 = cta861_meta;
953 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900954
955 // does not have valid info
956 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
957 hdrStaticInfo.reset();
958 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800959 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800960 if (hdrDynamicInfo
961 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800962 hdr.validTypes |= HdrMetadata::HDR10PLUS;
963 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800964 hdrDynamicInfo->m.data,
965 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800966 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800967 qbi.setHdrMetadata(hdr);
968 }
Hongguangfc1478a2022-07-20 22:56:06 -0700969 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
970
Brian Lindahl932bf602023-03-09 11:59:48 -0700971 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
972 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
973 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800974 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
975 if (result != OK) {
976 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800977 if (result == NO_INIT) {
978 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
979 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800980 return result;
981 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800982
983 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
984 ALOGD("[%s] queue buffer successful", mName);
985 } else {
986 ALOGV("[%s] queue buffer successful", mName);
987 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800988
989 int64_t mediaTimeUs = 0;
990 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahl932bf602023-03-09 11:59:48 -0700991 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
992 processRenderedFrames(qbo.frameTimestamps);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800993
994 return OK;
995}
996
Brian Lindahl932bf602023-03-09 11:59:48 -0700997void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
998 int hasPresentFenceTimes = 0;
999 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1000 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
1001 if (mHasPresentFenceTimes) {
1002 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1003 }
1004 mTrackedFrames.clear();
1005}
1006
1007void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1008 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1009 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1010 // so track the frame as if the desired render time is now.
1011 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1012 if (desiredRenderTimeNs < nowNs) {
1013 desiredRenderTimeNs = nowNs;
1014 }
1015 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1016 // actually rendered.
1017 TrackedFrame frame;
1018 frame.number = qbo.nextFrameNumber - 1;
1019 frame.mediaTimeUs = mediaTimeUs;
1020 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1021 frame.latchTime = -1;
1022 frame.presentFence = nullptr;
1023 mTrackedFrames.push_back(frame);
1024}
1025
1026void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1027 // Grab the latch times and present fences from the frame event deltas
1028 for (const auto& delta : deltas) {
1029 for (auto& frame : mTrackedFrames) {
1030 if (delta.getFrameNumber() == frame.number) {
1031 delta.getLatchTime(&frame.latchTime);
1032 delta.getDisplayPresentFence(&frame.presentFence);
1033 }
1034 }
1035 }
1036
1037 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1038 // in fact, been rendered.
1039 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1040 while (!mTrackedFrames.empty()) {
1041 TrackedFrame & frame = mTrackedFrames.front();
1042 // Frames that should have been rendered at least 100ms in the past are checked
1043 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1044 break;
1045 }
1046
1047 // If we don't have a render time by now, then consider the frame as dropped
1048 int64_t renderTimeNs = getRenderTimeNs(frame);
1049 if (renderTimeNs != -1) {
1050 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1051 }
1052 mTrackedFrames.pop_front();
1053 }
1054}
1055
1056int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1057 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1058 if (!mHasPresentFenceTimes) {
1059 if (frame.latchTime == -1) {
1060 ALOGD("no latch time for frame %d", (int) frame.number);
1061 return -1;
1062 }
1063 return frame.latchTime;
1064 }
1065
1066 if (frame.presentFence == nullptr) {
1067 ALOGW("no present fence for frame %d", (int) frame.number);
1068 return -1;
1069 }
1070
1071 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1072
1073 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1074 ALOGW("invalid signal time for frame %d", (int) frame.number);
1075 return -1;
1076 }
1077
1078 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1079 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1080 return -1;
1081 }
1082
1083 return actualRenderTimeNs;
1084}
1085
1086void CCodecBufferChannel::pollForRenderedBuffers() {
1087 FrameEventHistoryDelta delta;
1088 mComponent->pollForRenderedFrames(&delta);
1089 processRenderedFrames(delta);
1090}
1091
Pawin Vongmasa36653902018-11-15 00:10:25 -08001092status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1093 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1094 bool released = false;
1095 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001096 Mutexed<Input>::Locked input(mInput);
1097 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001098 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001099 }
1100 }
1101 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001102 Mutexed<Output>::Locked output(mOutput);
1103 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001104 released = true;
1105 }
1106 }
1107 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001108 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001109 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001110 } else {
1111 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1112 }
1113 return OK;
1114}
1115
1116void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1117 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001118 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001119
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001120 if (!input->buffers) {
1121 ALOGE("getInputBufferArray: No Input Buffers allocated");
1122 return;
1123 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001124 if (!input->buffers->isArrayMode()) {
1125 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001126 }
1127
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001128 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001129}
1130
1131void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1132 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001133 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001134 if (!output->buffers) {
1135 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1136 return;
1137 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001138 if (!output->buffers->isArrayMode()) {
1139 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001140 }
1141
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001142 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001143}
1144
1145status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001146 const sp<AMessage> &inputFormat,
1147 const sp<AMessage> &outputFormat,
1148 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001149 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1150 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001151 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001152 C2PortReorderBufferDepthTuning::output reorderDepth;
1153 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001154 C2PortActualDelayTuning::input inputDelay(0);
1155 C2PortActualDelayTuning::output outputDelay(0);
1156 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001157 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001158
Pawin Vongmasa36653902018-11-15 00:10:25 -08001159 c2_status_t err = mComponent->query(
1160 {
1161 &iStreamFormat,
1162 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001163 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001164 &reorderDepth,
1165 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001166 &inputDelay,
1167 &pipelineDelay,
1168 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001169 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001170 },
1171 {},
1172 C2_DONT_BLOCK,
1173 nullptr);
1174 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001175 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001176 return UNKNOWN_ERROR;
1177 }
1178 } else if (err != C2_OK) {
1179 return UNKNOWN_ERROR;
1180 }
1181
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001182 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1183 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1184 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1185
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001186 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1187 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001188
Pawin Vongmasa36653902018-11-15 00:10:25 -08001189 // TODO: get this from input format
1190 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1191
Sungtak Lee04b30352020-07-27 13:57:25 -07001192 // secure mode is a static parameter (shall not change in the executing state)
1193 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1194
Pawin Vongmasa36653902018-11-15 00:10:25 -08001195 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001196 int poolMask = GetCodec2PoolMask();
1197 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001198
1199 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001200 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001201 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001202 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1203 API_REFLECTION |
1204 API_VALUES |
1205 API_CURRENT_VALUES |
1206 API_DEPENDENCY |
1207 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001208 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1209 C2StreamSampleRateInfo::input sampleRate(0u);
1210 C2StreamChannelCountInfo::input channelCount(0u);
1211 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001212 std::shared_ptr<C2BlockPool> pool;
1213 {
1214 Mutexed<BlockPools>::Locked pools(mBlockPools);
1215
1216 // set default allocator ID.
1217 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001218 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001219
1220 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1221 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1222 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001223 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001224 std::vector<C2Param *> stackParams({&featuresSetting});
1225 if (audioEncoder) {
1226 stackParams.push_back(&encoderFrameSize);
1227 stackParams.push_back(&sampleRate);
1228 stackParams.push_back(&channelCount);
1229 stackParams.push_back(&pcmEncoding);
1230 } else {
1231 encoderFrameSize.invalidate();
1232 sampleRate.invalidate();
1233 channelCount.invalidate();
1234 pcmEncoding.invalidate();
1235 }
1236 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001237 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1238 C2_DONT_BLOCK,
1239 &params);
1240 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1241 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1242 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001243 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001244 C2PortAllocatorsTuning::input *inputAllocators =
1245 C2PortAllocatorsTuning::input::From(params[0].get());
1246 if (inputAllocators && inputAllocators->flexCount() > 0) {
1247 std::shared_ptr<C2Allocator> allocator;
1248 // verify allocator IDs and resolve default allocator
1249 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1250 if (allocator) {
1251 pools->inputAllocatorId = allocator->getId();
1252 } else {
1253 ALOGD("[%s] component requested invalid input allocator ID %u",
1254 mName, inputAllocators->m.values[0]);
1255 }
1256 }
1257 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001258 if (featuresSetting) {
1259 apiFeatures = featuresSetting.value;
1260 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001261
1262 // TODO: use C2Component wrapper to associate this pool with ourselves
1263 if ((poolMask >> pools->inputAllocatorId) & 1) {
1264 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1265 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1266 mName, pools->inputAllocatorId,
1267 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1268 asString(err), err);
1269 } else {
1270 err = C2_NOT_FOUND;
1271 }
1272 if (err != C2_OK) {
1273 C2BlockPool::local_id_t inputPoolId =
1274 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1275 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1276 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1277 mName, (unsigned long long)inputPoolId,
1278 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1279 asString(err), err);
1280 if (err != C2_OK) {
1281 return NO_MEMORY;
1282 }
1283 }
1284 pools->inputPool = pool;
1285 }
1286
Wonsik Kim51051262018-11-28 13:59:05 -08001287 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001288 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001289 input->inputDelay = inputDelayValue;
1290 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001291 input->numSlots = numInputSlots;
1292 input->extraBuffers.flush();
1293 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001294 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001295 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1296 input->frameReassembler.init(
1297 pool,
1298 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1299 encoderFrameSize.value,
1300 sampleRate.value,
1301 channelCount.value,
1302 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1303 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001304 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1305 // For encrypted content, framework decrypts source buffer (ashmem) into
1306 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001307 if (!buffersBoundToCodec
1308 && !input->frameReassembler
1309 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001310 input->buffers.reset(new SlotInputBuffers(mName));
1311 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001312 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001313 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001314 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001315 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001316 // This is to ensure buffers do not get released prematurely.
1317 // TODO: handle this without going into array mode
1318 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001319 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001320 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001321 }
1322 } else {
1323 if (hasCryptoOrDescrambler()) {
1324 int32_t capacity = kLinearBufferSize;
1325 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1326 if ((size_t)capacity > kMaxLinearBufferSize) {
1327 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1328 capacity = kMaxLinearBufferSize;
1329 }
1330 if (mDealer == nullptr) {
1331 mDealer = new MemoryDealer(
1332 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001333 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001334 "EncryptedLinearInputBuffers");
1335 mDecryptDestination = mDealer->allocate((size_t)capacity);
1336 }
1337 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001338 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1339 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001340 } else {
1341 mHeapSeqNum = -1;
1342 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001343 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001344 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001345 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001346 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001347 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001348 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001349 }
1350 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001351 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001352
1353 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001354 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001355 } else {
1356 // TODO: error
1357 }
Wonsik Kim51051262018-11-28 13:59:05 -08001358
1359 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001360 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001361 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001362 }
1363
1364 if (outputFormat != nullptr) {
1365 sp<IGraphicBufferProducer> outputSurface;
1366 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001367 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001368 {
1369 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001370 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001371 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001372 outputSurface = output->surface ?
1373 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001374 if (outputSurface) {
1375 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1376 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001377 outputGeneration = output->generation;
1378 }
1379
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001380 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001381 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001382 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001383
1384 {
1385 Mutexed<BlockPools>::Locked pools(mBlockPools);
1386
David Stevensc3fbb282021-01-18 18:11:20 +09001387 prevOutputPoolId = pools->outputPoolId;
1388
Pawin Vongmasa36653902018-11-15 00:10:25 -08001389 // set default allocator ID.
1390 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001391 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001392
1393 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1394 // unsuccessful.
1395 std::vector<std::unique_ptr<C2Param>> params;
1396 err = mComponent->query({ },
1397 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1398 C2_DONT_BLOCK,
1399 &params);
1400 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1401 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1402 mName, params.size(), asString(err), err);
1403 } else if (err == C2_OK && params.size() == 1) {
1404 C2PortAllocatorsTuning::output *outputAllocators =
1405 C2PortAllocatorsTuning::output::From(params[0].get());
1406 if (outputAllocators && outputAllocators->flexCount() > 0) {
1407 std::shared_ptr<C2Allocator> allocator;
1408 // verify allocator IDs and resolve default allocator
1409 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1410 if (allocator) {
1411 pools->outputAllocatorId = allocator->getId();
1412 } else {
1413 ALOGD("[%s] component requested invalid output allocator ID %u",
1414 mName, outputAllocators->m.values[0]);
1415 }
1416 }
1417 }
1418
1419 // use bufferqueue if outputting to a surface.
1420 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1421 // if unsuccessful.
1422 if (outputSurface) {
1423 params.clear();
1424 err = mComponent->query({ },
1425 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1426 C2_DONT_BLOCK,
1427 &params);
1428 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1429 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1430 mName, params.size(), asString(err), err);
1431 } else if (err == C2_OK && params.size() == 1) {
1432 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1433 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1434 if (surfaceAllocator) {
1435 std::shared_ptr<C2Allocator> allocator;
1436 // verify allocator IDs and resolve default allocator
1437 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1438 if (allocator) {
1439 pools->outputAllocatorId = allocator->getId();
1440 } else {
1441 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1442 mName, surfaceAllocator->value);
1443 err = C2_BAD_VALUE;
1444 }
1445 }
1446 }
1447 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1448 && err != C2_OK
1449 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1450 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1451 }
1452 }
1453
1454 if ((poolMask >> pools->outputAllocatorId) & 1) {
1455 err = mComponent->createBlockPool(
1456 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1457 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1458 mName, pools->outputAllocatorId,
1459 (unsigned long long)pools->outputPoolId,
1460 asString(err));
1461 } else {
1462 err = C2_NOT_FOUND;
1463 }
1464 if (err != C2_OK) {
1465 // use basic pool instead
1466 pools->outputPoolId =
1467 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1468 }
1469
1470 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1471 // component.
1472 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1473 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1474
1475 std::vector<std::unique_ptr<C2SettingResult>> failures;
1476 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1477 ALOGD("[%s] Configured output block pool ids %llu => %s",
1478 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1479 outputPoolId_ = pools->outputPoolId;
1480 }
1481
David Stevensc3fbb282021-01-18 18:11:20 +09001482 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1483 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1484 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1485 if (err != C2_OK) {
1486 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1487 (unsigned long long) prevOutputPoolId, asString(err), err);
1488 }
1489 }
1490
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001491 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001492 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001493 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001494 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001495 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001496 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001497 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001498 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001499 }
1500 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001501 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001502 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001503 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001504
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001505 output->buffers->clearStash();
1506 if (reorderDepth) {
1507 output->buffers->setReorderDepth(reorderDepth.value);
1508 }
1509 if (reorderKey) {
1510 output->buffers->setReorderKey(reorderKey.value);
1511 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001512
1513 // Try to set output surface to created block pool if given.
1514 if (outputSurface) {
1515 mComponent->setOutputSurface(
1516 outputPoolId_,
1517 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001518 outputGeneration,
1519 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001520 } else {
1521 // configure CPU read consumer usage
1522 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1523 std::vector<std::unique_ptr<C2SettingResult>> failures;
1524 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1525 // do not print error message for now as most components may not yet
1526 // support this setting
1527 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1528 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001529 }
1530
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001531 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001532 if (buffersBoundToCodec) {
1533 // WORKAROUND: if we're using early CSD workaround we convert to
1534 // array mode, to appease apps assuming the output
1535 // buffers to be of the same size.
1536 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1537 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001538
1539 int32_t channelCount;
1540 int32_t sampleRate;
1541 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1542 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1543 int32_t delay = 0;
1544 int32_t padding = 0;;
1545 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1546 delay = 0;
1547 }
1548 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1549 padding = 0;
1550 }
1551 if (delay || padding) {
1552 // We need write access to the buffers, and we're already in
1553 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001554 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001555 }
1556 }
1557 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001558
1559 int32_t tunneled = 0;
1560 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1561 tunneled = 0;
1562 }
1563 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001564 }
1565
1566 // Set up pipeline control. This has to be done after mInputBuffers and
1567 // mOutputBuffers are initialized to make sure that lingering callbacks
1568 // about buffers from the previous generation do not interfere with the
1569 // newly initialized pipeline capacity.
1570
Wonsik Kim62545252021-01-20 11:25:41 -08001571 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001572 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001573 watcher->inputDelay(inputDelayValue)
1574 .pipelineDelay(pipelineDelayValue)
1575 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001576 .smoothnessFactor(kSmoothnessFactor);
1577 watcher->flush();
1578 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001579
1580 mInputMetEos = false;
1581 mSync.start();
1582 return OK;
1583}
1584
Wonsik Kim34b28b42022-05-20 15:49:32 -07001585status_t CCodecBufferChannel::prepareInitialInputBuffers(
1586 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001587 if (mInputSurface) {
1588 return OK;
1589 }
1590
Wonsik Kim34b28b42022-05-20 15:49:32 -07001591 size_t numInputSlots = mInput.lock()->numSlots;
1592
1593 {
1594 Mutexed<Input>::Locked input(mInput);
1595 while (clientInputBuffers->size() < numInputSlots) {
1596 size_t index;
1597 sp<MediaCodecBuffer> buffer;
1598 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1599 break;
1600 }
1601 clientInputBuffers->emplace(index, buffer);
1602 }
1603 }
1604 if (clientInputBuffers->empty()) {
1605 ALOGW("[%s] start: cannot allocate memory at all", mName);
1606 return NO_MEMORY;
1607 } else if (clientInputBuffers->size() < numInputSlots) {
1608 ALOGD("[%s] start: cannot allocate memory for all slots, "
1609 "only %zu buffers allocated",
1610 mName, clientInputBuffers->size());
1611 } else {
1612 ALOGV("[%s] %zu initial input buffers available",
1613 mName, clientInputBuffers->size());
1614 }
1615 return OK;
1616}
1617
1618status_t CCodecBufferChannel::requestInitialInputBuffers(
1619 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001620 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001621 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1622 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1623 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001624 return UNKNOWN_ERROR;
1625 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001626
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001627 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1628 mFlushedConfigs.lock()->swap(flushedConfigs);
1629 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001630 {
1631 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1632 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1633 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1634 watcher->onWorkQueued(
1635 work->input.ordinal.frameIndex.peeku(),
1636 std::vector(work->input.buffers),
1637 now);
1638 }
1639 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001640 err = mComponent->queue(&flushedConfigs);
1641 if (err != C2_OK) {
1642 ALOGW("[%s] Error while queueing a flushed config", mName);
1643 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001644 }
1645 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001646 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001647 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1648 !clientInputBuffers.empty()) {
1649 size_t minIndex = clientInputBuffers.begin()->first;
1650 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1651 for (const auto &[index, buffer] : clientInputBuffers) {
1652 if (minBuffer->capacity() > buffer->capacity()) {
1653 minIndex = index;
1654 minBuffer = buffer;
1655 }
1656 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001657 // WORKAROUND: Some apps expect CSD available without queueing
1658 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001659 minBuffer->setRange(0, 0);
1660 minBuffer->meta()->clear();
1661 minBuffer->meta()->setInt64("timeUs", 0);
1662 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001663 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1664 mName);
1665 return UNKNOWN_ERROR;
1666 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001667 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001668 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001669
Wonsik Kim34b28b42022-05-20 15:49:32 -07001670 for (const auto &[index, buffer] : clientInputBuffers) {
1671 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001672 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001673
Pawin Vongmasa36653902018-11-15 00:10:25 -08001674 return OK;
1675}
1676
1677void CCodecBufferChannel::stop() {
1678 mSync.stop();
1679 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001680}
1681
Sungtak Lee99144332023-01-26 11:03:14 +00001682void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
1683 sp<Surface> surface = mOutputSurface.lock()->surface;
1684 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00001685 C2BlockPool::local_id_t outputPoolId;
1686 {
1687 Mutexed<BlockPools>::Locked pools(mBlockPools);
1688 outputPoolId = pools->outputPoolId;
1689 }
1690 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00001691
1692 if (pushBlankBuffer) {
1693 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
1694 if (anw) {
1695 pushBlankBuffersToNativeWindow(anw.get());
1696 }
1697 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00001698 }
1699}
1700
Wonsik Kim936a89c2020-05-08 16:07:50 -07001701void CCodecBufferChannel::reset() {
1702 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001703 if (mInputSurface != nullptr) {
1704 mInputSurface.reset();
1705 }
1706 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001707 {
1708 Mutexed<Input>::Locked input(mInput);
1709 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001710 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001711 }
1712 {
1713 Mutexed<Output>::Locked output(mOutput);
1714 output->buffers.reset();
1715 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001716 // reset the frames that are being tracked for onFrameRendered callbacks
1717 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001718}
1719
1720void CCodecBufferChannel::release() {
1721 mComponent.reset();
1722 mInputAllocator.reset();
1723 mOutputSurface.lock()->surface.clear();
1724 {
1725 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1726 blockPools->inputPool.reset();
1727 blockPools->outputPoolIntf.reset();
1728 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001729 setCrypto(nullptr);
1730 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001731}
1732
Pawin Vongmasa36653902018-11-15 00:10:25 -08001733void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1734 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001735 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001736 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001737 {
1738 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1739 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1740 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1741 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1742 watcher->onWorkDone(frameIndex);
1743 continue;
1744 }
1745 if (work->input.buffers.empty()
1746 || work->input.buffers.front() == nullptr
1747 || work->input.buffers.front()->data().linearBlocks().empty()) {
1748 ALOGD("[%s] no linear codec config data found", mName);
1749 watcher->onWorkDone(frameIndex);
1750 continue;
1751 }
1752 std::unique_ptr<C2Work> copy(new C2Work);
1753 copy->input.flags = C2FrameData::flags_t(
1754 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1755 copy->input.ordinal = work->input.ordinal;
1756 copy->input.ordinal.frameIndex = mFrameIndex++;
1757 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1758 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1759 }
1760 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1761 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1762 }
1763 copy->input.infoBuffers.insert(
1764 copy->input.infoBuffers.begin(),
1765 work->input.infoBuffers.begin(),
1766 work->input.infoBuffers.end());
1767 copy->worklets.emplace_back(new C2Worklet);
1768 configs.push_back(std::move(copy));
1769 watcher->onWorkDone(frameIndex);
1770 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001771 }
1772 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001773 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001774 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001775 Mutexed<Input>::Locked input(mInput);
1776 input->buffers->flush();
1777 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001778 }
1779 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001780 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001781 if (output->buffers) {
1782 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001783 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001784 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001785 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001786 // reset the frames that are being tracked for onFrameRendered callbacks
1787 mTrackedFrames.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001788}
1789
1790void CCodecBufferChannel::onWorkDone(
1791 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001792 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001793 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001794 feedInputBufferIfAvailable();
1795 }
1796}
1797
1798void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001799 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001800 if (mInputSurface) {
1801 return;
1802 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001803 std::shared_ptr<C2Buffer> buffer =
1804 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001805 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001806 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001807 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001808 if (input->lastFlushIndex >= frameIndex) {
1809 ALOGD("[%s] Ignoring stale input buffer done callback: "
1810 "last flush index = %lld, frameIndex = %lld",
1811 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1812 } else {
1813 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1814 if (!newInputSlotAvailable) {
1815 (void)input->extraBuffers.expireComponentBuffer(buffer);
1816 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001817 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001818 }
1819 if (newInputSlotAvailable) {
1820 feedInputBufferIfAvailable();
1821 }
1822}
1823
1824bool CCodecBufferChannel::handleWork(
1825 std::unique_ptr<C2Work> work,
1826 const sp<AMessage> &outputFormat,
1827 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001828 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001829 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001830 if (!output->buffers) {
1831 return false;
1832 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001833 }
1834
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001835 // Whether the output buffer should be reported to the client or not.
1836 bool notifyClient = false;
1837
1838 if (work->result == C2_OK){
1839 notifyClient = true;
1840 } else if (work->result == C2_NOT_FOUND) {
1841 ALOGD("[%s] flushed work; ignored.", mName);
1842 } else {
1843 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1844 // the config update.
1845 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1846 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1847 return false;
1848 }
1849
1850 if ((work->input.ordinal.frameIndex -
1851 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001852 // Discard frames from previous generation.
1853 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001854 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001855 }
1856
Wonsik Kim524b0582019-03-12 11:28:57 -07001857 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001858 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001859 || !(work->worklets.front()->output.flags &
1860 C2FrameData::FLAG_INCOMPLETE))) {
1861 mPipelineWatcher.lock()->onWorkDone(
1862 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001863 }
1864
1865 // NOTE: MediaCodec usage supposedly have only one worklet
1866 if (work->worklets.size() != 1u) {
1867 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1868 mName, work->worklets.size());
1869 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1870 return false;
1871 }
1872
1873 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1874
1875 std::shared_ptr<C2Buffer> buffer;
1876 // NOTE: MediaCodec usage supposedly have only one output stream.
1877 if (worklet->output.buffers.size() > 1u) {
1878 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1879 mName, worklet->output.buffers.size());
1880 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1881 return false;
1882 } else if (worklet->output.buffers.size() == 1u) {
1883 buffer = worklet->output.buffers[0];
1884 if (!buffer) {
1885 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1886 }
1887 }
1888
Wonsik Kim3dedf682021-05-03 10:57:09 -07001889 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1890 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001891 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001892 while (!worklet->output.configUpdate.empty()) {
1893 std::unique_ptr<C2Param> param;
1894 worklet->output.configUpdate.back().swap(param);
1895 worklet->output.configUpdate.pop_back();
1896 switch (param->coreIndex().coreIndex()) {
1897 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1898 C2PortReorderBufferDepthTuning::output reorderDepth;
1899 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001900 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1901 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001902 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001903 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001904 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001905 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1906 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001907 }
1908 break;
1909 }
1910 case C2PortReorderKeySetting::CORE_INDEX: {
1911 C2PortReorderKeySetting::output reorderKey;
1912 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001913 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001914 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1915 mName, reorderKey.value);
1916 } else {
1917 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1918 }
1919 break;
1920 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001921 case C2PortActualDelayTuning::CORE_INDEX: {
1922 if (param->isGlobal()) {
1923 C2ActualPipelineDelayTuning pipelineDelay;
1924 if (pipelineDelay.updateFrom(*param)) {
1925 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1926 mName, pipelineDelay.value);
1927 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001928 (void)mPipelineWatcher.lock()->pipelineDelay(
1929 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001930 }
1931 }
1932 if (param->forInput()) {
1933 C2PortActualDelayTuning::input inputDelay;
1934 if (inputDelay.updateFrom(*param)) {
1935 ALOGV("[%s] onWorkDone: updating input delay %u",
1936 mName, inputDelay.value);
1937 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001938 (void)mPipelineWatcher.lock()->inputDelay(
1939 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001940 }
1941 }
1942 if (param->forOutput()) {
1943 C2PortActualDelayTuning::output outputDelay;
1944 if (outputDelay.updateFrom(*param)) {
1945 ALOGV("[%s] onWorkDone: updating output delay %u",
1946 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001947 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001948 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001949 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001950
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001951 }
1952 }
1953 break;
1954 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001955 case C2PortTunnelSystemTime::CORE_INDEX: {
1956 C2PortTunnelSystemTime::output frameRenderTime;
1957 if (frameRenderTime.updateFrom(*param)) {
1958 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1959 mName, (long long)frameRenderTime.value,
1960 (long long)worklet->output.ordinal.timestamp.peekll());
1961 mCCodecCallback->onOutputFramesRendered(
1962 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1963 }
1964 break;
1965 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001966 case C2StreamTunnelHoldRender::CORE_INDEX: {
1967 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1968 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1969 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1970 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1971 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1972 mCCodecCallback->onFirstTunnelFrameReady();
1973 break;
1974 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001975 default:
1976 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1977 mName, param->index());
1978 break;
1979 }
1980 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001981 if (newInputDelay || newPipelineDelay) {
1982 Mutexed<Input>::Locked input(mInput);
1983 size_t newNumSlots =
1984 newInputDelay.value_or(input->inputDelay) +
1985 newPipelineDelay.value_or(input->pipelineDelay) +
1986 kSmoothnessFactor;
1987 if (input->buffers->isArrayMode()) {
1988 if (input->numSlots >= newNumSlots) {
1989 input->numExtraSlots = 0;
1990 } else {
1991 input->numExtraSlots = newNumSlots - input->numSlots;
1992 }
1993 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1994 mName, input->numExtraSlots);
1995 } else {
1996 input->numSlots = newNumSlots;
1997 }
1998 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001999 size_t numOutputSlots = 0;
2000 uint32_t reorderDepth = 0;
2001 bool outputBuffersChanged = false;
2002 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2003 Mutexed<Output>::Locked output(mOutput);
2004 if (!output->buffers) {
2005 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002006 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002007 numOutputSlots = output->numSlots;
2008 if (newReorderKey) {
2009 output->buffers->setReorderKey(newReorderKey.value());
2010 }
2011 if (newReorderDepth) {
2012 output->buffers->setReorderDepth(newReorderDepth.value());
2013 }
2014 reorderDepth = output->buffers->getReorderDepth();
2015 if (newOutputDelay) {
2016 output->outputDelay = newOutputDelay.value();
2017 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2018 if (output->numSlots < numOutputSlots) {
2019 output->numSlots = numOutputSlots;
2020 if (output->buffers->isArrayMode()) {
2021 OutputBuffersArray *array =
2022 (OutputBuffersArray *)output->buffers.get();
2023 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2024 mName, numOutputSlots);
2025 array->grow(numOutputSlots);
2026 outputBuffersChanged = true;
2027 }
2028 }
2029 }
2030 numOutputSlots = output->numSlots;
2031 }
2032 if (outputBuffersChanged) {
2033 mCCodecCallback->onOutputBuffersChanged();
2034 }
2035 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002036 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002037 {
2038 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2039 maxDequeueCount = output->maxDequeueBuffers =
2040 numOutputSlots + reorderDepth + kRenderingDepth;
2041 if (output->surface) {
2042 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2043 }
2044 }
2045 if (maxDequeueCount > 0) {
2046 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002047 }
2048 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002049
Pawin Vongmasa36653902018-11-15 00:10:25 -08002050 int32_t flags = 0;
2051 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002052 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002053 ALOGV("[%s] onWorkDone: output EOS", mName);
2054 }
2055
Pawin Vongmasa36653902018-11-15 00:10:25 -08002056 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2057 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2058 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2059 // shall correspond to the client input timesamp (in customOrdinal). By using the
2060 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2061 // produces multiple output.
2062 c2_cntr64_t timestamp =
2063 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2064 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002065 if (mInputSurface != nullptr) {
2066 // When using input surface we need to restore the original input timestamp.
2067 timestamp = work->input.ordinal.customOrdinal;
2068 }
My Name6bd9a7d2022-03-25 12:37:58 -07002069 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2070 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002071 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2072 mName,
2073 work->input.ordinal.customOrdinal.peekll(),
2074 work->input.ordinal.timestamp.peekll(),
2075 worklet->output.ordinal.timestamp.peekll(),
2076 timestamp.peekll());
2077
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002078 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002079 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002080 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002081 if (output->buffers && outputFormat) {
2082 output->buffers->updateSkipCutBuffer(outputFormat);
2083 output->buffers->setFormat(outputFormat);
2084 }
2085 if (!notifyClient) {
2086 return false;
2087 }
2088 size_t index;
2089 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07002090 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002091 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002092 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002093 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2094
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002095 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002096 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002097 } else {
2098 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002099 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002100 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002101 return false;
2102 }
2103 }
2104
Wonsik Kimec585c32021-10-01 01:11:00 -07002105 bool drop = false;
2106 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2107 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2108 drop = true;
2109 }
2110
Marc Kassisec910342022-11-25 11:43:05 +01002111 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2112 // HAL, the flag is then removed in the corresponding output buffer.
2113 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2114 flags |= BUFFER_FLAG_DECODE_ONLY;
2115 }
2116
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002117 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002118 if (mTunneled && drop && outputFormat) {
2119 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2120 mName, work->input.ordinal.frameIndex.peekull());
2121 } else {
2122 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2123 mName, work->input.ordinal.frameIndex.peekull());
2124 notifyClient = false;
2125 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002126 }
2127
2128 if (buffer) {
2129 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2130 // TODO: properly translate these to metadata
2131 switch (info->coreIndex().coreIndex()) {
2132 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002133 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002134 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002135 }
2136 break;
2137 default:
2138 break;
2139 }
2140 }
2141 }
2142
2143 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002144 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002145 if (!output->buffers) {
2146 return false;
2147 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002148 output->buffers->pushToStash(
2149 buffer,
2150 notifyClient,
2151 timestamp.peek(),
2152 flags,
2153 outputFormat,
2154 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002155 }
2156 sendOutputBuffers();
2157 return true;
2158}
2159
2160void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002161 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002162 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002163 sp<MediaCodecBuffer> outBuffer;
2164 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002165
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002166 constexpr int kMaxReallocTry = 5;
2167 int reallocTryNum = 0;
2168
Pawin Vongmasa36653902018-11-15 00:10:25 -08002169 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002170 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002171 if (!output->buffers) {
2172 return;
2173 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002174 action = output->buffers->popFromStashAndRegister(
2175 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002176 if (action != OutputBuffers::REALLOCATE) {
2177 reallocTryNum = 0;
2178 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002179 switch (action) {
2180 case OutputBuffers::SKIP:
2181 return;
2182 case OutputBuffers::DISCARD:
2183 break;
2184 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00002185 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002186 mCallback->onOutputBufferAvailable(index, outBuffer);
2187 break;
2188 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002189 if (++reallocTryNum > kMaxReallocTry) {
2190 output.unlock();
2191 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2192 mName, kMaxReallocTry);
2193 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2194 return;
2195 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002196 if (!output->buffers->isArrayMode()) {
2197 output->buffers =
2198 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002199 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002200 static_cast<OutputBuffersArray*>(output->buffers.get())->
2201 realloc(c2Buffer);
2202 output.unlock();
2203 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002204 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002205 case OutputBuffers::RETRY:
2206 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2207 mName);
2208 return;
2209 default:
2210 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2211 "corrupted BufferAction value (%d) "
2212 "returned from popFromStashAndRegister.",
2213 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002214 return;
2215 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002216 }
2217}
2218
Sungtak Lee99144332023-01-26 11:03:14 +00002219status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002220 static std::atomic_uint32_t surfaceGeneration{0};
2221 uint32_t generation = (getpid() << 10) |
2222 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2223 & ((1 << 10) - 1));
2224
2225 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002226 int maxDequeueCount;
2227 sp<Surface> oldSurface;
2228 {
2229 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2230 maxDequeueCount = outputSurface->maxDequeueBuffers;
2231 oldSurface = outputSurface->surface;
2232 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002233 if (newSurface) {
2234 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002235 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002236 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002237 producer = newSurface->getIGraphicBufferProducer();
2238 producer->setGenerationNumber(generation);
2239 } else {
2240 ALOGE("[%s] setting output surface to null", mName);
2241 return INVALID_OPERATION;
2242 }
2243
2244 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2245 C2BlockPool::local_id_t outputPoolId;
2246 {
2247 Mutexed<BlockPools>::Locked pools(mBlockPools);
2248 outputPoolId = pools->outputPoolId;
2249 outputPoolIntf = pools->outputPoolIntf;
2250 }
2251
2252 if (outputPoolIntf) {
2253 if (mComponent->setOutputSurface(
2254 outputPoolId,
2255 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002256 generation,
2257 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002258 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2259 return INVALID_OPERATION;
2260 }
2261 }
2262
2263 {
2264 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2265 output->surface = newSurface;
2266 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002267 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002268 }
2269
Sungtak Lee99144332023-01-26 11:03:14 +00002270 if (oldSurface && pushBlankBuffer) {
2271 // When ReleaseSurface was set from MediaCodec,
2272 // pushing a blank buffer at the end might be necessary.
2273 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2274 if (anw) {
2275 pushBlankBuffersToNativeWindow(anw.get());
2276 }
2277 }
2278
Pawin Vongmasa36653902018-11-15 00:10:25 -08002279 return OK;
2280}
2281
Wonsik Kimab34ed62019-01-31 15:28:46 -08002282PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002283 // Otherwise, component may have stalled work due to input starvation up to
2284 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002285 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2286 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002287 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002288 size_t outputDelay = mOutput.lock()->outputDelay;
2289 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002290 Mutexed<Input>::Locked input(mInput);
2291 n = input->inputDelay + input->pipelineDelay + outputDelay;
2292 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002293 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002294}
2295
Pawin Vongmasa36653902018-11-15 00:10:25 -08002296void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2297 mMetaMode = mode;
2298}
2299
Wonsik Kim596187e2019-10-25 12:44:10 -07002300void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002301 if (mCrypto != nullptr) {
2302 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2303 mCrypto->unsetHeap(entry.second);
2304 }
2305 mHeapSeqNumMap.clear();
2306 if (mHeapSeqNum >= 0) {
2307 mCrypto->unsetHeap(mHeapSeqNum);
2308 mHeapSeqNum = -1;
2309 }
2310 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002311 mCrypto = crypto;
2312}
2313
2314void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2315 mDescrambler = descrambler;
2316}
2317
Pawin Vongmasa36653902018-11-15 00:10:25 -08002318status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2319 // C2_OK is always translated to OK.
2320 if (c2s == C2_OK) {
2321 return OK;
2322 }
2323
2324 // Operation-dependent translation
2325 // TODO: Add as necessary
2326 switch (c2op) {
2327 case C2_OPERATION_Component_start:
2328 switch (c2s) {
2329 case C2_NO_MEMORY:
2330 return NO_MEMORY;
2331 default:
2332 return UNKNOWN_ERROR;
2333 }
2334 default:
2335 break;
2336 }
2337
2338 // Backup operation-agnostic translation
2339 switch (c2s) {
2340 case C2_BAD_INDEX:
2341 return BAD_INDEX;
2342 case C2_BAD_VALUE:
2343 return BAD_VALUE;
2344 case C2_BLOCKING:
2345 return WOULD_BLOCK;
2346 case C2_DUPLICATE:
2347 return ALREADY_EXISTS;
2348 case C2_NO_INIT:
2349 return NO_INIT;
2350 case C2_NO_MEMORY:
2351 return NO_MEMORY;
2352 case C2_NOT_FOUND:
2353 return NAME_NOT_FOUND;
2354 case C2_TIMED_OUT:
2355 return TIMED_OUT;
2356 case C2_BAD_STATE:
2357 case C2_CANCELED:
2358 case C2_CANNOT_DO:
2359 case C2_CORRUPTED:
2360 case C2_OMITTED:
2361 case C2_REFUSED:
2362 return UNKNOWN_ERROR;
2363 default:
2364 return -static_cast<status_t>(c2s);
2365 }
2366}
2367
Pawin Vongmasa36653902018-11-15 00:10:25 -08002368} // namespace android