blob: 4083bba01d76d4a3b67490444c0c59c9750821c1 [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright 2017, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010018#include <utils/Errors.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080019#define LOG_TAG "CCodecBufferChannel"
My Name6bd9a7d2022-03-25 12:37:58 -070020#define ATRACE_TAG ATRACE_TAG_VIDEO
Pawin Vongmasa36653902018-11-15 00:10:25 -080021#include <utils/Log.h>
My Name6bd9a7d2022-03-25 12:37:58 -070022#include <utils/Trace.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080023
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070024#include <algorithm>
Wonsik Kim6b2c8be2021-09-28 05:11:04 -070025#include <atomic>
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070026#include <list>
Pawin Vongmasa36653902018-11-15 00:10:25 -080027#include <numeric>
28
29#include <C2AllocatorGralloc.h>
30#include <C2PlatformSupport.h>
31#include <C2BlockInternal.h>
32#include <C2Config.h>
33#include <C2Debug.h>
34
35#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070036#include <android/hardware/drm/1.0/types.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080037#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080038#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080039#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080040#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070041#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080042#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070043#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080044#include <media/openmax/OMX_Core.h>
45#include <media/stagefright/foundation/ABuffer.h>
46#include <media/stagefright/foundation/ALookup.h>
47#include <media/stagefright/foundation/AMessage.h>
48#include <media/stagefright/foundation/AUtils.h>
49#include <media/stagefright/foundation/hexdump.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080050#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070051#include <media/stagefright/SkipCutBuffer.h>
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010052#include <media/stagefright/SurfaceUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080053#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070054#include <mediadrm/ICrypto.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080055#include <system/window.h>
56
57#include "CCodecBufferChannel.h"
58#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080059
60namespace android {
61
62using android::base::StringPrintf;
63using hardware::hidl_handle;
64using hardware::hidl_string;
65using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070066using hardware::fromHeap;
67using hardware::HidlMemory;
68
Pawin Vongmasa36653902018-11-15 00:10:25 -080069using namespace hardware::cas::V1_0;
70using namespace hardware::cas::native::V1_0;
71
72using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070073using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080074
Pawin Vongmasa36653902018-11-15 00:10:25 -080075namespace {
76
Wonsik Kim469c8342019-04-11 16:46:09 -070077constexpr size_t kSmoothnessFactor = 4;
78constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080079
Sungtak Leeab6f2f32019-02-15 14:43:51 -080080// This is for keeping IGBP's buffer dropping logic in legacy mode other
81// than making it non-blocking. Do not change this value.
82const static size_t kDequeueTimeoutNs = 0;
83
Pawin Vongmasa36653902018-11-15 00:10:25 -080084} // namespace
85
86CCodecBufferChannel::QueueGuard::QueueGuard(
87 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
88 Mutex::Autolock l(mSync.mGuardLock);
89 // At this point it's guaranteed that mSync is not under state transition,
90 // as we are holding its mutex.
91
92 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
93 if (count->value == -1) {
94 mRunning = false;
95 } else {
96 ++count->value;
97 mRunning = true;
98 }
99}
100
101CCodecBufferChannel::QueueGuard::~QueueGuard() {
102 if (mRunning) {
103 // We are not holding mGuardLock at this point so that QueueSync::stop() can
104 // keep holding the lock until mCount reaches zero.
105 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
106 --count->value;
107 count->cond.broadcast();
108 }
109}
110
111void CCodecBufferChannel::QueueSync::start() {
112 Mutex::Autolock l(mGuardLock);
113 // If stopped, it goes to running state; otherwise no-op.
114 Mutexed<Counter>::Locked count(mCount);
115 if (count->value == -1) {
116 count->value = 0;
117 }
118}
119
120void CCodecBufferChannel::QueueSync::stop() {
121 Mutex::Autolock l(mGuardLock);
122 Mutexed<Counter>::Locked count(mCount);
123 if (count->value == -1) {
124 // no-op
125 return;
126 }
127 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
128 // mCount can only decrement. In other words, threads that acquired the lock
129 // are allowed to finish execution but additional threads trying to acquire
130 // the lock at this point will block, and then get QueueGuard at STOPPED
131 // state.
132 while (count->value != 0) {
133 count.waitForCondition(count->cond);
134 }
135 count->value = -1;
136}
137
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700138// Input
139
140CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
141
Pawin Vongmasa36653902018-11-15 00:10:25 -0800142// CCodecBufferChannel
143
144CCodecBufferChannel::CCodecBufferChannel(
145 const std::shared_ptr<CCodecCallback> &callback)
146 : mHeapSeqNum(-1),
147 mCCodecCallback(callback),
148 mFrameIndex(0u),
149 mFirstValidFrameIndex(0u),
150 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700151 mInputMetEos(false),
152 mSendEncryptedInfoBuffer(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700153 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700154 {
155 Mutexed<Input>::Locked input(mInput);
156 input->buffers.reset(new DummyInputBuffers(""));
157 input->extraBuffers.flush();
158 input->inputDelay = 0u;
159 input->pipelineDelay = 0u;
160 input->numSlots = kSmoothnessFactor;
161 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700162 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700163 }
164 {
165 Mutexed<Output>::Locked output(mOutput);
166 output->outputDelay = 0u;
167 output->numSlots = kSmoothnessFactor;
168 }
David Stevensc3fbb282021-01-18 18:11:20 +0900169 {
170 Mutexed<BlockPools>::Locked pools(mBlockPools);
171 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
172 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800173}
174
175CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800176 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800177 mCrypto->unsetHeap(mHeapSeqNum);
178 }
179}
180
181void CCodecBufferChannel::setComponent(
182 const std::shared_ptr<Codec2Client::Component> &component) {
183 mComponent = component;
184 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
185 mName = mComponentName.c_str();
186}
187
188status_t CCodecBufferChannel::setInputSurface(
189 const std::shared_ptr<InputSurfaceWrapper> &surface) {
190 ALOGV("[%s] setInputSurface", mName);
191 mInputSurface = surface;
192 return mInputSurface->connect(mComponent);
193}
194
195status_t CCodecBufferChannel::signalEndOfInputStream() {
196 if (mInputSurface == nullptr) {
197 return INVALID_OPERATION;
198 }
199 return mInputSurface->signalEndOfInputStream();
200}
201
Sungtak Lee04b30352020-07-27 13:57:25 -0700202status_t CCodecBufferChannel::queueInputBufferInternal(
203 sp<MediaCodecBuffer> buffer,
204 std::shared_ptr<C2LinearBlock> encryptedBlock,
205 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800206 int64_t timeUs;
207 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
208
209 if (mInputMetEos) {
210 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
211 return OK;
212 }
213
214 int32_t flags = 0;
215 int32_t tmp = 0;
216 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200217 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800218 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
219 eos = true;
220 mInputMetEos = true;
221 ALOGV("[%s] input EOS", mName);
222 }
223 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
224 flags |= C2FrameData::FLAG_CODEC_CONFIG;
225 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200226 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
227 tunnelFirstFrame = true;
228 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800229 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800230 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800231 std::unique_ptr<C2Work> work(new C2Work);
232 work->input.ordinal.timestamp = timeUs;
233 work->input.ordinal.frameIndex = mFrameIndex++;
234 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
235 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
236 // Keep client timestamp in customOrdinal
237 work->input.ordinal.customOrdinal = timeUs;
238 work->input.buffers.clear();
239
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700240 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800241 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800242
Pawin Vongmasa36653902018-11-15 00:10:25 -0800243 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700244 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800245 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700246 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800247 return -ENOENT;
248 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700249 // TODO: we want to delay copying buffers.
250 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
251 copy = input->buffers->cloneAndReleaseBuffer(buffer);
252 if (copy != nullptr) {
253 (void)input->extraBuffers.assignSlot(copy);
254 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
255 return UNKNOWN_ERROR;
256 }
257 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
258 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
259 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700260 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700261 } else {
262 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
263 "buffer starvation on component.", mName);
264 }
265 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800266 if (input->frameReassembler) {
267 usesFrameReassembler = true;
268 input->frameReassembler.process(buffer, &items);
269 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900270 int32_t cvo = 0;
271 if (buffer->meta()->findInt32("cvo", &cvo)) {
272 int32_t rotation = cvo % 360;
273 // change rotation to counter-clock wise.
274 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
275
276 Mutexed<OutputSurface>::Locked output(mOutputSurface);
277 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
278 output->rotation[frameIndex] = rotation;
279 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800280 work->input.buffers.push_back(c2buffer);
281 if (encryptedBlock) {
282 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
283 kParamIndexEncryptedBuffer,
284 encryptedBlock->share(0, blockSize, C2Fence())));
285 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700286 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800287 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700288 Mutexed<Input>::Locked input(mInput);
289 if (input->frameReassembler) {
290 usesFrameReassembler = true;
291 // drain any pending items with eos
292 input->frameReassembler.process(buffer, &items);
293 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800294 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800295 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800296 if (usesFrameReassembler) {
297 if (!items.empty()) {
298 items.front()->input.configUpdate = std::move(mParamsToBeSet);
299 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
300 }
301 } else {
302 work->input.flags = (C2FrameData::flags_t)flags;
303 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800304
Wonsik Kime1104ca2020-11-24 15:01:33 -0800305 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200306 if (tunnelFirstFrame) {
307 C2StreamTunnelHoldRender::input tunnelHoldRender{
308 0u /* stream */,
309 C2_TRUE /* value */
310 };
311 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
312 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800313 work->worklets.clear();
314 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800315
Wonsik Kime1104ca2020-11-24 15:01:33 -0800316 items.push_back(std::move(work));
317
318 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800319 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800320 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800321 work.reset(new C2Work);
322 work->input.ordinal.timestamp = timeUs;
323 work->input.ordinal.frameIndex = mFrameIndex++;
324 // WORKAROUND: keep client timestamp in customOrdinal
325 work->input.ordinal.customOrdinal = timeUs;
326 work->input.buffers.clear();
327 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800328 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800329 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800330 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800331 c2_status_t err = C2_OK;
332 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700333 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
334 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800335 {
336 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
337 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
338 for (const std::unique_ptr<C2Work> &work : items) {
339 watcher->onWorkQueued(
340 work->input.ordinal.frameIndex.peeku(),
341 std::vector(work->input.buffers),
342 now);
343 }
344 }
345 err = mComponent->queue(&items);
346 }
347 if (err != C2_OK) {
348 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
349 for (const std::unique_ptr<C2Work> &work : items) {
350 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
351 }
352 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700353 Mutexed<Input>::Locked input(mInput);
354 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700355 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700356 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700357 } else if (buffer) {
358 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700359 }
360 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
361 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800362 }
363
364 feedInputBufferIfAvailableInternal();
365 return err;
366}
367
368status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
369 QueueGuard guard(mSync);
370 if (!guard.isRunning()) {
371 ALOGD("[%s] setParameters is only supported in the running state.", mName);
372 return -ENOSYS;
373 }
374 mParamsToBeSet.insert(mParamsToBeSet.end(),
375 std::make_move_iterator(params.begin()),
376 std::make_move_iterator(params.end()));
377 params.clear();
378 return OK;
379}
380
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800381status_t CCodecBufferChannel::attachBuffer(
382 const std::shared_ptr<C2Buffer> &c2Buffer,
383 const sp<MediaCodecBuffer> &buffer) {
384 if (!buffer->copy(c2Buffer)) {
385 return -ENOSYS;
386 }
387 return OK;
388}
389
390void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
391 if (!mDecryptDestination || mDecryptDestination->size() < size) {
392 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
393 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
394 mCrypto->unsetHeap(mHeapSeqNum);
395 }
396 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
397 if (mCrypto) {
398 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
399 }
400 }
401}
402
403int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
404 CHECK(mCrypto);
405 auto it = mHeapSeqNumMap.find(memory);
406 int32_t heapSeqNum = -1;
407 if (it == mHeapSeqNumMap.end()) {
408 heapSeqNum = mCrypto->setHeap(memory);
409 mHeapSeqNumMap.emplace(memory, heapSeqNum);
410 } else {
411 heapSeqNum = it->second;
412 }
413 return heapSeqNum;
414}
415
416status_t CCodecBufferChannel::attachEncryptedBuffer(
417 const sp<hardware::HidlMemory> &memory,
418 bool secure,
419 const uint8_t *key,
420 const uint8_t *iv,
421 CryptoPlugin::Mode mode,
422 CryptoPlugin::Pattern pattern,
423 size_t offset,
424 const CryptoPlugin::SubSample *subSamples,
425 size_t numSubSamples,
426 const sp<MediaCodecBuffer> &buffer) {
427 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
428 static const C2MemoryUsage kDefaultReadWriteUsage{
429 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
430
431 size_t size = 0;
432 for (size_t i = 0; i < numSubSamples; ++i) {
433 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
434 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700435 if (size == 0) {
436 buffer->setRange(0, 0);
437 return OK;
438 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800439 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
440 std::shared_ptr<C2LinearBlock> block;
441 c2_status_t err = pool->fetchLinearBlock(
442 size,
443 secure ? kSecureUsage : kDefaultReadWriteUsage,
444 &block);
445 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700446 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
447 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800448 return NO_MEMORY;
449 }
450 if (!secure) {
451 ensureDecryptDestination(size);
452 }
453 ssize_t result = -1;
454 ssize_t codecDataOffset = 0;
455 if (mCrypto) {
456 AString errorDetailMsg;
457 int32_t heapSeqNum = getHeapSeqNum(memory);
458 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
459 hardware::drm::V1_0::DestinationBuffer dst;
460 if (secure) {
461 dst.type = DrmBufferType::NATIVE_HANDLE;
462 dst.secureMemory = hardware::hidl_handle(block->handle());
463 } else {
464 dst.type = DrmBufferType::SHARED_MEMORY;
465 IMemoryToSharedBuffer(
466 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
467 }
468 result = mCrypto->decrypt(
469 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
470 dst, &errorDetailMsg);
471 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700472 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800473 return result;
474 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800475 } else {
476 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
477 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
478 hidl_vec<SubSample> hidlSubSamples;
479 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
480
481 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
482 hardware::cas::native::V1_0::DestinationBuffer dst;
483 if (secure) {
484 dst.type = BufferType::NATIVE_HANDLE;
485 dst.secureMemory = hardware::hidl_handle(block->handle());
486 } else {
487 dst.type = BufferType::SHARED_MEMORY;
488 dst.nonsecureMemory = src;
489 }
490
491 CasStatus status = CasStatus::OK;
492 hidl_string detailedError;
493 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
494
495 if (key != nullptr) {
496 sctrl = (ScramblingControl)key[0];
497 // Adjust for the PES offset
498 codecDataOffset = key[2] | (key[3] << 8);
499 }
500
501 auto returnVoid = mDescrambler->descramble(
502 sctrl,
503 hidlSubSamples,
504 src,
505 0,
506 dst,
507 0,
508 [&status, &result, &detailedError] (
509 CasStatus _status, uint32_t _bytesWritten,
510 const hidl_string& _detailedError) {
511 status = _status;
512 result = (ssize_t)_bytesWritten;
513 detailedError = _detailedError;
514 });
515
516 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
517 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
518 mName, returnVoid.description().c_str(), status, result);
519 return UNKNOWN_ERROR;
520 }
521
522 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700523 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
524 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800525 return BAD_VALUE;
526 }
527 }
528 if (!secure) {
529 C2WriteView view = block->map().get();
530 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700531 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
532 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800533 return UNKNOWN_ERROR;
534 }
535 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700536 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
537 "(non-secure)",
538 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800539 return UNKNOWN_ERROR;
540 }
541 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
542 }
543 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
544 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
545 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700546 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800547 return -ENOSYS;
548 }
549 return OK;
550}
551
Pawin Vongmasa36653902018-11-15 00:10:25 -0800552status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
553 QueueGuard guard(mSync);
554 if (!guard.isRunning()) {
555 ALOGD("[%s] No more buffers should be queued at current state.", mName);
556 return -ENOSYS;
557 }
558 return queueInputBufferInternal(buffer);
559}
560
561status_t CCodecBufferChannel::queueSecureInputBuffer(
562 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
563 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
564 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
565 AString *errorDetailMsg) {
566 QueueGuard guard(mSync);
567 if (!guard.isRunning()) {
568 ALOGD("[%s] No more buffers should be queued at current state.", mName);
569 return -ENOSYS;
570 }
571
572 if (!hasCryptoOrDescrambler()) {
573 return -ENOSYS;
574 }
575 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
576
Sungtak Lee04b30352020-07-27 13:57:25 -0700577 std::shared_ptr<C2LinearBlock> block;
578 size_t allocSize = buffer->size();
579 size_t bufferSize = 0;
580 c2_status_t blockRes = C2_OK;
581 bool copied = false;
582 if (mSendEncryptedInfoBuffer) {
583 static const C2MemoryUsage kDefaultReadWriteUsage{
584 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
585 constexpr int kAllocGranule0 = 1024 * 64;
586 constexpr int kAllocGranule1 = 1024 * 1024;
587 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
588 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
589 if (allocSize <= kAllocGranule1) {
590 bufferSize = align(allocSize, kAllocGranule0);
591 } else {
592 bufferSize = align(allocSize, kAllocGranule1);
593 }
594 blockRes = pool->fetchLinearBlock(
595 bufferSize, kDefaultReadWriteUsage, &block);
596
597 if (blockRes == C2_OK) {
598 C2WriteView view = block->map().get();
599 if (view.error() == C2_OK && view.size() == bufferSize) {
600 copied = true;
601 // TODO: only copy clear sections
602 memcpy(view.data(), buffer->data(), allocSize);
603 }
604 }
605 }
606
607 if (!copied) {
608 block.reset();
609 }
610
Pawin Vongmasa36653902018-11-15 00:10:25 -0800611 ssize_t result = -1;
612 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700613 if (numSubSamples == 1
614 && subSamples[0].mNumBytesOfClearData == 0
615 && subSamples[0].mNumBytesOfEncryptedData == 0) {
616 // We don't need to go through crypto or descrambler if the input is empty.
617 result = 0;
618 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700619 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800620 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700621 destination.type = DrmBufferType::NATIVE_HANDLE;
622 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800623 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700624 destination.type = DrmBufferType::SHARED_MEMORY;
625 IMemoryToSharedBuffer(
626 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800627 }
Robert Shih895fba92019-07-16 16:29:44 -0700628 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800629 encryptedBuffer->fillSourceBuffer(&source);
630 result = mCrypto->decrypt(
631 key, iv, mode, pattern, source, buffer->offset(),
632 subSamples, numSubSamples, destination, errorDetailMsg);
633 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700634 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800635 return result;
636 }
Robert Shih895fba92019-07-16 16:29:44 -0700637 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800638 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
639 }
640 } else {
641 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
642 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
643 hidl_vec<SubSample> hidlSubSamples;
644 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
645
646 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
647 encryptedBuffer->fillSourceBuffer(&srcBuffer);
648
649 DestinationBuffer dstBuffer;
650 if (secure) {
651 dstBuffer.type = BufferType::NATIVE_HANDLE;
652 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
653 } else {
654 dstBuffer.type = BufferType::SHARED_MEMORY;
655 dstBuffer.nonsecureMemory = srcBuffer;
656 }
657
658 CasStatus status = CasStatus::OK;
659 hidl_string detailedError;
660 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
661
662 if (key != nullptr) {
663 sctrl = (ScramblingControl)key[0];
664 // Adjust for the PES offset
665 codecDataOffset = key[2] | (key[3] << 8);
666 }
667
668 auto returnVoid = mDescrambler->descramble(
669 sctrl,
670 hidlSubSamples,
671 srcBuffer,
672 0,
673 dstBuffer,
674 0,
675 [&status, &result, &detailedError] (
676 CasStatus _status, uint32_t _bytesWritten,
677 const hidl_string& _detailedError) {
678 status = _status;
679 result = (ssize_t)_bytesWritten;
680 detailedError = _detailedError;
681 });
682
683 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
684 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
685 mName, returnVoid.description().c_str(), status, result);
686 return UNKNOWN_ERROR;
687 }
688
689 if (result < codecDataOffset) {
690 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
691 return BAD_VALUE;
692 }
693
694 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
695
696 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
697 encryptedBuffer->copyDecryptedContentFromMemory(result);
698 }
699 }
700
701 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700702
703 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800704}
705
706void CCodecBufferChannel::feedInputBufferIfAvailable() {
707 QueueGuard guard(mSync);
708 if (!guard.isRunning()) {
709 ALOGV("[%s] We're not running --- no input buffer reported", mName);
710 return;
711 }
712 feedInputBufferIfAvailableInternal();
713}
714
715void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900716 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800717 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700718 }
719 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700720 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700721 if (!output->buffers ||
722 output->buffers->hasPending() ||
Wonsik Kim0487b782020-10-28 11:45:50 -0700723 output->buffers->numActiveSlots() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800724 return;
725 }
726 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700727 size_t numActiveSlots = 0;
728 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800729 sp<MediaCodecBuffer> inBuffer;
730 size_t index;
731 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700732 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700733 numActiveSlots = input->buffers->numActiveSlots();
734 if (numActiveSlots >= input->numSlots) {
735 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800736 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700737 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800738 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800739 break;
740 }
741 }
742 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
743 mCallback->onInputBufferAvailable(index, inBuffer);
744 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700745 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800746}
747
748status_t CCodecBufferChannel::renderOutputBuffer(
749 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800750 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800751 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800752 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800753 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700754 Mutexed<Output>::Locked output(mOutput);
755 if (output->buffers) {
756 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800757 }
758 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800759 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
760 // set to true.
761 sendOutputBuffers();
762 // input buffer feeding may have been gated by pending output buffers
763 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800764 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800765 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700766 std::call_once(mRenderWarningFlag, [this] {
767 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
768 "timestamp or render=true with non-video buffers. Apps should "
769 "call releaseOutputBuffer() with render=false for those.",
770 mName);
771 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800772 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800773 return INVALID_OPERATION;
774 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800775
776#if 0
777 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
778 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
779 for (const std::shared_ptr<const C2Info> &info : infoParams) {
780 AString res;
781 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
782 if (ix) res.append(", ");
783 res.append(*((int32_t*)info.get() + (ix / 4)));
784 }
785 ALOGV(" [%s]", res.c_str());
786 }
787#endif
788 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
789 std::static_pointer_cast<const C2StreamRotationInfo::output>(
790 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
791 bool flip = rotation && (rotation->flip & 1);
792 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900793
794 {
795 Mutexed<OutputSurface>::Locked output(mOutputSurface);
796 if (output->surface == nullptr) {
797 ALOGI("[%s] cannot render buffer without surface", mName);
798 return OK;
799 }
800 int64_t frameIndex;
801 buffer->meta()->findInt64("frameIndex", &frameIndex);
802 if (output->rotation.count(frameIndex) != 0) {
803 auto it = output->rotation.find(frameIndex);
804 quarters = (it->second / 90) & 3;
805 output->rotation.erase(it);
806 }
807 }
808
Pawin Vongmasa36653902018-11-15 00:10:25 -0800809 uint32_t transform = 0;
810 switch (quarters) {
811 case 0: // no rotation
812 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
813 break;
814 case 1: // 90 degrees counter-clockwise
815 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
816 : HAL_TRANSFORM_ROT_270;
817 break;
818 case 2: // 180 degrees
819 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
820 break;
821 case 3: // 90 degrees clockwise
822 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
823 : HAL_TRANSFORM_ROT_90;
824 break;
825 }
826
827 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
828 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
829 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
830 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
831 if (surfaceScaling) {
832 videoScalingMode = surfaceScaling->value;
833 }
834
835 // Use dataspace from format as it has the default aspects already applied
836 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
837 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
838
839 // HDR static info
840 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
841 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
842 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
843
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800844 // HDR10 plus info
845 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
846 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
847 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800848 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
849 hdr10PlusInfo.reset();
850 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800851
Wonsik Kima79c5522022-01-18 16:29:24 -0800852 // HDR dynamic info
853 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
854 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
855 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
856 // TODO: make this sticky & enable unset
857 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
858 hdrDynamicInfo.reset();
859 }
860
861 if (hdr10PlusInfo) {
862 // C2StreamHdr10PlusInfo is deprecated; components should use
863 // C2StreamHdrDynamicMetadataInfo
864 // TODO: #metric
865 if (hdrDynamicInfo) {
866 // It is unexpected that C2StreamHdr10PlusInfo and
867 // C2StreamHdrDynamicMetadataInfo is both present.
868 // C2StreamHdrDynamicMetadataInfo takes priority.
869 // TODO: #metric
870 } else {
871 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
872 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
873 hdr10PlusInfo->flexCount(),
874 0u,
875 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
876 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
877 hdrDynamicInfo = info;
878 }
879 }
880
Pawin Vongmasa36653902018-11-15 00:10:25 -0800881 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
882 if (blocks.size() != 1u) {
883 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
884 return UNKNOWN_ERROR;
885 }
886 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700887 C2Fence c2fence = block.fence();
888 sp<Fence> fence = Fence::NO_FENCE;
889 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
890 // Once C2Fence::type() is added, check the exact C2Fence type
891 if (c2fence.isHW()) {
892 int fenceFd = c2fence.fd();
893 fence = sp<Fence>::make(fenceFd);
894 if (!fence) {
895 ALOGE("[%s] Failed to allocate a fence", mName);
896 close(fenceFd);
897 return NO_MEMORY;
898 }
899 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800900
901 // TODO: revisit this after C2Fence implementation.
Brian Lindahlc953b462023-01-27 16:21:43 -0700902 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800903 timestampNs,
904 false, // droppable
905 dataSpace,
906 Rect(blocks.front().crop().left,
907 blocks.front().crop().top,
908 blocks.front().crop().right(),
909 blocks.front().crop().bottom()),
910 videoScalingMode,
911 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700912 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800913 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800914 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800915 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800916 // If mastering max and min luminance fields are 0, do not use them.
917 // It indicates the value may not be present in the stream.
918 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
919 hdrStaticInfo->mastering.minLuminance > 0.0f) {
920 struct android_smpte2086_metadata smpte2086_meta = {
921 .displayPrimaryRed = {
922 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
923 },
924 .displayPrimaryGreen = {
925 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
926 },
927 .displayPrimaryBlue = {
928 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
929 },
930 .whitePoint = {
931 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
932 },
933 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
934 .minLuminance = hdrStaticInfo->mastering.minLuminance,
935 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800936 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800937 hdr.smpte2086 = smpte2086_meta;
938 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700939 // If the content light level fields are 0, do not use them, it
940 // indicates the value may not be present in the stream.
941 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
942 struct android_cta861_3_metadata cta861_meta = {
943 .maxContentLightLevel = hdrStaticInfo->maxCll,
944 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
945 };
946 hdr.validTypes |= HdrMetadata::CTA861_3;
947 hdr.cta8613 = cta861_meta;
948 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900949
950 // does not have valid info
951 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
952 hdrStaticInfo.reset();
953 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800954 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800955 if (hdrDynamicInfo
956 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800957 hdr.validTypes |= HdrMetadata::HDR10PLUS;
958 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800959 hdrDynamicInfo->m.data,
960 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800961 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800962 qbi.setHdrMetadata(hdr);
963 }
Hongguangfc1478a2022-07-20 22:56:06 -0700964 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
965
Brian Lindahlc953b462023-01-27 16:21:43 -0700966 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
967 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
968 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800969 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
970 if (result != OK) {
971 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800972 if (result == NO_INIT) {
973 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
974 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800975 return result;
976 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800977
978 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
979 ALOGD("[%s] queue buffer successful", mName);
980 } else {
981 ALOGV("[%s] queue buffer successful", mName);
982 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800983
984 int64_t mediaTimeUs = 0;
985 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
986 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
Brian Lindahlc953b462023-01-27 16:21:43 -0700987 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
988 processRenderedFrames(qbo.frameTimestamps);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800989
990 return OK;
991}
992
Brian Lindahlc953b462023-01-27 16:21:43 -0700993void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
994 int hasPresentFenceTimes = 0;
995 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
996 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
997 if (mHasPresentFenceTimes) {
998 ALOGI("Using latch times for frame rendered signals - present fences not supported");
999 }
1000 mTrackedFrames.clear();
1001}
1002
1003void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1004 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1005 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1006 // so track the frame as if the desired render time is now.
1007 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1008 if (desiredRenderTimeNs < nowNs) {
1009 desiredRenderTimeNs = nowNs;
1010 }
1011 // We've just released a frame to the surface, so keep track of it and later check to see if it
1012 // is actually rendered.
1013 TrackedFrame frame;
1014 frame.number = qbo.nextFrameNumber - 1;
1015 frame.mediaTimeUs = mediaTimeUs;
1016 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1017 frame.latchTime = -1;
1018 frame.presentFence = nullptr;
1019 mTrackedFrames.push_back(frame);
1020}
1021
1022void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1023 // Grab the latch times and present fences from the frame event deltas
1024 for (const auto& delta : deltas) {
1025 for (auto& frame : mTrackedFrames) {
1026 if (delta.getFrameNumber() == frame.number) {
1027 delta.getLatchTime(&frame.latchTime);
1028 delta.getDisplayPresentFence(&frame.presentFence);
1029 }
1030 }
1031 }
1032
1033 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1034 // in fact, been rendered.
1035 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1036 while (!mTrackedFrames.empty()) {
1037 TrackedFrame & frame = mTrackedFrames.front();
1038 // Frames that should have been rendered at least 100ms in the past are checked
1039 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1040 break;
1041 }
1042
1043 // If we don't have a render time by now, then consider the frame as dropped
1044 int64_t renderTimeNs = getRenderTimeNs(frame);
1045 if (renderTimeNs != -1) {
1046 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1047 }
1048 mTrackedFrames.pop_front();
1049 }
1050}
1051
1052int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1053 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1054 if (!mHasPresentFenceTimes) {
1055 if (frame.latchTime == -1) {
1056 ALOGD("no latch time for frame %d", (int) frame.number);
1057 return -1;
1058 }
1059 return frame.latchTime;
1060 }
1061
1062 if (frame.presentFence == nullptr) {
1063 ALOGW("no present fence for frame %d", (int) frame.number);
1064 return -1;
1065 }
1066
1067 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1068
1069 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1070 ALOGW("invalid signal time for frame %d", (int) frame.number);
1071 return -1;
1072 }
1073
1074 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1075 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1076 return -1;
1077 }
1078
1079 return actualRenderTimeNs;
1080}
1081
1082void CCodecBufferChannel::pollForRenderedBuffers() {
1083 FrameEventHistoryDelta delta;
1084 mComponent->pollForRenderedFrames(&delta);
1085 processRenderedFrames(delta);
1086}
1087
Pawin Vongmasa36653902018-11-15 00:10:25 -08001088status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1089 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1090 bool released = false;
1091 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001092 Mutexed<Input>::Locked input(mInput);
1093 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001094 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001095 }
1096 }
1097 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001098 Mutexed<Output>::Locked output(mOutput);
1099 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001100 released = true;
1101 }
1102 }
1103 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001104 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001105 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001106 } else {
1107 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1108 }
1109 return OK;
1110}
1111
1112void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1113 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001114 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001115
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001116 if (!input->buffers) {
1117 ALOGE("getInputBufferArray: No Input Buffers allocated");
1118 return;
1119 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001120 if (!input->buffers->isArrayMode()) {
1121 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001122 }
1123
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001124 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001125}
1126
1127void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1128 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001129 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001130 if (!output->buffers) {
1131 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1132 return;
1133 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001134 if (!output->buffers->isArrayMode()) {
1135 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001136 }
1137
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001138 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001139}
1140
1141status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001142 const sp<AMessage> &inputFormat,
1143 const sp<AMessage> &outputFormat,
1144 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001145 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1146 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001147 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001148 C2PortReorderBufferDepthTuning::output reorderDepth;
1149 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001150 C2PortActualDelayTuning::input inputDelay(0);
1151 C2PortActualDelayTuning::output outputDelay(0);
1152 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001153 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001154
Pawin Vongmasa36653902018-11-15 00:10:25 -08001155 c2_status_t err = mComponent->query(
1156 {
1157 &iStreamFormat,
1158 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001159 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001160 &reorderDepth,
1161 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001162 &inputDelay,
1163 &pipelineDelay,
1164 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001165 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001166 },
1167 {},
1168 C2_DONT_BLOCK,
1169 nullptr);
1170 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001171 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001172 return UNKNOWN_ERROR;
1173 }
1174 } else if (err != C2_OK) {
1175 return UNKNOWN_ERROR;
1176 }
1177
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001178 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1179 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1180 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1181
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001182 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1183 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001184
Pawin Vongmasa36653902018-11-15 00:10:25 -08001185 // TODO: get this from input format
1186 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1187
Sungtak Lee04b30352020-07-27 13:57:25 -07001188 // secure mode is a static parameter (shall not change in the executing state)
1189 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1190
Pawin Vongmasa36653902018-11-15 00:10:25 -08001191 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001192 int poolMask = GetCodec2PoolMask();
1193 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001194
1195 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001196 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001197 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001198 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1199 API_REFLECTION |
1200 API_VALUES |
1201 API_CURRENT_VALUES |
1202 API_DEPENDENCY |
1203 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001204 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1205 C2StreamSampleRateInfo::input sampleRate(0u);
1206 C2StreamChannelCountInfo::input channelCount(0u);
1207 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001208 std::shared_ptr<C2BlockPool> pool;
1209 {
1210 Mutexed<BlockPools>::Locked pools(mBlockPools);
1211
1212 // set default allocator ID.
1213 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001214 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001215
1216 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1217 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1218 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001219 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001220 std::vector<C2Param *> stackParams({&featuresSetting});
1221 if (audioEncoder) {
1222 stackParams.push_back(&encoderFrameSize);
1223 stackParams.push_back(&sampleRate);
1224 stackParams.push_back(&channelCount);
1225 stackParams.push_back(&pcmEncoding);
1226 } else {
1227 encoderFrameSize.invalidate();
1228 sampleRate.invalidate();
1229 channelCount.invalidate();
1230 pcmEncoding.invalidate();
1231 }
1232 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001233 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1234 C2_DONT_BLOCK,
1235 &params);
1236 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1237 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1238 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001239 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001240 C2PortAllocatorsTuning::input *inputAllocators =
1241 C2PortAllocatorsTuning::input::From(params[0].get());
1242 if (inputAllocators && inputAllocators->flexCount() > 0) {
1243 std::shared_ptr<C2Allocator> allocator;
1244 // verify allocator IDs and resolve default allocator
1245 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1246 if (allocator) {
1247 pools->inputAllocatorId = allocator->getId();
1248 } else {
1249 ALOGD("[%s] component requested invalid input allocator ID %u",
1250 mName, inputAllocators->m.values[0]);
1251 }
1252 }
1253 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001254 if (featuresSetting) {
1255 apiFeatures = featuresSetting.value;
1256 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001257
1258 // TODO: use C2Component wrapper to associate this pool with ourselves
1259 if ((poolMask >> pools->inputAllocatorId) & 1) {
1260 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1261 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1262 mName, pools->inputAllocatorId,
1263 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1264 asString(err), err);
1265 } else {
1266 err = C2_NOT_FOUND;
1267 }
1268 if (err != C2_OK) {
1269 C2BlockPool::local_id_t inputPoolId =
1270 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1271 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1272 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1273 mName, (unsigned long long)inputPoolId,
1274 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1275 asString(err), err);
1276 if (err != C2_OK) {
1277 return NO_MEMORY;
1278 }
1279 }
1280 pools->inputPool = pool;
1281 }
1282
Wonsik Kim51051262018-11-28 13:59:05 -08001283 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001284 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001285 input->inputDelay = inputDelayValue;
1286 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001287 input->numSlots = numInputSlots;
1288 input->extraBuffers.flush();
1289 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001290 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001291 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1292 input->frameReassembler.init(
1293 pool,
1294 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1295 encoderFrameSize.value,
1296 sampleRate.value,
1297 channelCount.value,
1298 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1299 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001300 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1301 // For encrypted content, framework decrypts source buffer (ashmem) into
1302 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001303 if (!buffersBoundToCodec
1304 && !input->frameReassembler
1305 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001306 input->buffers.reset(new SlotInputBuffers(mName));
1307 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001308 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001309 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001310 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001311 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001312 // This is to ensure buffers do not get released prematurely.
1313 // TODO: handle this without going into array mode
1314 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001315 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001316 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001317 }
1318 } else {
1319 if (hasCryptoOrDescrambler()) {
1320 int32_t capacity = kLinearBufferSize;
1321 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1322 if ((size_t)capacity > kMaxLinearBufferSize) {
1323 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1324 capacity = kMaxLinearBufferSize;
1325 }
1326 if (mDealer == nullptr) {
1327 mDealer = new MemoryDealer(
1328 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001329 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001330 "EncryptedLinearInputBuffers");
1331 mDecryptDestination = mDealer->allocate((size_t)capacity);
1332 }
1333 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001334 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1335 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001336 } else {
1337 mHeapSeqNum = -1;
1338 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001339 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001340 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001341 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001342 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001343 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001344 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001345 }
1346 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001347 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001348
1349 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001350 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001351 } else {
1352 // TODO: error
1353 }
Wonsik Kim51051262018-11-28 13:59:05 -08001354
1355 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001356 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001357 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001358 }
1359
1360 if (outputFormat != nullptr) {
1361 sp<IGraphicBufferProducer> outputSurface;
1362 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001363 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001364 {
1365 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001366 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001367 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001368 outputSurface = output->surface ?
1369 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001370 if (outputSurface) {
1371 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1372 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001373 outputGeneration = output->generation;
1374 }
1375
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001376 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001377 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001378 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001379
1380 {
1381 Mutexed<BlockPools>::Locked pools(mBlockPools);
1382
David Stevensc3fbb282021-01-18 18:11:20 +09001383 prevOutputPoolId = pools->outputPoolId;
1384
Pawin Vongmasa36653902018-11-15 00:10:25 -08001385 // set default allocator ID.
1386 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001387 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001388
1389 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1390 // unsuccessful.
1391 std::vector<std::unique_ptr<C2Param>> params;
1392 err = mComponent->query({ },
1393 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1394 C2_DONT_BLOCK,
1395 &params);
1396 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1397 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1398 mName, params.size(), asString(err), err);
1399 } else if (err == C2_OK && params.size() == 1) {
1400 C2PortAllocatorsTuning::output *outputAllocators =
1401 C2PortAllocatorsTuning::output::From(params[0].get());
1402 if (outputAllocators && outputAllocators->flexCount() > 0) {
1403 std::shared_ptr<C2Allocator> allocator;
1404 // verify allocator IDs and resolve default allocator
1405 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1406 if (allocator) {
1407 pools->outputAllocatorId = allocator->getId();
1408 } else {
1409 ALOGD("[%s] component requested invalid output allocator ID %u",
1410 mName, outputAllocators->m.values[0]);
1411 }
1412 }
1413 }
1414
1415 // use bufferqueue if outputting to a surface.
1416 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1417 // if unsuccessful.
1418 if (outputSurface) {
1419 params.clear();
1420 err = mComponent->query({ },
1421 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1422 C2_DONT_BLOCK,
1423 &params);
1424 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1425 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1426 mName, params.size(), asString(err), err);
1427 } else if (err == C2_OK && params.size() == 1) {
1428 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1429 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1430 if (surfaceAllocator) {
1431 std::shared_ptr<C2Allocator> allocator;
1432 // verify allocator IDs and resolve default allocator
1433 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1434 if (allocator) {
1435 pools->outputAllocatorId = allocator->getId();
1436 } else {
1437 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1438 mName, surfaceAllocator->value);
1439 err = C2_BAD_VALUE;
1440 }
1441 }
1442 }
1443 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1444 && err != C2_OK
1445 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1446 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1447 }
1448 }
1449
1450 if ((poolMask >> pools->outputAllocatorId) & 1) {
1451 err = mComponent->createBlockPool(
1452 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1453 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1454 mName, pools->outputAllocatorId,
1455 (unsigned long long)pools->outputPoolId,
1456 asString(err));
1457 } else {
1458 err = C2_NOT_FOUND;
1459 }
1460 if (err != C2_OK) {
1461 // use basic pool instead
1462 pools->outputPoolId =
1463 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1464 }
1465
1466 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1467 // component.
1468 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1469 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1470
1471 std::vector<std::unique_ptr<C2SettingResult>> failures;
1472 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1473 ALOGD("[%s] Configured output block pool ids %llu => %s",
1474 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1475 outputPoolId_ = pools->outputPoolId;
1476 }
1477
David Stevensc3fbb282021-01-18 18:11:20 +09001478 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1479 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1480 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1481 if (err != C2_OK) {
1482 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1483 (unsigned long long) prevOutputPoolId, asString(err), err);
1484 }
1485 }
1486
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001487 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001488 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001489 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001490 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001491 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001492 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001493 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001494 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001495 }
1496 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001497 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001498 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001499 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001500
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001501 output->buffers->clearStash();
1502 if (reorderDepth) {
1503 output->buffers->setReorderDepth(reorderDepth.value);
1504 }
1505 if (reorderKey) {
1506 output->buffers->setReorderKey(reorderKey.value);
1507 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001508
1509 // Try to set output surface to created block pool if given.
1510 if (outputSurface) {
1511 mComponent->setOutputSurface(
1512 outputPoolId_,
1513 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001514 outputGeneration,
1515 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001516 } else {
1517 // configure CPU read consumer usage
1518 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1519 std::vector<std::unique_ptr<C2SettingResult>> failures;
1520 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1521 // do not print error message for now as most components may not yet
1522 // support this setting
1523 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1524 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001525 }
1526
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001527 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001528 if (buffersBoundToCodec) {
1529 // WORKAROUND: if we're using early CSD workaround we convert to
1530 // array mode, to appease apps assuming the output
1531 // buffers to be of the same size.
1532 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1533 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001534
1535 int32_t channelCount;
1536 int32_t sampleRate;
1537 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1538 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1539 int32_t delay = 0;
1540 int32_t padding = 0;;
1541 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1542 delay = 0;
1543 }
1544 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1545 padding = 0;
1546 }
1547 if (delay || padding) {
1548 // We need write access to the buffers, and we're already in
1549 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001550 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001551 }
1552 }
1553 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001554
1555 int32_t tunneled = 0;
1556 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1557 tunneled = 0;
1558 }
1559 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001560 }
1561
1562 // Set up pipeline control. This has to be done after mInputBuffers and
1563 // mOutputBuffers are initialized to make sure that lingering callbacks
1564 // about buffers from the previous generation do not interfere with the
1565 // newly initialized pipeline capacity.
1566
Wonsik Kim62545252021-01-20 11:25:41 -08001567 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001568 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001569 watcher->inputDelay(inputDelayValue)
1570 .pipelineDelay(pipelineDelayValue)
1571 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001572 .smoothnessFactor(kSmoothnessFactor);
1573 watcher->flush();
1574 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001575
1576 mInputMetEos = false;
1577 mSync.start();
1578 return OK;
1579}
1580
Wonsik Kim34b28b42022-05-20 15:49:32 -07001581status_t CCodecBufferChannel::prepareInitialInputBuffers(
1582 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001583 if (mInputSurface) {
1584 return OK;
1585 }
1586
Wonsik Kim34b28b42022-05-20 15:49:32 -07001587 size_t numInputSlots = mInput.lock()->numSlots;
1588
1589 {
1590 Mutexed<Input>::Locked input(mInput);
1591 while (clientInputBuffers->size() < numInputSlots) {
1592 size_t index;
1593 sp<MediaCodecBuffer> buffer;
1594 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1595 break;
1596 }
1597 clientInputBuffers->emplace(index, buffer);
1598 }
1599 }
1600 if (clientInputBuffers->empty()) {
1601 ALOGW("[%s] start: cannot allocate memory at all", mName);
1602 return NO_MEMORY;
1603 } else if (clientInputBuffers->size() < numInputSlots) {
1604 ALOGD("[%s] start: cannot allocate memory for all slots, "
1605 "only %zu buffers allocated",
1606 mName, clientInputBuffers->size());
1607 } else {
1608 ALOGV("[%s] %zu initial input buffers available",
1609 mName, clientInputBuffers->size());
1610 }
1611 return OK;
1612}
1613
1614status_t CCodecBufferChannel::requestInitialInputBuffers(
1615 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001616 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001617 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1618 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1619 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001620 return UNKNOWN_ERROR;
1621 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001622
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001623 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1624 mFlushedConfigs.lock()->swap(flushedConfigs);
1625 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001626 {
1627 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1628 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1629 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1630 watcher->onWorkQueued(
1631 work->input.ordinal.frameIndex.peeku(),
1632 std::vector(work->input.buffers),
1633 now);
1634 }
1635 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001636 err = mComponent->queue(&flushedConfigs);
1637 if (err != C2_OK) {
1638 ALOGW("[%s] Error while queueing a flushed config", mName);
1639 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001640 }
1641 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001642 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001643 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1644 !clientInputBuffers.empty()) {
1645 size_t minIndex = clientInputBuffers.begin()->first;
1646 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1647 for (const auto &[index, buffer] : clientInputBuffers) {
1648 if (minBuffer->capacity() > buffer->capacity()) {
1649 minIndex = index;
1650 minBuffer = buffer;
1651 }
1652 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001653 // WORKAROUND: Some apps expect CSD available without queueing
1654 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001655 minBuffer->setRange(0, 0);
1656 minBuffer->meta()->clear();
1657 minBuffer->meta()->setInt64("timeUs", 0);
1658 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001659 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1660 mName);
1661 return UNKNOWN_ERROR;
1662 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001663 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001664 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001665
Wonsik Kim34b28b42022-05-20 15:49:32 -07001666 for (const auto &[index, buffer] : clientInputBuffers) {
1667 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001668 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001669
Pawin Vongmasa36653902018-11-15 00:10:25 -08001670 return OK;
1671}
1672
1673void CCodecBufferChannel::stop() {
1674 mSync.stop();
1675 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001676}
1677
Sungtak Leed964e2e2022-07-30 08:43:58 +00001678void CCodecBufferChannel::stopUseOutputSurface() {
1679 if (mOutputSurface.lock()->surface) {
1680 C2BlockPool::local_id_t outputPoolId;
1681 {
1682 Mutexed<BlockPools>::Locked pools(mBlockPools);
1683 outputPoolId = pools->outputPoolId;
1684 }
1685 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
1686 }
1687}
1688
Wonsik Kim936a89c2020-05-08 16:07:50 -07001689void CCodecBufferChannel::reset() {
1690 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001691 if (mInputSurface != nullptr) {
1692 mInputSurface.reset();
1693 }
1694 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001695 {
1696 Mutexed<Input>::Locked input(mInput);
1697 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001698 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001699 }
1700 {
1701 Mutexed<Output>::Locked output(mOutput);
1702 output->buffers.reset();
1703 }
Brian Lindahlc953b462023-01-27 16:21:43 -07001704 // reset the frames that are being tracked for onFrameRendered callbacks
1705 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001706}
1707
1708void CCodecBufferChannel::release() {
1709 mComponent.reset();
1710 mInputAllocator.reset();
1711 mOutputSurface.lock()->surface.clear();
1712 {
1713 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1714 blockPools->inputPool.reset();
1715 blockPools->outputPoolIntf.reset();
1716 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001717 setCrypto(nullptr);
1718 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001719}
1720
Pawin Vongmasa36653902018-11-15 00:10:25 -08001721void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1722 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001723 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001724 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001725 {
1726 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1727 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1728 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1729 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1730 watcher->onWorkDone(frameIndex);
1731 continue;
1732 }
1733 if (work->input.buffers.empty()
1734 || work->input.buffers.front() == nullptr
1735 || work->input.buffers.front()->data().linearBlocks().empty()) {
1736 ALOGD("[%s] no linear codec config data found", mName);
1737 watcher->onWorkDone(frameIndex);
1738 continue;
1739 }
1740 std::unique_ptr<C2Work> copy(new C2Work);
1741 copy->input.flags = C2FrameData::flags_t(
1742 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1743 copy->input.ordinal = work->input.ordinal;
1744 copy->input.ordinal.frameIndex = mFrameIndex++;
1745 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1746 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1747 }
1748 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1749 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1750 }
1751 copy->input.infoBuffers.insert(
1752 copy->input.infoBuffers.begin(),
1753 work->input.infoBuffers.begin(),
1754 work->input.infoBuffers.end());
1755 copy->worklets.emplace_back(new C2Worklet);
1756 configs.push_back(std::move(copy));
1757 watcher->onWorkDone(frameIndex);
1758 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001759 }
1760 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001761 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001762 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001763 Mutexed<Input>::Locked input(mInput);
1764 input->buffers->flush();
1765 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001766 }
1767 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001768 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001769 if (output->buffers) {
1770 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001771 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001772 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001773 }
Brian Lindahlc953b462023-01-27 16:21:43 -07001774 // reset the frames that are being tracked for onFrameRendered callbacks
1775 mTrackedFrames.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001776}
1777
1778void CCodecBufferChannel::onWorkDone(
1779 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001780 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001781 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001782 feedInputBufferIfAvailable();
1783 }
1784}
1785
1786void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001787 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001788 if (mInputSurface) {
1789 return;
1790 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001791 std::shared_ptr<C2Buffer> buffer =
1792 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001793 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001794 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001795 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001796 if (input->lastFlushIndex >= frameIndex) {
1797 ALOGD("[%s] Ignoring stale input buffer done callback: "
1798 "last flush index = %lld, frameIndex = %lld",
1799 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1800 } else {
1801 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1802 if (!newInputSlotAvailable) {
1803 (void)input->extraBuffers.expireComponentBuffer(buffer);
1804 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001805 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001806 }
1807 if (newInputSlotAvailable) {
1808 feedInputBufferIfAvailable();
1809 }
1810}
1811
1812bool CCodecBufferChannel::handleWork(
1813 std::unique_ptr<C2Work> work,
1814 const sp<AMessage> &outputFormat,
1815 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001816 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001817 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001818 if (!output->buffers) {
1819 return false;
1820 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001821 }
1822
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001823 // Whether the output buffer should be reported to the client or not.
1824 bool notifyClient = false;
1825
1826 if (work->result == C2_OK){
1827 notifyClient = true;
1828 } else if (work->result == C2_NOT_FOUND) {
1829 ALOGD("[%s] flushed work; ignored.", mName);
1830 } else {
1831 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1832 // the config update.
1833 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1834 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1835 return false;
1836 }
1837
1838 if ((work->input.ordinal.frameIndex -
1839 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001840 // Discard frames from previous generation.
1841 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001842 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001843 }
1844
Wonsik Kim524b0582019-03-12 11:28:57 -07001845 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001846 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001847 || !(work->worklets.front()->output.flags &
1848 C2FrameData::FLAG_INCOMPLETE))) {
1849 mPipelineWatcher.lock()->onWorkDone(
1850 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001851 }
1852
1853 // NOTE: MediaCodec usage supposedly have only one worklet
1854 if (work->worklets.size() != 1u) {
1855 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1856 mName, work->worklets.size());
1857 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1858 return false;
1859 }
1860
1861 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1862
1863 std::shared_ptr<C2Buffer> buffer;
1864 // NOTE: MediaCodec usage supposedly have only one output stream.
1865 if (worklet->output.buffers.size() > 1u) {
1866 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1867 mName, worklet->output.buffers.size());
1868 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1869 return false;
1870 } else if (worklet->output.buffers.size() == 1u) {
1871 buffer = worklet->output.buffers[0];
1872 if (!buffer) {
1873 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1874 }
1875 }
1876
Wonsik Kim3dedf682021-05-03 10:57:09 -07001877 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1878 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001879 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001880 while (!worklet->output.configUpdate.empty()) {
1881 std::unique_ptr<C2Param> param;
1882 worklet->output.configUpdate.back().swap(param);
1883 worklet->output.configUpdate.pop_back();
1884 switch (param->coreIndex().coreIndex()) {
1885 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1886 C2PortReorderBufferDepthTuning::output reorderDepth;
1887 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001888 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1889 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001890 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001891 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001892 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001893 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1894 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001895 }
1896 break;
1897 }
1898 case C2PortReorderKeySetting::CORE_INDEX: {
1899 C2PortReorderKeySetting::output reorderKey;
1900 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001901 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001902 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1903 mName, reorderKey.value);
1904 } else {
1905 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1906 }
1907 break;
1908 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001909 case C2PortActualDelayTuning::CORE_INDEX: {
1910 if (param->isGlobal()) {
1911 C2ActualPipelineDelayTuning pipelineDelay;
1912 if (pipelineDelay.updateFrom(*param)) {
1913 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1914 mName, pipelineDelay.value);
1915 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001916 (void)mPipelineWatcher.lock()->pipelineDelay(
1917 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001918 }
1919 }
1920 if (param->forInput()) {
1921 C2PortActualDelayTuning::input inputDelay;
1922 if (inputDelay.updateFrom(*param)) {
1923 ALOGV("[%s] onWorkDone: updating input delay %u",
1924 mName, inputDelay.value);
1925 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001926 (void)mPipelineWatcher.lock()->inputDelay(
1927 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001928 }
1929 }
1930 if (param->forOutput()) {
1931 C2PortActualDelayTuning::output outputDelay;
1932 if (outputDelay.updateFrom(*param)) {
1933 ALOGV("[%s] onWorkDone: updating output delay %u",
1934 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001935 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001936 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001937 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001938
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001939 }
1940 }
1941 break;
1942 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001943 case C2PortTunnelSystemTime::CORE_INDEX: {
1944 C2PortTunnelSystemTime::output frameRenderTime;
1945 if (frameRenderTime.updateFrom(*param)) {
1946 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1947 mName, (long long)frameRenderTime.value,
1948 (long long)worklet->output.ordinal.timestamp.peekll());
1949 mCCodecCallback->onOutputFramesRendered(
1950 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1951 }
1952 break;
1953 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001954 case C2StreamTunnelHoldRender::CORE_INDEX: {
1955 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1956 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1957 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1958 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1959 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1960 mCCodecCallback->onFirstTunnelFrameReady();
1961 break;
1962 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001963 default:
1964 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1965 mName, param->index());
1966 break;
1967 }
1968 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001969 if (newInputDelay || newPipelineDelay) {
1970 Mutexed<Input>::Locked input(mInput);
1971 size_t newNumSlots =
1972 newInputDelay.value_or(input->inputDelay) +
1973 newPipelineDelay.value_or(input->pipelineDelay) +
1974 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08001975 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001976 if (input->buffers->isArrayMode()) {
1977 if (input->numSlots >= newNumSlots) {
1978 input->numExtraSlots = 0;
1979 } else {
1980 input->numExtraSlots = newNumSlots - input->numSlots;
1981 }
1982 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1983 mName, input->numExtraSlots);
1984 } else {
1985 input->numSlots = newNumSlots;
1986 }
1987 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001988 size_t numOutputSlots = 0;
1989 uint32_t reorderDepth = 0;
1990 bool outputBuffersChanged = false;
1991 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
1992 Mutexed<Output>::Locked output(mOutput);
1993 if (!output->buffers) {
1994 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001995 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001996 numOutputSlots = output->numSlots;
1997 if (newReorderKey) {
1998 output->buffers->setReorderKey(newReorderKey.value());
1999 }
2000 if (newReorderDepth) {
2001 output->buffers->setReorderDepth(newReorderDepth.value());
2002 }
2003 reorderDepth = output->buffers->getReorderDepth();
2004 if (newOutputDelay) {
2005 output->outputDelay = newOutputDelay.value();
2006 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2007 if (output->numSlots < numOutputSlots) {
2008 output->numSlots = numOutputSlots;
2009 if (output->buffers->isArrayMode()) {
2010 OutputBuffersArray *array =
2011 (OutputBuffersArray *)output->buffers.get();
2012 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2013 mName, numOutputSlots);
2014 array->grow(numOutputSlots);
2015 outputBuffersChanged = true;
2016 }
2017 }
2018 }
2019 numOutputSlots = output->numSlots;
2020 }
2021 if (outputBuffersChanged) {
2022 mCCodecCallback->onOutputBuffersChanged();
2023 }
2024 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002025 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002026 {
2027 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2028 maxDequeueCount = output->maxDequeueBuffers =
2029 numOutputSlots + reorderDepth + kRenderingDepth;
2030 if (output->surface) {
2031 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2032 }
2033 }
2034 if (maxDequeueCount > 0) {
2035 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002036 }
2037 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002038
Pawin Vongmasa36653902018-11-15 00:10:25 -08002039 int32_t flags = 0;
2040 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002041 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002042 ALOGV("[%s] onWorkDone: output EOS", mName);
2043 }
2044
Pawin Vongmasa36653902018-11-15 00:10:25 -08002045 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2046 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2047 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2048 // shall correspond to the client input timesamp (in customOrdinal). By using the
2049 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2050 // produces multiple output.
2051 c2_cntr64_t timestamp =
2052 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2053 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002054 if (mInputSurface != nullptr) {
2055 // When using input surface we need to restore the original input timestamp.
2056 timestamp = work->input.ordinal.customOrdinal;
2057 }
My Name6bd9a7d2022-03-25 12:37:58 -07002058 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2059 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002060 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2061 mName,
2062 work->input.ordinal.customOrdinal.peekll(),
2063 work->input.ordinal.timestamp.peekll(),
2064 worklet->output.ordinal.timestamp.peekll(),
2065 timestamp.peekll());
2066
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002067 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002068 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002069 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002070 if (output->buffers && outputFormat) {
2071 output->buffers->updateSkipCutBuffer(outputFormat);
2072 output->buffers->setFormat(outputFormat);
2073 }
2074 if (!notifyClient) {
2075 return false;
2076 }
2077 size_t index;
2078 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07002079 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002080 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002081 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002082 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2083
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002084 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002085 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002086 } else {
2087 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002088 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002089 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002090 return false;
2091 }
2092 }
2093
Wonsik Kimec585c32021-10-01 01:11:00 -07002094 bool drop = false;
2095 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2096 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2097 drop = true;
2098 }
2099
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002100 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002101 if (mTunneled && drop && outputFormat) {
2102 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2103 mName, work->input.ordinal.frameIndex.peekull());
2104 } else {
2105 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2106 mName, work->input.ordinal.frameIndex.peekull());
2107 notifyClient = false;
2108 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002109 }
2110
2111 if (buffer) {
2112 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2113 // TODO: properly translate these to metadata
2114 switch (info->coreIndex().coreIndex()) {
2115 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002116 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002117 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002118 }
2119 break;
2120 default:
2121 break;
2122 }
2123 }
2124 }
2125
2126 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002127 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002128 if (!output->buffers) {
2129 return false;
2130 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002131 output->buffers->pushToStash(
2132 buffer,
2133 notifyClient,
2134 timestamp.peek(),
2135 flags,
2136 outputFormat,
2137 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002138 }
2139 sendOutputBuffers();
2140 return true;
2141}
2142
2143void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002144 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002145 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002146 sp<MediaCodecBuffer> outBuffer;
2147 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002148
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002149 constexpr int kMaxReallocTry = 5;
2150 int reallocTryNum = 0;
2151
Pawin Vongmasa36653902018-11-15 00:10:25 -08002152 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002153 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002154 if (!output->buffers) {
2155 return;
2156 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002157 action = output->buffers->popFromStashAndRegister(
2158 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002159 if (action != OutputBuffers::REALLOCATE) {
2160 reallocTryNum = 0;
2161 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002162 switch (action) {
2163 case OutputBuffers::SKIP:
2164 return;
2165 case OutputBuffers::DISCARD:
2166 break;
2167 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00002168 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002169 mCallback->onOutputBufferAvailable(index, outBuffer);
2170 break;
2171 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002172 if (++reallocTryNum > kMaxReallocTry) {
2173 output.unlock();
2174 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2175 mName, kMaxReallocTry);
2176 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2177 return;
2178 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002179 if (!output->buffers->isArrayMode()) {
2180 output->buffers =
2181 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002182 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002183 static_cast<OutputBuffersArray*>(output->buffers.get())->
2184 realloc(c2Buffer);
2185 output.unlock();
2186 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002187 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002188 case OutputBuffers::RETRY:
2189 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2190 mName);
2191 return;
2192 default:
2193 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2194 "corrupted BufferAction value (%d) "
2195 "returned from popFromStashAndRegister.",
2196 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002197 return;
2198 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002199 }
2200}
2201
2202status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
2203 static std::atomic_uint32_t surfaceGeneration{0};
2204 uint32_t generation = (getpid() << 10) |
2205 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2206 & ((1 << 10) - 1));
2207
2208 sp<IGraphicBufferProducer> producer;
Sungtak Leedb14cba2021-04-10 00:50:23 -07002209 int maxDequeueCount = mOutputSurface.lock()->maxDequeueBuffers;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002210 if (newSurface) {
2211 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002212 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002213 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002214 producer = newSurface->getIGraphicBufferProducer();
2215 producer->setGenerationNumber(generation);
2216 } else {
2217 ALOGE("[%s] setting output surface to null", mName);
2218 return INVALID_OPERATION;
2219 }
2220
2221 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2222 C2BlockPool::local_id_t outputPoolId;
2223 {
2224 Mutexed<BlockPools>::Locked pools(mBlockPools);
2225 outputPoolId = pools->outputPoolId;
2226 outputPoolIntf = pools->outputPoolIntf;
2227 }
2228
2229 if (outputPoolIntf) {
2230 if (mComponent->setOutputSurface(
2231 outputPoolId,
2232 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002233 generation,
2234 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002235 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2236 return INVALID_OPERATION;
2237 }
2238 }
2239
2240 {
2241 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2242 output->surface = newSurface;
2243 output->generation = generation;
2244 }
Brian Lindahlc953b462023-01-27 16:21:43 -07002245 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002246 return OK;
2247}
2248
Wonsik Kimab34ed62019-01-31 15:28:46 -08002249PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002250 // Otherwise, component may have stalled work due to input starvation up to
2251 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002252 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2253 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002254 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002255 size_t outputDelay = mOutput.lock()->outputDelay;
2256 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002257 Mutexed<Input>::Locked input(mInput);
2258 n = input->inputDelay + input->pipelineDelay + outputDelay;
2259 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002260 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002261}
2262
Pawin Vongmasa36653902018-11-15 00:10:25 -08002263void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2264 mMetaMode = mode;
2265}
2266
Wonsik Kim596187e2019-10-25 12:44:10 -07002267void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002268 if (mCrypto != nullptr) {
2269 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2270 mCrypto->unsetHeap(entry.second);
2271 }
2272 mHeapSeqNumMap.clear();
2273 if (mHeapSeqNum >= 0) {
2274 mCrypto->unsetHeap(mHeapSeqNum);
2275 mHeapSeqNum = -1;
2276 }
2277 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002278 mCrypto = crypto;
2279}
2280
2281void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2282 mDescrambler = descrambler;
2283}
2284
Pawin Vongmasa36653902018-11-15 00:10:25 -08002285status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2286 // C2_OK is always translated to OK.
2287 if (c2s == C2_OK) {
2288 return OK;
2289 }
2290
2291 // Operation-dependent translation
2292 // TODO: Add as necessary
2293 switch (c2op) {
2294 case C2_OPERATION_Component_start:
2295 switch (c2s) {
2296 case C2_NO_MEMORY:
2297 return NO_MEMORY;
2298 default:
2299 return UNKNOWN_ERROR;
2300 }
2301 default:
2302 break;
2303 }
2304
2305 // Backup operation-agnostic translation
2306 switch (c2s) {
2307 case C2_BAD_INDEX:
2308 return BAD_INDEX;
2309 case C2_BAD_VALUE:
2310 return BAD_VALUE;
2311 case C2_BLOCKING:
2312 return WOULD_BLOCK;
2313 case C2_DUPLICATE:
2314 return ALREADY_EXISTS;
2315 case C2_NO_INIT:
2316 return NO_INIT;
2317 case C2_NO_MEMORY:
2318 return NO_MEMORY;
2319 case C2_NOT_FOUND:
2320 return NAME_NOT_FOUND;
2321 case C2_TIMED_OUT:
2322 return TIMED_OUT;
2323 case C2_BAD_STATE:
2324 case C2_CANCELED:
2325 case C2_CANNOT_DO:
2326 case C2_CORRUPTED:
2327 case C2_OMITTED:
2328 case C2_REFUSED:
2329 return UNKNOWN_ERROR;
2330 default:
2331 return -static_cast<status_t>(c2s);
2332 }
2333}
2334
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +01002335status_t CCodecBufferChannel::pushBlankBufferToOutputSurface() {
2336 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2337 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(output->surface.get());
2338 if (nativeWindow == nullptr) {
2339 return INVALID_OPERATION;
2340 }
2341 return pushBlankBuffersToNativeWindow(nativeWindow.get());
2342}
2343
Pawin Vongmasa36653902018-11-15 00:10:25 -08002344} // namespace android