blob: 22c4aee571d93518217347f68ab2685a07f8f350 [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),
Brian Lindahle31a52d2023-04-05 08:49:23 -0600150 mIsSurfaceToDisplay(false),
151 mHasPresentFenceTimes(false),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800152 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700153 mInputMetEos(false),
154 mSendEncryptedInfoBuffer(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700155 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700156 {
157 Mutexed<Input>::Locked input(mInput);
158 input->buffers.reset(new DummyInputBuffers(""));
159 input->extraBuffers.flush();
160 input->inputDelay = 0u;
161 input->pipelineDelay = 0u;
162 input->numSlots = kSmoothnessFactor;
163 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700164 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700165 }
166 {
167 Mutexed<Output>::Locked output(mOutput);
168 output->outputDelay = 0u;
169 output->numSlots = kSmoothnessFactor;
170 }
David Stevensc3fbb282021-01-18 18:11:20 +0900171 {
172 Mutexed<BlockPools>::Locked pools(mBlockPools);
173 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
174 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800175}
176
177CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800178 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800179 mCrypto->unsetHeap(mHeapSeqNum);
180 }
181}
182
183void CCodecBufferChannel::setComponent(
184 const std::shared_ptr<Codec2Client::Component> &component) {
185 mComponent = component;
186 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
187 mName = mComponentName.c_str();
188}
189
190status_t CCodecBufferChannel::setInputSurface(
191 const std::shared_ptr<InputSurfaceWrapper> &surface) {
192 ALOGV("[%s] setInputSurface", mName);
193 mInputSurface = surface;
194 return mInputSurface->connect(mComponent);
195}
196
197status_t CCodecBufferChannel::signalEndOfInputStream() {
198 if (mInputSurface == nullptr) {
199 return INVALID_OPERATION;
200 }
201 return mInputSurface->signalEndOfInputStream();
202}
203
Sungtak Lee04b30352020-07-27 13:57:25 -0700204status_t CCodecBufferChannel::queueInputBufferInternal(
205 sp<MediaCodecBuffer> buffer,
206 std::shared_ptr<C2LinearBlock> encryptedBlock,
207 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800208 int64_t timeUs;
209 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
210
211 if (mInputMetEos) {
212 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
213 return OK;
214 }
215
216 int32_t flags = 0;
217 int32_t tmp = 0;
218 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200219 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800220 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
221 eos = true;
222 mInputMetEos = true;
223 ALOGV("[%s] input EOS", mName);
224 }
225 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
226 flags |= C2FrameData::FLAG_CODEC_CONFIG;
227 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200228 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
229 tunnelFirstFrame = true;
230 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800231 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800232 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800233 std::unique_ptr<C2Work> work(new C2Work);
234 work->input.ordinal.timestamp = timeUs;
235 work->input.ordinal.frameIndex = mFrameIndex++;
236 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
237 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
238 // Keep client timestamp in customOrdinal
239 work->input.ordinal.customOrdinal = timeUs;
240 work->input.buffers.clear();
241
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700242 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800243 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800244
Pawin Vongmasa36653902018-11-15 00:10:25 -0800245 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700246 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800247 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700248 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800249 return -ENOENT;
250 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700251 // TODO: we want to delay copying buffers.
252 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
253 copy = input->buffers->cloneAndReleaseBuffer(buffer);
254 if (copy != nullptr) {
255 (void)input->extraBuffers.assignSlot(copy);
256 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
257 return UNKNOWN_ERROR;
258 }
259 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
260 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
261 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700262 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700263 } else {
264 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
265 "buffer starvation on component.", mName);
266 }
267 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800268 if (input->frameReassembler) {
269 usesFrameReassembler = true;
270 input->frameReassembler.process(buffer, &items);
271 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900272 int32_t cvo = 0;
273 if (buffer->meta()->findInt32("cvo", &cvo)) {
274 int32_t rotation = cvo % 360;
275 // change rotation to counter-clock wise.
276 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
277
278 Mutexed<OutputSurface>::Locked output(mOutputSurface);
279 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
280 output->rotation[frameIndex] = rotation;
281 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800282 work->input.buffers.push_back(c2buffer);
283 if (encryptedBlock) {
284 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
285 kParamIndexEncryptedBuffer,
286 encryptedBlock->share(0, blockSize, C2Fence())));
287 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700288 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800289 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700290 Mutexed<Input>::Locked input(mInput);
291 if (input->frameReassembler) {
292 usesFrameReassembler = true;
293 // drain any pending items with eos
294 input->frameReassembler.process(buffer, &items);
295 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800296 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800297 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800298 if (usesFrameReassembler) {
299 if (!items.empty()) {
300 items.front()->input.configUpdate = std::move(mParamsToBeSet);
301 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
302 }
303 } else {
304 work->input.flags = (C2FrameData::flags_t)flags;
305 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800306
Wonsik Kime1104ca2020-11-24 15:01:33 -0800307 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200308 if (tunnelFirstFrame) {
309 C2StreamTunnelHoldRender::input tunnelHoldRender{
310 0u /* stream */,
311 C2_TRUE /* value */
312 };
313 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
314 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800315 work->worklets.clear();
316 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800317
Wonsik Kime1104ca2020-11-24 15:01:33 -0800318 items.push_back(std::move(work));
319
320 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800321 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800322 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800323 work.reset(new C2Work);
324 work->input.ordinal.timestamp = timeUs;
325 work->input.ordinal.frameIndex = mFrameIndex++;
326 // WORKAROUND: keep client timestamp in customOrdinal
327 work->input.ordinal.customOrdinal = timeUs;
328 work->input.buffers.clear();
329 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800330 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800331 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800332 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800333 c2_status_t err = C2_OK;
334 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700335 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
336 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800337 {
338 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
339 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
340 for (const std::unique_ptr<C2Work> &work : items) {
341 watcher->onWorkQueued(
342 work->input.ordinal.frameIndex.peeku(),
343 std::vector(work->input.buffers),
344 now);
345 }
346 }
347 err = mComponent->queue(&items);
348 }
349 if (err != C2_OK) {
350 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
351 for (const std::unique_ptr<C2Work> &work : items) {
352 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
353 }
354 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700355 Mutexed<Input>::Locked input(mInput);
356 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700357 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700358 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700359 } else if (buffer) {
360 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700361 }
362 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
363 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800364 }
365
366 feedInputBufferIfAvailableInternal();
367 return err;
368}
369
370status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
371 QueueGuard guard(mSync);
372 if (!guard.isRunning()) {
373 ALOGD("[%s] setParameters is only supported in the running state.", mName);
374 return -ENOSYS;
375 }
376 mParamsToBeSet.insert(mParamsToBeSet.end(),
377 std::make_move_iterator(params.begin()),
378 std::make_move_iterator(params.end()));
379 params.clear();
380 return OK;
381}
382
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800383status_t CCodecBufferChannel::attachBuffer(
384 const std::shared_ptr<C2Buffer> &c2Buffer,
385 const sp<MediaCodecBuffer> &buffer) {
386 if (!buffer->copy(c2Buffer)) {
387 return -ENOSYS;
388 }
389 return OK;
390}
391
392void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
393 if (!mDecryptDestination || mDecryptDestination->size() < size) {
394 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
395 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
396 mCrypto->unsetHeap(mHeapSeqNum);
397 }
398 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
399 if (mCrypto) {
400 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
401 }
402 }
403}
404
405int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
406 CHECK(mCrypto);
407 auto it = mHeapSeqNumMap.find(memory);
408 int32_t heapSeqNum = -1;
409 if (it == mHeapSeqNumMap.end()) {
410 heapSeqNum = mCrypto->setHeap(memory);
411 mHeapSeqNumMap.emplace(memory, heapSeqNum);
412 } else {
413 heapSeqNum = it->second;
414 }
415 return heapSeqNum;
416}
417
418status_t CCodecBufferChannel::attachEncryptedBuffer(
419 const sp<hardware::HidlMemory> &memory,
420 bool secure,
421 const uint8_t *key,
422 const uint8_t *iv,
423 CryptoPlugin::Mode mode,
424 CryptoPlugin::Pattern pattern,
425 size_t offset,
426 const CryptoPlugin::SubSample *subSamples,
427 size_t numSubSamples,
428 const sp<MediaCodecBuffer> &buffer) {
429 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
430 static const C2MemoryUsage kDefaultReadWriteUsage{
431 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
432
433 size_t size = 0;
434 for (size_t i = 0; i < numSubSamples; ++i) {
435 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
436 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700437 if (size == 0) {
438 buffer->setRange(0, 0);
439 return OK;
440 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800441 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
442 std::shared_ptr<C2LinearBlock> block;
443 c2_status_t err = pool->fetchLinearBlock(
444 size,
445 secure ? kSecureUsage : kDefaultReadWriteUsage,
446 &block);
447 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700448 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
449 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800450 return NO_MEMORY;
451 }
452 if (!secure) {
453 ensureDecryptDestination(size);
454 }
455 ssize_t result = -1;
456 ssize_t codecDataOffset = 0;
457 if (mCrypto) {
458 AString errorDetailMsg;
459 int32_t heapSeqNum = getHeapSeqNum(memory);
460 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
461 hardware::drm::V1_0::DestinationBuffer dst;
462 if (secure) {
463 dst.type = DrmBufferType::NATIVE_HANDLE;
464 dst.secureMemory = hardware::hidl_handle(block->handle());
465 } else {
466 dst.type = DrmBufferType::SHARED_MEMORY;
467 IMemoryToSharedBuffer(
468 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
469 }
470 result = mCrypto->decrypt(
471 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
472 dst, &errorDetailMsg);
473 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700474 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800475 return result;
476 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800477 } else {
478 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
479 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
480 hidl_vec<SubSample> hidlSubSamples;
481 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
482
483 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
484 hardware::cas::native::V1_0::DestinationBuffer dst;
485 if (secure) {
486 dst.type = BufferType::NATIVE_HANDLE;
487 dst.secureMemory = hardware::hidl_handle(block->handle());
488 } else {
489 dst.type = BufferType::SHARED_MEMORY;
490 dst.nonsecureMemory = src;
491 }
492
493 CasStatus status = CasStatus::OK;
494 hidl_string detailedError;
495 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
496
497 if (key != nullptr) {
498 sctrl = (ScramblingControl)key[0];
499 // Adjust for the PES offset
500 codecDataOffset = key[2] | (key[3] << 8);
501 }
502
503 auto returnVoid = mDescrambler->descramble(
504 sctrl,
505 hidlSubSamples,
506 src,
507 0,
508 dst,
509 0,
510 [&status, &result, &detailedError] (
511 CasStatus _status, uint32_t _bytesWritten,
512 const hidl_string& _detailedError) {
513 status = _status;
514 result = (ssize_t)_bytesWritten;
515 detailedError = _detailedError;
516 });
517
518 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
519 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
520 mName, returnVoid.description().c_str(), status, result);
521 return UNKNOWN_ERROR;
522 }
523
524 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700525 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
526 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800527 return BAD_VALUE;
528 }
529 }
530 if (!secure) {
531 C2WriteView view = block->map().get();
532 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700533 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
534 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800535 return UNKNOWN_ERROR;
536 }
537 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700538 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
539 "(non-secure)",
540 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800541 return UNKNOWN_ERROR;
542 }
543 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
544 }
545 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
546 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
547 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700548 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800549 return -ENOSYS;
550 }
551 return OK;
552}
553
Pawin Vongmasa36653902018-11-15 00:10:25 -0800554status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
555 QueueGuard guard(mSync);
556 if (!guard.isRunning()) {
557 ALOGD("[%s] No more buffers should be queued at current state.", mName);
558 return -ENOSYS;
559 }
560 return queueInputBufferInternal(buffer);
561}
562
563status_t CCodecBufferChannel::queueSecureInputBuffer(
564 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
565 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
566 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
567 AString *errorDetailMsg) {
568 QueueGuard guard(mSync);
569 if (!guard.isRunning()) {
570 ALOGD("[%s] No more buffers should be queued at current state.", mName);
571 return -ENOSYS;
572 }
573
574 if (!hasCryptoOrDescrambler()) {
575 return -ENOSYS;
576 }
577 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
578
Sungtak Lee04b30352020-07-27 13:57:25 -0700579 std::shared_ptr<C2LinearBlock> block;
580 size_t allocSize = buffer->size();
581 size_t bufferSize = 0;
582 c2_status_t blockRes = C2_OK;
583 bool copied = false;
584 if (mSendEncryptedInfoBuffer) {
585 static const C2MemoryUsage kDefaultReadWriteUsage{
586 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
587 constexpr int kAllocGranule0 = 1024 * 64;
588 constexpr int kAllocGranule1 = 1024 * 1024;
589 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
590 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
591 if (allocSize <= kAllocGranule1) {
592 bufferSize = align(allocSize, kAllocGranule0);
593 } else {
594 bufferSize = align(allocSize, kAllocGranule1);
595 }
596 blockRes = pool->fetchLinearBlock(
597 bufferSize, kDefaultReadWriteUsage, &block);
598
599 if (blockRes == C2_OK) {
600 C2WriteView view = block->map().get();
601 if (view.error() == C2_OK && view.size() == bufferSize) {
602 copied = true;
603 // TODO: only copy clear sections
604 memcpy(view.data(), buffer->data(), allocSize);
605 }
606 }
607 }
608
609 if (!copied) {
610 block.reset();
611 }
612
Pawin Vongmasa36653902018-11-15 00:10:25 -0800613 ssize_t result = -1;
614 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700615 if (numSubSamples == 1
616 && subSamples[0].mNumBytesOfClearData == 0
617 && subSamples[0].mNumBytesOfEncryptedData == 0) {
618 // We don't need to go through crypto or descrambler if the input is empty.
619 result = 0;
620 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700621 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800622 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700623 destination.type = DrmBufferType::NATIVE_HANDLE;
624 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800625 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700626 destination.type = DrmBufferType::SHARED_MEMORY;
627 IMemoryToSharedBuffer(
628 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800629 }
Robert Shih895fba92019-07-16 16:29:44 -0700630 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800631 encryptedBuffer->fillSourceBuffer(&source);
632 result = mCrypto->decrypt(
633 key, iv, mode, pattern, source, buffer->offset(),
634 subSamples, numSubSamples, destination, errorDetailMsg);
635 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700636 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800637 return result;
638 }
Robert Shih895fba92019-07-16 16:29:44 -0700639 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800640 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
641 }
642 } else {
643 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
644 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
645 hidl_vec<SubSample> hidlSubSamples;
646 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
647
648 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
649 encryptedBuffer->fillSourceBuffer(&srcBuffer);
650
651 DestinationBuffer dstBuffer;
652 if (secure) {
653 dstBuffer.type = BufferType::NATIVE_HANDLE;
654 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
655 } else {
656 dstBuffer.type = BufferType::SHARED_MEMORY;
657 dstBuffer.nonsecureMemory = srcBuffer;
658 }
659
660 CasStatus status = CasStatus::OK;
661 hidl_string detailedError;
662 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
663
664 if (key != nullptr) {
665 sctrl = (ScramblingControl)key[0];
666 // Adjust for the PES offset
667 codecDataOffset = key[2] | (key[3] << 8);
668 }
669
670 auto returnVoid = mDescrambler->descramble(
671 sctrl,
672 hidlSubSamples,
673 srcBuffer,
674 0,
675 dstBuffer,
676 0,
677 [&status, &result, &detailedError] (
678 CasStatus _status, uint32_t _bytesWritten,
679 const hidl_string& _detailedError) {
680 status = _status;
681 result = (ssize_t)_bytesWritten;
682 detailedError = _detailedError;
683 });
684
685 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
686 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
687 mName, returnVoid.description().c_str(), status, result);
688 return UNKNOWN_ERROR;
689 }
690
691 if (result < codecDataOffset) {
692 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
693 return BAD_VALUE;
694 }
695
696 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
697
698 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
699 encryptedBuffer->copyDecryptedContentFromMemory(result);
700 }
701 }
702
703 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700704
705 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800706}
707
708void CCodecBufferChannel::feedInputBufferIfAvailable() {
709 QueueGuard guard(mSync);
710 if (!guard.isRunning()) {
711 ALOGV("[%s] We're not running --- no input buffer reported", mName);
712 return;
713 }
714 feedInputBufferIfAvailableInternal();
715}
716
717void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900718 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800719 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700720 }
721 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700722 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700723 if (!output->buffers ||
724 output->buffers->hasPending() ||
Wonsik Kim0487b782020-10-28 11:45:50 -0700725 output->buffers->numActiveSlots() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800726 return;
727 }
728 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700729 size_t numActiveSlots = 0;
730 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800731 sp<MediaCodecBuffer> inBuffer;
732 size_t index;
733 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700734 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700735 numActiveSlots = input->buffers->numActiveSlots();
736 if (numActiveSlots >= input->numSlots) {
737 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800738 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700739 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800740 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800741 break;
742 }
743 }
744 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
745 mCallback->onInputBufferAvailable(index, inBuffer);
746 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700747 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748}
749
750status_t CCodecBufferChannel::renderOutputBuffer(
751 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800752 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800753 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800754 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800755 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700756 Mutexed<Output>::Locked output(mOutput);
757 if (output->buffers) {
758 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759 }
760 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800761 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
762 // set to true.
763 sendOutputBuffers();
764 // input buffer feeding may have been gated by pending output buffers
765 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800766 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800767 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700768 std::call_once(mRenderWarningFlag, [this] {
769 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
770 "timestamp or render=true with non-video buffers. Apps should "
771 "call releaseOutputBuffer() with render=false for those.",
772 mName);
773 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800774 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800775 return INVALID_OPERATION;
776 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800777
778#if 0
779 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
780 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
781 for (const std::shared_ptr<const C2Info> &info : infoParams) {
782 AString res;
783 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
784 if (ix) res.append(", ");
785 res.append(*((int32_t*)info.get() + (ix / 4)));
786 }
787 ALOGV(" [%s]", res.c_str());
788 }
789#endif
790 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
791 std::static_pointer_cast<const C2StreamRotationInfo::output>(
792 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
793 bool flip = rotation && (rotation->flip & 1);
794 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900795
796 {
797 Mutexed<OutputSurface>::Locked output(mOutputSurface);
798 if (output->surface == nullptr) {
799 ALOGI("[%s] cannot render buffer without surface", mName);
800 return OK;
801 }
802 int64_t frameIndex;
803 buffer->meta()->findInt64("frameIndex", &frameIndex);
804 if (output->rotation.count(frameIndex) != 0) {
805 auto it = output->rotation.find(frameIndex);
806 quarters = (it->second / 90) & 3;
807 output->rotation.erase(it);
808 }
809 }
810
Pawin Vongmasa36653902018-11-15 00:10:25 -0800811 uint32_t transform = 0;
812 switch (quarters) {
813 case 0: // no rotation
814 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
815 break;
816 case 1: // 90 degrees counter-clockwise
817 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
818 : HAL_TRANSFORM_ROT_270;
819 break;
820 case 2: // 180 degrees
821 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
822 break;
823 case 3: // 90 degrees clockwise
824 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
825 : HAL_TRANSFORM_ROT_90;
826 break;
827 }
828
829 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
830 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
831 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
832 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
833 if (surfaceScaling) {
834 videoScalingMode = surfaceScaling->value;
835 }
836
837 // Use dataspace from format as it has the default aspects already applied
838 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
839 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
840
841 // HDR static info
842 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
843 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
844 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
845
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800846 // HDR10 plus info
847 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
848 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
849 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800850 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
851 hdr10PlusInfo.reset();
852 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800853
Wonsik Kima79c5522022-01-18 16:29:24 -0800854 // HDR dynamic info
855 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
856 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
857 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
858 // TODO: make this sticky & enable unset
859 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
860 hdrDynamicInfo.reset();
861 }
862
863 if (hdr10PlusInfo) {
864 // C2StreamHdr10PlusInfo is deprecated; components should use
865 // C2StreamHdrDynamicMetadataInfo
866 // TODO: #metric
867 if (hdrDynamicInfo) {
868 // It is unexpected that C2StreamHdr10PlusInfo and
869 // C2StreamHdrDynamicMetadataInfo is both present.
870 // C2StreamHdrDynamicMetadataInfo takes priority.
871 // TODO: #metric
872 } else {
873 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
874 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
875 hdr10PlusInfo->flexCount(),
876 0u,
877 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
878 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
879 hdrDynamicInfo = info;
880 }
881 }
882
Pawin Vongmasa36653902018-11-15 00:10:25 -0800883 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
884 if (blocks.size() != 1u) {
885 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
886 return UNKNOWN_ERROR;
887 }
888 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700889 C2Fence c2fence = block.fence();
890 sp<Fence> fence = Fence::NO_FENCE;
891 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
892 // Once C2Fence::type() is added, check the exact C2Fence type
893 if (c2fence.isHW()) {
894 int fenceFd = c2fence.fd();
895 fence = sp<Fence>::make(fenceFd);
896 if (!fence) {
897 ALOGE("[%s] Failed to allocate a fence", mName);
898 close(fenceFd);
899 return NO_MEMORY;
900 }
901 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800902
903 // TODO: revisit this after C2Fence implementation.
Brian Lindahlc953b462023-01-27 16:21:43 -0700904 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800905 timestampNs,
906 false, // droppable
907 dataSpace,
908 Rect(blocks.front().crop().left,
909 blocks.front().crop().top,
910 blocks.front().crop().right(),
911 blocks.front().crop().bottom()),
912 videoScalingMode,
913 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700914 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800915 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800916 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800917 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800918 // If mastering max and min luminance fields are 0, do not use them.
919 // It indicates the value may not be present in the stream.
920 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
921 hdrStaticInfo->mastering.minLuminance > 0.0f) {
922 struct android_smpte2086_metadata smpte2086_meta = {
923 .displayPrimaryRed = {
924 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
925 },
926 .displayPrimaryGreen = {
927 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
928 },
929 .displayPrimaryBlue = {
930 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
931 },
932 .whitePoint = {
933 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
934 },
935 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
936 .minLuminance = hdrStaticInfo->mastering.minLuminance,
937 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800938 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800939 hdr.smpte2086 = smpte2086_meta;
940 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700941 // If the content light level fields are 0, do not use them, it
942 // indicates the value may not be present in the stream.
943 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
944 struct android_cta861_3_metadata cta861_meta = {
945 .maxContentLightLevel = hdrStaticInfo->maxCll,
946 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
947 };
948 hdr.validTypes |= HdrMetadata::CTA861_3;
949 hdr.cta8613 = cta861_meta;
950 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900951
952 // does not have valid info
953 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
954 hdrStaticInfo.reset();
955 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800956 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800957 if (hdrDynamicInfo
958 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800959 hdr.validTypes |= HdrMetadata::HDR10PLUS;
960 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800961 hdrDynamicInfo->m.data,
962 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800963 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800964 qbi.setHdrMetadata(hdr);
965 }
Hongguangfc1478a2022-07-20 22:56:06 -0700966 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
967
Brian Lindahlc953b462023-01-27 16:21:43 -0700968 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
969 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
970 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800971 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
972 if (result != OK) {
973 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800974 if (result == NO_INIT) {
975 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
976 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800977 return result;
978 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800979
980 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
981 ALOGD("[%s] queue buffer successful", mName);
982 } else {
983 ALOGV("[%s] queue buffer successful", mName);
984 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800985
986 int64_t mediaTimeUs = 0;
987 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahle31a52d2023-04-05 08:49:23 -0600988 if (mIsSurfaceToDisplay) {
989 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
990 processRenderedFrames(qbo.frameTimestamps);
991 } else {
992 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
993 // when the frame is queued to the non-display surface
994 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
995 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800996
997 return OK;
998}
999
Brian Lindahlc953b462023-01-27 16:21:43 -07001000void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahle31a52d2023-04-05 08:49:23 -06001001 mTrackedFrames.clear();
1002
1003 int isSurfaceToDisplay = 0;
1004 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1005 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1006 // No frame tracking is needed if we're not sending frames to the display
1007 if (!mIsSurfaceToDisplay) {
1008 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1009 return;
1010 }
1011
Brian Lindahlc953b462023-01-27 16:21:43 -07001012 int hasPresentFenceTimes = 0;
1013 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1014 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
1015 if (mHasPresentFenceTimes) {
1016 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1017 }
Brian Lindahlc953b462023-01-27 16:21:43 -07001018}
1019
1020void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1021 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1022 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1023 // so track the frame as if the desired render time is now.
1024 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1025 if (desiredRenderTimeNs < nowNs) {
1026 desiredRenderTimeNs = nowNs;
1027 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001028 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1029 // actually rendered.
Brian Lindahlc953b462023-01-27 16:21:43 -07001030 TrackedFrame frame;
1031 frame.number = qbo.nextFrameNumber - 1;
1032 frame.mediaTimeUs = mediaTimeUs;
1033 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1034 frame.latchTime = -1;
1035 frame.presentFence = nullptr;
1036 mTrackedFrames.push_back(frame);
1037}
1038
1039void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1040 // Grab the latch times and present fences from the frame event deltas
1041 for (const auto& delta : deltas) {
1042 for (auto& frame : mTrackedFrames) {
1043 if (delta.getFrameNumber() == frame.number) {
1044 delta.getLatchTime(&frame.latchTime);
1045 delta.getDisplayPresentFence(&frame.presentFence);
1046 }
1047 }
1048 }
1049
1050 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1051 // in fact, been rendered.
1052 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1053 while (!mTrackedFrames.empty()) {
1054 TrackedFrame & frame = mTrackedFrames.front();
1055 // Frames that should have been rendered at least 100ms in the past are checked
1056 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1057 break;
1058 }
1059
1060 // If we don't have a render time by now, then consider the frame as dropped
1061 int64_t renderTimeNs = getRenderTimeNs(frame);
1062 if (renderTimeNs != -1) {
1063 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1064 }
1065 mTrackedFrames.pop_front();
1066 }
1067}
1068
1069int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1070 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1071 if (!mHasPresentFenceTimes) {
1072 if (frame.latchTime == -1) {
1073 ALOGD("no latch time for frame %d", (int) frame.number);
1074 return -1;
1075 }
1076 return frame.latchTime;
1077 }
1078
1079 if (frame.presentFence == nullptr) {
1080 ALOGW("no present fence for frame %d", (int) frame.number);
1081 return -1;
1082 }
1083
1084 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1085
1086 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1087 ALOGW("invalid signal time for frame %d", (int) frame.number);
1088 return -1;
1089 }
1090
1091 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1092 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1093 return -1;
1094 }
1095
1096 return actualRenderTimeNs;
1097}
1098
1099void CCodecBufferChannel::pollForRenderedBuffers() {
1100 FrameEventHistoryDelta delta;
1101 mComponent->pollForRenderedFrames(&delta);
1102 processRenderedFrames(delta);
1103}
1104
Pawin Vongmasa36653902018-11-15 00:10:25 -08001105status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1106 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1107 bool released = false;
1108 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001109 Mutexed<Input>::Locked input(mInput);
1110 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001111 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001112 }
1113 }
1114 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001115 Mutexed<Output>::Locked output(mOutput);
1116 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001117 released = true;
1118 }
1119 }
1120 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001121 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001122 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001123 } else {
1124 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1125 }
1126 return OK;
1127}
1128
1129void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1130 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001131 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001132
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001133 if (!input->buffers) {
1134 ALOGE("getInputBufferArray: No Input Buffers allocated");
1135 return;
1136 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001137 if (!input->buffers->isArrayMode()) {
1138 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001139 }
1140
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001141 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001142}
1143
1144void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1145 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001146 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001147 if (!output->buffers) {
1148 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1149 return;
1150 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001151 if (!output->buffers->isArrayMode()) {
1152 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001153 }
1154
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001155 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001156}
1157
1158status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001159 const sp<AMessage> &inputFormat,
1160 const sp<AMessage> &outputFormat,
1161 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001162 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1163 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001164 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001165 C2PortReorderBufferDepthTuning::output reorderDepth;
1166 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001167 C2PortActualDelayTuning::input inputDelay(0);
1168 C2PortActualDelayTuning::output outputDelay(0);
1169 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001170 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001171
Pawin Vongmasa36653902018-11-15 00:10:25 -08001172 c2_status_t err = mComponent->query(
1173 {
1174 &iStreamFormat,
1175 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001176 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001177 &reorderDepth,
1178 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001179 &inputDelay,
1180 &pipelineDelay,
1181 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001182 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001183 },
1184 {},
1185 C2_DONT_BLOCK,
1186 nullptr);
1187 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001188 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001189 return UNKNOWN_ERROR;
1190 }
1191 } else if (err != C2_OK) {
1192 return UNKNOWN_ERROR;
1193 }
1194
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001195 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1196 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1197 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1198
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001199 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1200 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001201
Pawin Vongmasa36653902018-11-15 00:10:25 -08001202 // TODO: get this from input format
1203 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1204
Sungtak Lee04b30352020-07-27 13:57:25 -07001205 // secure mode is a static parameter (shall not change in the executing state)
1206 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1207
Pawin Vongmasa36653902018-11-15 00:10:25 -08001208 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001209 int poolMask = GetCodec2PoolMask();
1210 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001211
1212 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001213 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001214 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001215 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1216 API_REFLECTION |
1217 API_VALUES |
1218 API_CURRENT_VALUES |
1219 API_DEPENDENCY |
1220 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001221 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1222 C2StreamSampleRateInfo::input sampleRate(0u);
1223 C2StreamChannelCountInfo::input channelCount(0u);
1224 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001225 std::shared_ptr<C2BlockPool> pool;
1226 {
1227 Mutexed<BlockPools>::Locked pools(mBlockPools);
1228
1229 // set default allocator ID.
1230 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001231 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001232
1233 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1234 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1235 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001236 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001237 std::vector<C2Param *> stackParams({&featuresSetting});
1238 if (audioEncoder) {
1239 stackParams.push_back(&encoderFrameSize);
1240 stackParams.push_back(&sampleRate);
1241 stackParams.push_back(&channelCount);
1242 stackParams.push_back(&pcmEncoding);
1243 } else {
1244 encoderFrameSize.invalidate();
1245 sampleRate.invalidate();
1246 channelCount.invalidate();
1247 pcmEncoding.invalidate();
1248 }
1249 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001250 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1251 C2_DONT_BLOCK,
1252 &params);
1253 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1254 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1255 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001256 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001257 C2PortAllocatorsTuning::input *inputAllocators =
1258 C2PortAllocatorsTuning::input::From(params[0].get());
1259 if (inputAllocators && inputAllocators->flexCount() > 0) {
1260 std::shared_ptr<C2Allocator> allocator;
1261 // verify allocator IDs and resolve default allocator
1262 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1263 if (allocator) {
1264 pools->inputAllocatorId = allocator->getId();
1265 } else {
1266 ALOGD("[%s] component requested invalid input allocator ID %u",
1267 mName, inputAllocators->m.values[0]);
1268 }
1269 }
1270 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001271 if (featuresSetting) {
1272 apiFeatures = featuresSetting.value;
1273 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001274
1275 // TODO: use C2Component wrapper to associate this pool with ourselves
1276 if ((poolMask >> pools->inputAllocatorId) & 1) {
1277 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1278 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1279 mName, pools->inputAllocatorId,
1280 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1281 asString(err), err);
1282 } else {
1283 err = C2_NOT_FOUND;
1284 }
1285 if (err != C2_OK) {
1286 C2BlockPool::local_id_t inputPoolId =
1287 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1288 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1289 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1290 mName, (unsigned long long)inputPoolId,
1291 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1292 asString(err), err);
1293 if (err != C2_OK) {
1294 return NO_MEMORY;
1295 }
1296 }
1297 pools->inputPool = pool;
1298 }
1299
Wonsik Kim51051262018-11-28 13:59:05 -08001300 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001301 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001302 input->inputDelay = inputDelayValue;
1303 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001304 input->numSlots = numInputSlots;
1305 input->extraBuffers.flush();
1306 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001307 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001308 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1309 input->frameReassembler.init(
1310 pool,
1311 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1312 encoderFrameSize.value,
1313 sampleRate.value,
1314 channelCount.value,
1315 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1316 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001317 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1318 // For encrypted content, framework decrypts source buffer (ashmem) into
1319 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001320 if (!buffersBoundToCodec
1321 && !input->frameReassembler
1322 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001323 input->buffers.reset(new SlotInputBuffers(mName));
1324 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001325 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001326 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001327 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001328 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001329 // This is to ensure buffers do not get released prematurely.
1330 // TODO: handle this without going into array mode
1331 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001332 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001333 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001334 }
1335 } else {
1336 if (hasCryptoOrDescrambler()) {
1337 int32_t capacity = kLinearBufferSize;
1338 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1339 if ((size_t)capacity > kMaxLinearBufferSize) {
1340 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1341 capacity = kMaxLinearBufferSize;
1342 }
1343 if (mDealer == nullptr) {
1344 mDealer = new MemoryDealer(
1345 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001346 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001347 "EncryptedLinearInputBuffers");
1348 mDecryptDestination = mDealer->allocate((size_t)capacity);
1349 }
1350 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001351 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1352 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001353 } else {
1354 mHeapSeqNum = -1;
1355 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001356 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001357 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001358 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001359 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001360 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001361 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001362 }
1363 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001364 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001365
1366 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001367 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001368 } else {
1369 // TODO: error
1370 }
Wonsik Kim51051262018-11-28 13:59:05 -08001371
1372 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001373 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001374 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001375 }
1376
1377 if (outputFormat != nullptr) {
1378 sp<IGraphicBufferProducer> outputSurface;
1379 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001380 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001381 {
1382 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001383 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001384 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001385 outputSurface = output->surface ?
1386 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001387 if (outputSurface) {
1388 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1389 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001390 outputGeneration = output->generation;
1391 }
1392
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001393 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001395 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001396
1397 {
1398 Mutexed<BlockPools>::Locked pools(mBlockPools);
1399
David Stevensc3fbb282021-01-18 18:11:20 +09001400 prevOutputPoolId = pools->outputPoolId;
1401
Pawin Vongmasa36653902018-11-15 00:10:25 -08001402 // set default allocator ID.
1403 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001404 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001405
1406 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1407 // unsuccessful.
1408 std::vector<std::unique_ptr<C2Param>> params;
1409 err = mComponent->query({ },
1410 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1411 C2_DONT_BLOCK,
1412 &params);
1413 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1414 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1415 mName, params.size(), asString(err), err);
1416 } else if (err == C2_OK && params.size() == 1) {
1417 C2PortAllocatorsTuning::output *outputAllocators =
1418 C2PortAllocatorsTuning::output::From(params[0].get());
1419 if (outputAllocators && outputAllocators->flexCount() > 0) {
1420 std::shared_ptr<C2Allocator> allocator;
1421 // verify allocator IDs and resolve default allocator
1422 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1423 if (allocator) {
1424 pools->outputAllocatorId = allocator->getId();
1425 } else {
1426 ALOGD("[%s] component requested invalid output allocator ID %u",
1427 mName, outputAllocators->m.values[0]);
1428 }
1429 }
1430 }
1431
1432 // use bufferqueue if outputting to a surface.
1433 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1434 // if unsuccessful.
1435 if (outputSurface) {
1436 params.clear();
1437 err = mComponent->query({ },
1438 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1439 C2_DONT_BLOCK,
1440 &params);
1441 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1442 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1443 mName, params.size(), asString(err), err);
1444 } else if (err == C2_OK && params.size() == 1) {
1445 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1446 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1447 if (surfaceAllocator) {
1448 std::shared_ptr<C2Allocator> allocator;
1449 // verify allocator IDs and resolve default allocator
1450 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1451 if (allocator) {
1452 pools->outputAllocatorId = allocator->getId();
1453 } else {
1454 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1455 mName, surfaceAllocator->value);
1456 err = C2_BAD_VALUE;
1457 }
1458 }
1459 }
1460 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1461 && err != C2_OK
1462 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1463 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1464 }
1465 }
1466
1467 if ((poolMask >> pools->outputAllocatorId) & 1) {
1468 err = mComponent->createBlockPool(
1469 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1470 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1471 mName, pools->outputAllocatorId,
1472 (unsigned long long)pools->outputPoolId,
1473 asString(err));
1474 } else {
1475 err = C2_NOT_FOUND;
1476 }
1477 if (err != C2_OK) {
1478 // use basic pool instead
1479 pools->outputPoolId =
1480 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1481 }
1482
1483 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1484 // component.
1485 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1486 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1487
1488 std::vector<std::unique_ptr<C2SettingResult>> failures;
1489 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1490 ALOGD("[%s] Configured output block pool ids %llu => %s",
1491 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1492 outputPoolId_ = pools->outputPoolId;
1493 }
1494
David Stevensc3fbb282021-01-18 18:11:20 +09001495 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1496 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1497 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1498 if (err != C2_OK) {
1499 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1500 (unsigned long long) prevOutputPoolId, asString(err), err);
1501 }
1502 }
1503
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001504 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001505 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001506 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001507 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001508 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001509 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001510 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001511 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001512 }
1513 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001514 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001515 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001516 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001517
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001518 output->buffers->clearStash();
1519 if (reorderDepth) {
1520 output->buffers->setReorderDepth(reorderDepth.value);
1521 }
1522 if (reorderKey) {
1523 output->buffers->setReorderKey(reorderKey.value);
1524 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001525
1526 // Try to set output surface to created block pool if given.
1527 if (outputSurface) {
1528 mComponent->setOutputSurface(
1529 outputPoolId_,
1530 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001531 outputGeneration,
1532 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001533 } else {
1534 // configure CPU read consumer usage
1535 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1536 std::vector<std::unique_ptr<C2SettingResult>> failures;
1537 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1538 // do not print error message for now as most components may not yet
1539 // support this setting
1540 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1541 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001542 }
1543
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001544 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001545 if (buffersBoundToCodec) {
1546 // WORKAROUND: if we're using early CSD workaround we convert to
1547 // array mode, to appease apps assuming the output
1548 // buffers to be of the same size.
1549 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1550 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001551
1552 int32_t channelCount;
1553 int32_t sampleRate;
1554 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1555 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1556 int32_t delay = 0;
1557 int32_t padding = 0;;
1558 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1559 delay = 0;
1560 }
1561 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1562 padding = 0;
1563 }
1564 if (delay || padding) {
1565 // We need write access to the buffers, and we're already in
1566 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001567 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001568 }
1569 }
1570 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001571
1572 int32_t tunneled = 0;
1573 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1574 tunneled = 0;
1575 }
1576 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001577 }
1578
1579 // Set up pipeline control. This has to be done after mInputBuffers and
1580 // mOutputBuffers are initialized to make sure that lingering callbacks
1581 // about buffers from the previous generation do not interfere with the
1582 // newly initialized pipeline capacity.
1583
Wonsik Kim62545252021-01-20 11:25:41 -08001584 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001585 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001586 watcher->inputDelay(inputDelayValue)
1587 .pipelineDelay(pipelineDelayValue)
1588 .outputDelay(outputDelayValue)
Houxiang Dai0b573282023-03-11 18:31:56 +08001589 .smoothnessFactor(kSmoothnessFactor)
1590 .tunneled(mTunneled);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001591 watcher->flush();
1592 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001593
1594 mInputMetEos = false;
1595 mSync.start();
1596 return OK;
1597}
1598
Wonsik Kim34b28b42022-05-20 15:49:32 -07001599status_t CCodecBufferChannel::prepareInitialInputBuffers(
1600 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001601 if (mInputSurface) {
1602 return OK;
1603 }
1604
Wonsik Kim34b28b42022-05-20 15:49:32 -07001605 size_t numInputSlots = mInput.lock()->numSlots;
1606
1607 {
1608 Mutexed<Input>::Locked input(mInput);
1609 while (clientInputBuffers->size() < numInputSlots) {
1610 size_t index;
1611 sp<MediaCodecBuffer> buffer;
1612 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1613 break;
1614 }
1615 clientInputBuffers->emplace(index, buffer);
1616 }
1617 }
1618 if (clientInputBuffers->empty()) {
1619 ALOGW("[%s] start: cannot allocate memory at all", mName);
1620 return NO_MEMORY;
1621 } else if (clientInputBuffers->size() < numInputSlots) {
1622 ALOGD("[%s] start: cannot allocate memory for all slots, "
1623 "only %zu buffers allocated",
1624 mName, clientInputBuffers->size());
1625 } else {
1626 ALOGV("[%s] %zu initial input buffers available",
1627 mName, clientInputBuffers->size());
1628 }
1629 return OK;
1630}
1631
1632status_t CCodecBufferChannel::requestInitialInputBuffers(
1633 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001634 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001635 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1636 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1637 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001638 return UNKNOWN_ERROR;
1639 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001640
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001641 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1642 mFlushedConfigs.lock()->swap(flushedConfigs);
1643 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001644 {
1645 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1646 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1647 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1648 watcher->onWorkQueued(
1649 work->input.ordinal.frameIndex.peeku(),
1650 std::vector(work->input.buffers),
1651 now);
1652 }
1653 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001654 err = mComponent->queue(&flushedConfigs);
1655 if (err != C2_OK) {
1656 ALOGW("[%s] Error while queueing a flushed config", mName);
1657 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001658 }
1659 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001660 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001661 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1662 !clientInputBuffers.empty()) {
1663 size_t minIndex = clientInputBuffers.begin()->first;
1664 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1665 for (const auto &[index, buffer] : clientInputBuffers) {
1666 if (minBuffer->capacity() > buffer->capacity()) {
1667 minIndex = index;
1668 minBuffer = buffer;
1669 }
1670 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001671 // WORKAROUND: Some apps expect CSD available without queueing
1672 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001673 minBuffer->setRange(0, 0);
1674 minBuffer->meta()->clear();
1675 minBuffer->meta()->setInt64("timeUs", 0);
1676 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001677 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1678 mName);
1679 return UNKNOWN_ERROR;
1680 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001681 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001682 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001683
Wonsik Kim34b28b42022-05-20 15:49:32 -07001684 for (const auto &[index, buffer] : clientInputBuffers) {
1685 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001686 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001687
Pawin Vongmasa36653902018-11-15 00:10:25 -08001688 return OK;
1689}
1690
1691void CCodecBufferChannel::stop() {
1692 mSync.stop();
1693 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001694}
1695
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001696void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
1697 sp<Surface> surface = mOutputSurface.lock()->surface;
1698 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00001699 C2BlockPool::local_id_t outputPoolId;
1700 {
1701 Mutexed<BlockPools>::Locked pools(mBlockPools);
1702 outputPoolId = pools->outputPoolId;
1703 }
1704 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001705
1706 if (pushBlankBuffer) {
1707 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
1708 if (anw) {
1709 pushBlankBuffersToNativeWindow(anw.get());
1710 }
1711 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00001712 }
1713}
1714
Wonsik Kim936a89c2020-05-08 16:07:50 -07001715void CCodecBufferChannel::reset() {
1716 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001717 if (mInputSurface != nullptr) {
1718 mInputSurface.reset();
1719 }
1720 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001721 {
1722 Mutexed<Input>::Locked input(mInput);
1723 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001724 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001725 }
1726 {
1727 Mutexed<Output>::Locked output(mOutput);
1728 output->buffers.reset();
1729 }
Brian Lindahlc953b462023-01-27 16:21:43 -07001730 // reset the frames that are being tracked for onFrameRendered callbacks
1731 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001732}
1733
1734void CCodecBufferChannel::release() {
1735 mComponent.reset();
1736 mInputAllocator.reset();
1737 mOutputSurface.lock()->surface.clear();
1738 {
1739 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1740 blockPools->inputPool.reset();
1741 blockPools->outputPoolIntf.reset();
1742 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001743 setCrypto(nullptr);
1744 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001745}
1746
Pawin Vongmasa36653902018-11-15 00:10:25 -08001747void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1748 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001749 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001750 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001751 {
1752 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1753 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1754 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1755 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1756 watcher->onWorkDone(frameIndex);
1757 continue;
1758 }
1759 if (work->input.buffers.empty()
1760 || work->input.buffers.front() == nullptr
1761 || work->input.buffers.front()->data().linearBlocks().empty()) {
1762 ALOGD("[%s] no linear codec config data found", mName);
1763 watcher->onWorkDone(frameIndex);
1764 continue;
1765 }
1766 std::unique_ptr<C2Work> copy(new C2Work);
1767 copy->input.flags = C2FrameData::flags_t(
1768 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1769 copy->input.ordinal = work->input.ordinal;
1770 copy->input.ordinal.frameIndex = mFrameIndex++;
1771 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1772 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1773 }
1774 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1775 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1776 }
1777 copy->input.infoBuffers.insert(
1778 copy->input.infoBuffers.begin(),
1779 work->input.infoBuffers.begin(),
1780 work->input.infoBuffers.end());
1781 copy->worklets.emplace_back(new C2Worklet);
1782 configs.push_back(std::move(copy));
1783 watcher->onWorkDone(frameIndex);
1784 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001785 }
1786 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001787 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001788 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001789 Mutexed<Input>::Locked input(mInput);
1790 input->buffers->flush();
1791 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001792 }
1793 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001794 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001795 if (output->buffers) {
1796 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001797 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001798 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001799 }
Brian Lindahlc953b462023-01-27 16:21:43 -07001800 // reset the frames that are being tracked for onFrameRendered callbacks
1801 mTrackedFrames.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001802}
1803
1804void CCodecBufferChannel::onWorkDone(
1805 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001806 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001807 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001808 feedInputBufferIfAvailable();
1809 }
1810}
1811
1812void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001813 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001814 if (mInputSurface) {
1815 return;
1816 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001817 std::shared_ptr<C2Buffer> buffer =
1818 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001819 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001820 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001821 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001822 if (input->lastFlushIndex >= frameIndex) {
1823 ALOGD("[%s] Ignoring stale input buffer done callback: "
1824 "last flush index = %lld, frameIndex = %lld",
1825 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1826 } else {
1827 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1828 if (!newInputSlotAvailable) {
1829 (void)input->extraBuffers.expireComponentBuffer(buffer);
1830 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001831 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001832 }
1833 if (newInputSlotAvailable) {
1834 feedInputBufferIfAvailable();
1835 }
1836}
1837
1838bool CCodecBufferChannel::handleWork(
1839 std::unique_ptr<C2Work> work,
1840 const sp<AMessage> &outputFormat,
1841 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001842 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001843 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001844 if (!output->buffers) {
1845 return false;
1846 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001847 }
1848
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001849 // Whether the output buffer should be reported to the client or not.
1850 bool notifyClient = false;
1851
1852 if (work->result == C2_OK){
1853 notifyClient = true;
1854 } else if (work->result == C2_NOT_FOUND) {
1855 ALOGD("[%s] flushed work; ignored.", mName);
1856 } else {
1857 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1858 // the config update.
1859 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1860 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1861 return false;
1862 }
1863
1864 if ((work->input.ordinal.frameIndex -
1865 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001866 // Discard frames from previous generation.
1867 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001868 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001869 }
1870
Wonsik Kim524b0582019-03-12 11:28:57 -07001871 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001872 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001873 || !(work->worklets.front()->output.flags &
1874 C2FrameData::FLAG_INCOMPLETE))) {
1875 mPipelineWatcher.lock()->onWorkDone(
1876 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001877 }
1878
1879 // NOTE: MediaCodec usage supposedly have only one worklet
1880 if (work->worklets.size() != 1u) {
1881 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1882 mName, work->worklets.size());
1883 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1884 return false;
1885 }
1886
1887 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1888
1889 std::shared_ptr<C2Buffer> buffer;
1890 // NOTE: MediaCodec usage supposedly have only one output stream.
1891 if (worklet->output.buffers.size() > 1u) {
1892 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1893 mName, worklet->output.buffers.size());
1894 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1895 return false;
1896 } else if (worklet->output.buffers.size() == 1u) {
1897 buffer = worklet->output.buffers[0];
1898 if (!buffer) {
1899 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1900 }
1901 }
1902
Wonsik Kim3dedf682021-05-03 10:57:09 -07001903 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1904 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001905 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001906 while (!worklet->output.configUpdate.empty()) {
1907 std::unique_ptr<C2Param> param;
1908 worklet->output.configUpdate.back().swap(param);
1909 worklet->output.configUpdate.pop_back();
1910 switch (param->coreIndex().coreIndex()) {
1911 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1912 C2PortReorderBufferDepthTuning::output reorderDepth;
1913 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001914 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1915 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001916 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001917 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001918 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001919 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1920 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001921 }
1922 break;
1923 }
1924 case C2PortReorderKeySetting::CORE_INDEX: {
1925 C2PortReorderKeySetting::output reorderKey;
1926 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001927 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001928 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1929 mName, reorderKey.value);
1930 } else {
1931 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1932 }
1933 break;
1934 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001935 case C2PortActualDelayTuning::CORE_INDEX: {
1936 if (param->isGlobal()) {
1937 C2ActualPipelineDelayTuning pipelineDelay;
1938 if (pipelineDelay.updateFrom(*param)) {
1939 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1940 mName, pipelineDelay.value);
1941 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001942 (void)mPipelineWatcher.lock()->pipelineDelay(
1943 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001944 }
1945 }
1946 if (param->forInput()) {
1947 C2PortActualDelayTuning::input inputDelay;
1948 if (inputDelay.updateFrom(*param)) {
1949 ALOGV("[%s] onWorkDone: updating input delay %u",
1950 mName, inputDelay.value);
1951 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001952 (void)mPipelineWatcher.lock()->inputDelay(
1953 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001954 }
1955 }
1956 if (param->forOutput()) {
1957 C2PortActualDelayTuning::output outputDelay;
1958 if (outputDelay.updateFrom(*param)) {
1959 ALOGV("[%s] onWorkDone: updating output delay %u",
1960 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001961 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001962 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001963 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001964
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001965 }
1966 }
1967 break;
1968 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001969 case C2PortTunnelSystemTime::CORE_INDEX: {
1970 C2PortTunnelSystemTime::output frameRenderTime;
1971 if (frameRenderTime.updateFrom(*param)) {
1972 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1973 mName, (long long)frameRenderTime.value,
1974 (long long)worklet->output.ordinal.timestamp.peekll());
1975 mCCodecCallback->onOutputFramesRendered(
1976 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1977 }
1978 break;
1979 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001980 case C2StreamTunnelHoldRender::CORE_INDEX: {
1981 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1982 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1983 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1984 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1985 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1986 mCCodecCallback->onFirstTunnelFrameReady();
1987 break;
1988 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001989 default:
1990 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1991 mName, param->index());
1992 break;
1993 }
1994 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001995 if (newInputDelay || newPipelineDelay) {
1996 Mutexed<Input>::Locked input(mInput);
1997 size_t newNumSlots =
1998 newInputDelay.value_or(input->inputDelay) +
1999 newPipelineDelay.value_or(input->pipelineDelay) +
2000 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08002001 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002002 if (input->buffers->isArrayMode()) {
2003 if (input->numSlots >= newNumSlots) {
2004 input->numExtraSlots = 0;
2005 } else {
2006 input->numExtraSlots = newNumSlots - input->numSlots;
2007 }
2008 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2009 mName, input->numExtraSlots);
2010 } else {
2011 input->numSlots = newNumSlots;
2012 }
2013 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002014 size_t numOutputSlots = 0;
2015 uint32_t reorderDepth = 0;
2016 bool outputBuffersChanged = false;
2017 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2018 Mutexed<Output>::Locked output(mOutput);
2019 if (!output->buffers) {
2020 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002021 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002022 numOutputSlots = output->numSlots;
2023 if (newReorderKey) {
2024 output->buffers->setReorderKey(newReorderKey.value());
2025 }
2026 if (newReorderDepth) {
2027 output->buffers->setReorderDepth(newReorderDepth.value());
2028 }
2029 reorderDepth = output->buffers->getReorderDepth();
2030 if (newOutputDelay) {
2031 output->outputDelay = newOutputDelay.value();
2032 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2033 if (output->numSlots < numOutputSlots) {
2034 output->numSlots = numOutputSlots;
2035 if (output->buffers->isArrayMode()) {
2036 OutputBuffersArray *array =
2037 (OutputBuffersArray *)output->buffers.get();
2038 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2039 mName, numOutputSlots);
2040 array->grow(numOutputSlots);
2041 outputBuffersChanged = true;
2042 }
2043 }
2044 }
2045 numOutputSlots = output->numSlots;
2046 }
2047 if (outputBuffersChanged) {
2048 mCCodecCallback->onOutputBuffersChanged();
2049 }
2050 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002051 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002052 {
2053 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2054 maxDequeueCount = output->maxDequeueBuffers =
2055 numOutputSlots + reorderDepth + kRenderingDepth;
2056 if (output->surface) {
2057 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2058 }
2059 }
2060 if (maxDequeueCount > 0) {
2061 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002062 }
2063 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002064
Pawin Vongmasa36653902018-11-15 00:10:25 -08002065 int32_t flags = 0;
2066 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002067 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002068 ALOGV("[%s] onWorkDone: output EOS", mName);
2069 }
2070
Pawin Vongmasa36653902018-11-15 00:10:25 -08002071 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2072 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2073 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2074 // shall correspond to the client input timesamp (in customOrdinal). By using the
2075 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2076 // produces multiple output.
2077 c2_cntr64_t timestamp =
2078 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2079 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002080 if (mInputSurface != nullptr) {
2081 // When using input surface we need to restore the original input timestamp.
2082 timestamp = work->input.ordinal.customOrdinal;
2083 }
My Name6bd9a7d2022-03-25 12:37:58 -07002084 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2085 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002086 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2087 mName,
2088 work->input.ordinal.customOrdinal.peekll(),
2089 work->input.ordinal.timestamp.peekll(),
2090 worklet->output.ordinal.timestamp.peekll(),
2091 timestamp.peekll());
2092
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002093 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002094 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002095 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002096 if (!output->buffers) {
2097 return false;
2098 }
2099 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002100 output->buffers->updateSkipCutBuffer(outputFormat);
2101 output->buffers->setFormat(outputFormat);
2102 }
2103 if (!notifyClient) {
2104 return false;
2105 }
2106 size_t index;
2107 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002108 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002109 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002110 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002111 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2112
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002113 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002114 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002115 } else {
2116 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002117 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002118 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002119 return false;
2120 }
2121 }
2122
Wonsik Kimec585c32021-10-01 01:11:00 -07002123 bool drop = false;
2124 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2125 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2126 drop = true;
2127 }
2128
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002129 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002130 if (mTunneled && drop && outputFormat) {
Houxiang Daie74e5062022-05-19 15:32:54 +08002131 if (mOutputFormat != outputFormat) {
2132 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2133 mName, work->input.ordinal.frameIndex.peekull());
2134 mOutputFormat = outputFormat;
2135 } else {
2136 ALOGV("[%s] onWorkDone: Not reporting output buffer without format change (%lld)",
2137 mName, work->input.ordinal.frameIndex.peekull());
2138 notifyClient = false;
2139 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002140 } else {
2141 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2142 mName, work->input.ordinal.frameIndex.peekull());
2143 notifyClient = false;
2144 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002145 }
2146
2147 if (buffer) {
2148 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2149 // TODO: properly translate these to metadata
2150 switch (info->coreIndex().coreIndex()) {
2151 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002152 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002153 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002154 }
2155 break;
2156 default:
2157 break;
2158 }
2159 }
2160 }
2161
2162 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002163 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002164 if (!output->buffers) {
2165 return false;
2166 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002167 output->buffers->pushToStash(
2168 buffer,
2169 notifyClient,
2170 timestamp.peek(),
2171 flags,
2172 outputFormat,
2173 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002174 }
2175 sendOutputBuffers();
2176 return true;
2177}
2178
2179void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002180 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002181 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002182 sp<MediaCodecBuffer> outBuffer;
2183 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002184
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002185 constexpr int kMaxReallocTry = 5;
2186 int reallocTryNum = 0;
2187
Pawin Vongmasa36653902018-11-15 00:10:25 -08002188 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002189 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002190 if (!output->buffers) {
2191 return;
2192 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002193 action = output->buffers->popFromStashAndRegister(
2194 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002195 if (action != OutputBuffers::REALLOCATE) {
2196 reallocTryNum = 0;
2197 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002198 switch (action) {
2199 case OutputBuffers::SKIP:
2200 return;
2201 case OutputBuffers::DISCARD:
2202 break;
2203 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00002204 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002205 mCallback->onOutputBufferAvailable(index, outBuffer);
2206 break;
2207 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002208 if (++reallocTryNum > kMaxReallocTry) {
2209 output.unlock();
2210 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2211 mName, kMaxReallocTry);
2212 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2213 return;
2214 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002215 if (!output->buffers->isArrayMode()) {
2216 output->buffers =
2217 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002218 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002219 static_cast<OutputBuffersArray*>(output->buffers.get())->
2220 realloc(c2Buffer);
2221 output.unlock();
2222 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002223 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002224 case OutputBuffers::RETRY:
2225 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2226 mName);
2227 return;
2228 default:
2229 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2230 "corrupted BufferAction value (%d) "
2231 "returned from popFromStashAndRegister.",
2232 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002233 return;
2234 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002235 }
2236}
2237
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002238status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002239 static std::atomic_uint32_t surfaceGeneration{0};
2240 uint32_t generation = (getpid() << 10) |
2241 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2242 & ((1 << 10) - 1));
2243
2244 sp<IGraphicBufferProducer> producer;
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002245 int maxDequeueCount;
2246 sp<Surface> oldSurface;
2247 {
2248 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2249 maxDequeueCount = outputSurface->maxDequeueBuffers;
2250 oldSurface = outputSurface->surface;
2251 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002252 if (newSurface) {
2253 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002254 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002255 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002256 producer = newSurface->getIGraphicBufferProducer();
2257 producer->setGenerationNumber(generation);
2258 } else {
2259 ALOGE("[%s] setting output surface to null", mName);
2260 return INVALID_OPERATION;
2261 }
2262
2263 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2264 C2BlockPool::local_id_t outputPoolId;
2265 {
2266 Mutexed<BlockPools>::Locked pools(mBlockPools);
2267 outputPoolId = pools->outputPoolId;
2268 outputPoolIntf = pools->outputPoolIntf;
2269 }
2270
2271 if (outputPoolIntf) {
2272 if (mComponent->setOutputSurface(
2273 outputPoolId,
2274 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002275 generation,
2276 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002277 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2278 return INVALID_OPERATION;
2279 }
2280 }
2281
2282 {
2283 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2284 output->surface = newSurface;
2285 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002286 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002287 }
2288
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002289 if (oldSurface && pushBlankBuffer) {
2290 // When ReleaseSurface was set from MediaCodec,
2291 // pushing a blank buffer at the end might be necessary.
2292 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2293 if (anw) {
2294 pushBlankBuffersToNativeWindow(anw.get());
2295 }
2296 }
2297
Pawin Vongmasa36653902018-11-15 00:10:25 -08002298 return OK;
2299}
2300
Wonsik Kimab34ed62019-01-31 15:28:46 -08002301PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002302 // Otherwise, component may have stalled work due to input starvation up to
2303 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002304 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2305 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002306 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002307 size_t outputDelay = mOutput.lock()->outputDelay;
2308 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002309 Mutexed<Input>::Locked input(mInput);
2310 n = input->inputDelay + input->pipelineDelay + outputDelay;
2311 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002312 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002313}
2314
Pawin Vongmasa36653902018-11-15 00:10:25 -08002315void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2316 mMetaMode = mode;
2317}
2318
Wonsik Kim596187e2019-10-25 12:44:10 -07002319void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002320 if (mCrypto != nullptr) {
2321 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2322 mCrypto->unsetHeap(entry.second);
2323 }
2324 mHeapSeqNumMap.clear();
2325 if (mHeapSeqNum >= 0) {
2326 mCrypto->unsetHeap(mHeapSeqNum);
2327 mHeapSeqNum = -1;
2328 }
2329 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002330 mCrypto = crypto;
2331}
2332
2333void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2334 mDescrambler = descrambler;
2335}
2336
Pawin Vongmasa36653902018-11-15 00:10:25 -08002337status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2338 // C2_OK is always translated to OK.
2339 if (c2s == C2_OK) {
2340 return OK;
2341 }
2342
2343 // Operation-dependent translation
2344 // TODO: Add as necessary
2345 switch (c2op) {
2346 case C2_OPERATION_Component_start:
2347 switch (c2s) {
2348 case C2_NO_MEMORY:
2349 return NO_MEMORY;
2350 default:
2351 return UNKNOWN_ERROR;
2352 }
2353 default:
2354 break;
2355 }
2356
2357 // Backup operation-agnostic translation
2358 switch (c2s) {
2359 case C2_BAD_INDEX:
2360 return BAD_INDEX;
2361 case C2_BAD_VALUE:
2362 return BAD_VALUE;
2363 case C2_BLOCKING:
2364 return WOULD_BLOCK;
2365 case C2_DUPLICATE:
2366 return ALREADY_EXISTS;
2367 case C2_NO_INIT:
2368 return NO_INIT;
2369 case C2_NO_MEMORY:
2370 return NO_MEMORY;
2371 case C2_NOT_FOUND:
2372 return NAME_NOT_FOUND;
2373 case C2_TIMED_OUT:
2374 return TIMED_OUT;
2375 case C2_BAD_STATE:
2376 case C2_CANCELED:
2377 case C2_CANNOT_DO:
2378 case C2_CORRUPTED:
2379 case C2_OMITTED:
2380 case C2_REFUSED:
2381 return UNKNOWN_ERROR;
2382 default:
2383 return -static_cast<status_t>(c2s);
2384 }
2385}
2386
Pawin Vongmasa36653902018-11-15 00:10:25 -08002387} // namespace android