blob: df349c9f18c0d2e140b434be3ceeba0d2aade94a [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright 2017, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010018#include <utils/Errors.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080019#define LOG_TAG "CCodecBufferChannel"
My Name6bd9a7d2022-03-25 12:37:58 -070020#define ATRACE_TAG ATRACE_TAG_VIDEO
Pawin Vongmasa36653902018-11-15 00:10:25 -080021#include <utils/Log.h>
My Name6bd9a7d2022-03-25 12:37:58 -070022#include <utils/Trace.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080023
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070024#include <algorithm>
Wonsik Kim6b2c8be2021-09-28 05:11:04 -070025#include <atomic>
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070026#include <list>
Pawin Vongmasa36653902018-11-15 00:10:25 -080027#include <numeric>
28
29#include <C2AllocatorGralloc.h>
30#include <C2PlatformSupport.h>
31#include <C2BlockInternal.h>
32#include <C2Config.h>
33#include <C2Debug.h>
34
35#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070036#include <android/hardware/drm/1.0/types.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080037#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080038#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080039#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080040#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070041#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080042#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070043#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080044#include <media/openmax/OMX_Core.h>
45#include <media/stagefright/foundation/ABuffer.h>
46#include <media/stagefright/foundation/ALookup.h>
47#include <media/stagefright/foundation/AMessage.h>
48#include <media/stagefright/foundation/AUtils.h>
49#include <media/stagefright/foundation/hexdump.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080050#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070051#include <media/stagefright/SkipCutBuffer.h>
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010052#include <media/stagefright/SurfaceUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080053#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070054#include <mediadrm/ICrypto.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080055#include <system/window.h>
56
57#include "CCodecBufferChannel.h"
58#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080059
60namespace android {
61
62using android::base::StringPrintf;
63using hardware::hidl_handle;
64using hardware::hidl_string;
65using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070066using hardware::fromHeap;
67using hardware::HidlMemory;
68
Pawin Vongmasa36653902018-11-15 00:10:25 -080069using namespace hardware::cas::V1_0;
70using namespace hardware::cas::native::V1_0;
71
72using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070073using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080074
Pawin Vongmasa36653902018-11-15 00:10:25 -080075namespace {
76
Wonsik Kim469c8342019-04-11 16:46:09 -070077constexpr size_t kSmoothnessFactor = 4;
78constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080079
Sungtak Leeab6f2f32019-02-15 14:43:51 -080080// This is for keeping IGBP's buffer dropping logic in legacy mode other
81// than making it non-blocking. Do not change this value.
82const static size_t kDequeueTimeoutNs = 0;
83
Pawin Vongmasa36653902018-11-15 00:10:25 -080084} // namespace
85
86CCodecBufferChannel::QueueGuard::QueueGuard(
87 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
88 Mutex::Autolock l(mSync.mGuardLock);
89 // At this point it's guaranteed that mSync is not under state transition,
90 // as we are holding its mutex.
91
92 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
93 if (count->value == -1) {
94 mRunning = false;
95 } else {
96 ++count->value;
97 mRunning = true;
98 }
99}
100
101CCodecBufferChannel::QueueGuard::~QueueGuard() {
102 if (mRunning) {
103 // We are not holding mGuardLock at this point so that QueueSync::stop() can
104 // keep holding the lock until mCount reaches zero.
105 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
106 --count->value;
107 count->cond.broadcast();
108 }
109}
110
111void CCodecBufferChannel::QueueSync::start() {
112 Mutex::Autolock l(mGuardLock);
113 // If stopped, it goes to running state; otherwise no-op.
114 Mutexed<Counter>::Locked count(mCount);
115 if (count->value == -1) {
116 count->value = 0;
117 }
118}
119
120void CCodecBufferChannel::QueueSync::stop() {
121 Mutex::Autolock l(mGuardLock);
122 Mutexed<Counter>::Locked count(mCount);
123 if (count->value == -1) {
124 // no-op
125 return;
126 }
127 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
128 // mCount can only decrement. In other words, threads that acquired the lock
129 // are allowed to finish execution but additional threads trying to acquire
130 // the lock at this point will block, and then get QueueGuard at STOPPED
131 // state.
132 while (count->value != 0) {
133 count.waitForCondition(count->cond);
134 }
135 count->value = -1;
136}
137
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700138// Input
139
140CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
141
Pawin Vongmasa36653902018-11-15 00:10:25 -0800142// CCodecBufferChannel
143
144CCodecBufferChannel::CCodecBufferChannel(
145 const std::shared_ptr<CCodecCallback> &callback)
146 : mHeapSeqNum(-1),
147 mCCodecCallback(callback),
148 mFrameIndex(0u),
149 mFirstValidFrameIndex(0u),
Brian Lindahle31a52d2023-04-05 08:49:23 -0600150 mIsSurfaceToDisplay(false),
151 mHasPresentFenceTimes(false),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800152 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700153 mInputMetEos(false),
154 mSendEncryptedInfoBuffer(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700155 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700156 {
157 Mutexed<Input>::Locked input(mInput);
158 input->buffers.reset(new DummyInputBuffers(""));
159 input->extraBuffers.flush();
160 input->inputDelay = 0u;
161 input->pipelineDelay = 0u;
162 input->numSlots = kSmoothnessFactor;
163 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700164 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700165 }
166 {
167 Mutexed<Output>::Locked output(mOutput);
168 output->outputDelay = 0u;
169 output->numSlots = kSmoothnessFactor;
170 }
David Stevensc3fbb282021-01-18 18:11:20 +0900171 {
172 Mutexed<BlockPools>::Locked pools(mBlockPools);
173 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
174 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800175}
176
177CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800178 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800179 mCrypto->unsetHeap(mHeapSeqNum);
180 }
181}
182
183void CCodecBufferChannel::setComponent(
184 const std::shared_ptr<Codec2Client::Component> &component) {
185 mComponent = component;
186 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
187 mName = mComponentName.c_str();
188}
189
190status_t CCodecBufferChannel::setInputSurface(
191 const std::shared_ptr<InputSurfaceWrapper> &surface) {
192 ALOGV("[%s] setInputSurface", mName);
193 mInputSurface = surface;
194 return mInputSurface->connect(mComponent);
195}
196
197status_t CCodecBufferChannel::signalEndOfInputStream() {
198 if (mInputSurface == nullptr) {
199 return INVALID_OPERATION;
200 }
201 return mInputSurface->signalEndOfInputStream();
202}
203
Sungtak Lee04b30352020-07-27 13:57:25 -0700204status_t CCodecBufferChannel::queueInputBufferInternal(
205 sp<MediaCodecBuffer> buffer,
206 std::shared_ptr<C2LinearBlock> encryptedBlock,
207 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800208 int64_t timeUs;
209 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
210
211 if (mInputMetEos) {
212 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
213 return OK;
214 }
215
216 int32_t flags = 0;
217 int32_t tmp = 0;
218 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200219 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800220 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
221 eos = true;
222 mInputMetEos = true;
223 ALOGV("[%s] input EOS", mName);
224 }
225 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
226 flags |= C2FrameData::FLAG_CODEC_CONFIG;
227 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200228 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
229 tunnelFirstFrame = true;
230 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800231 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800232 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800233 std::unique_ptr<C2Work> work(new C2Work);
234 work->input.ordinal.timestamp = timeUs;
235 work->input.ordinal.frameIndex = mFrameIndex++;
236 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
237 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
238 // Keep client timestamp in customOrdinal
239 work->input.ordinal.customOrdinal = timeUs;
240 work->input.buffers.clear();
241
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700242 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800243 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800244
Pawin Vongmasa36653902018-11-15 00:10:25 -0800245 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700246 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800247 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700248 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800249 return -ENOENT;
250 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700251 // TODO: we want to delay copying buffers.
252 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
253 copy = input->buffers->cloneAndReleaseBuffer(buffer);
254 if (copy != nullptr) {
255 (void)input->extraBuffers.assignSlot(copy);
256 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
257 return UNKNOWN_ERROR;
258 }
259 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
260 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
261 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700262 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700263 } else {
264 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
265 "buffer starvation on component.", mName);
266 }
267 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800268 if (input->frameReassembler) {
269 usesFrameReassembler = true;
270 input->frameReassembler.process(buffer, &items);
271 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900272 int32_t cvo = 0;
273 if (buffer->meta()->findInt32("cvo", &cvo)) {
274 int32_t rotation = cvo % 360;
275 // change rotation to counter-clock wise.
276 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
277
278 Mutexed<OutputSurface>::Locked output(mOutputSurface);
279 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
280 output->rotation[frameIndex] = rotation;
281 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800282 work->input.buffers.push_back(c2buffer);
283 if (encryptedBlock) {
284 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
285 kParamIndexEncryptedBuffer,
286 encryptedBlock->share(0, blockSize, C2Fence())));
287 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700288 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800289 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700290 Mutexed<Input>::Locked input(mInput);
291 if (input->frameReassembler) {
292 usesFrameReassembler = true;
293 // drain any pending items with eos
294 input->frameReassembler.process(buffer, &items);
295 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800296 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800297 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800298 if (usesFrameReassembler) {
299 if (!items.empty()) {
300 items.front()->input.configUpdate = std::move(mParamsToBeSet);
301 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
302 }
303 } else {
304 work->input.flags = (C2FrameData::flags_t)flags;
305 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800306
Wonsik Kime1104ca2020-11-24 15:01:33 -0800307 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200308 if (tunnelFirstFrame) {
309 C2StreamTunnelHoldRender::input tunnelHoldRender{
310 0u /* stream */,
311 C2_TRUE /* value */
312 };
313 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
314 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800315 work->worklets.clear();
316 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800317
Wonsik Kime1104ca2020-11-24 15:01:33 -0800318 items.push_back(std::move(work));
319
320 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800321 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800322 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800323 work.reset(new C2Work);
324 work->input.ordinal.timestamp = timeUs;
325 work->input.ordinal.frameIndex = mFrameIndex++;
326 // WORKAROUND: keep client timestamp in customOrdinal
327 work->input.ordinal.customOrdinal = timeUs;
328 work->input.buffers.clear();
329 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800330 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800331 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800332 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800333 c2_status_t err = C2_OK;
334 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700335 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
336 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800337 {
338 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
339 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
340 for (const std::unique_ptr<C2Work> &work : items) {
341 watcher->onWorkQueued(
342 work->input.ordinal.frameIndex.peeku(),
343 std::vector(work->input.buffers),
344 now);
345 }
346 }
347 err = mComponent->queue(&items);
348 }
349 if (err != C2_OK) {
350 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
351 for (const std::unique_ptr<C2Work> &work : items) {
352 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
353 }
354 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700355 Mutexed<Input>::Locked input(mInput);
356 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700357 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700358 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700359 } else if (buffer) {
360 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700361 }
362 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
363 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800364 }
365
366 feedInputBufferIfAvailableInternal();
367 return err;
368}
369
370status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
371 QueueGuard guard(mSync);
372 if (!guard.isRunning()) {
373 ALOGD("[%s] setParameters is only supported in the running state.", mName);
374 return -ENOSYS;
375 }
376 mParamsToBeSet.insert(mParamsToBeSet.end(),
377 std::make_move_iterator(params.begin()),
378 std::make_move_iterator(params.end()));
379 params.clear();
380 return OK;
381}
382
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800383status_t CCodecBufferChannel::attachBuffer(
384 const std::shared_ptr<C2Buffer> &c2Buffer,
385 const sp<MediaCodecBuffer> &buffer) {
386 if (!buffer->copy(c2Buffer)) {
387 return -ENOSYS;
388 }
389 return OK;
390}
391
392void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
393 if (!mDecryptDestination || mDecryptDestination->size() < size) {
394 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
395 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
396 mCrypto->unsetHeap(mHeapSeqNum);
397 }
398 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
399 if (mCrypto) {
400 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
401 }
402 }
403}
404
405int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
406 CHECK(mCrypto);
407 auto it = mHeapSeqNumMap.find(memory);
408 int32_t heapSeqNum = -1;
409 if (it == mHeapSeqNumMap.end()) {
410 heapSeqNum = mCrypto->setHeap(memory);
411 mHeapSeqNumMap.emplace(memory, heapSeqNum);
412 } else {
413 heapSeqNum = it->second;
414 }
415 return heapSeqNum;
416}
417
418status_t CCodecBufferChannel::attachEncryptedBuffer(
419 const sp<hardware::HidlMemory> &memory,
420 bool secure,
421 const uint8_t *key,
422 const uint8_t *iv,
423 CryptoPlugin::Mode mode,
424 CryptoPlugin::Pattern pattern,
425 size_t offset,
426 const CryptoPlugin::SubSample *subSamples,
427 size_t numSubSamples,
428 const sp<MediaCodecBuffer> &buffer) {
429 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
430 static const C2MemoryUsage kDefaultReadWriteUsage{
431 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
432
433 size_t size = 0;
434 for (size_t i = 0; i < numSubSamples; ++i) {
435 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
436 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700437 if (size == 0) {
438 buffer->setRange(0, 0);
439 return OK;
440 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800441 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
442 std::shared_ptr<C2LinearBlock> block;
443 c2_status_t err = pool->fetchLinearBlock(
444 size,
445 secure ? kSecureUsage : kDefaultReadWriteUsage,
446 &block);
447 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700448 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
449 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800450 return NO_MEMORY;
451 }
452 if (!secure) {
453 ensureDecryptDestination(size);
454 }
455 ssize_t result = -1;
456 ssize_t codecDataOffset = 0;
457 if (mCrypto) {
458 AString errorDetailMsg;
459 int32_t heapSeqNum = getHeapSeqNum(memory);
460 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
461 hardware::drm::V1_0::DestinationBuffer dst;
462 if (secure) {
463 dst.type = DrmBufferType::NATIVE_HANDLE;
464 dst.secureMemory = hardware::hidl_handle(block->handle());
465 } else {
466 dst.type = DrmBufferType::SHARED_MEMORY;
467 IMemoryToSharedBuffer(
468 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
469 }
470 result = mCrypto->decrypt(
471 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
472 dst, &errorDetailMsg);
473 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700474 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800475 return result;
476 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800477 } else {
478 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
479 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
480 hidl_vec<SubSample> hidlSubSamples;
481 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
482
483 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
484 hardware::cas::native::V1_0::DestinationBuffer dst;
485 if (secure) {
486 dst.type = BufferType::NATIVE_HANDLE;
487 dst.secureMemory = hardware::hidl_handle(block->handle());
488 } else {
489 dst.type = BufferType::SHARED_MEMORY;
490 dst.nonsecureMemory = src;
491 }
492
493 CasStatus status = CasStatus::OK;
494 hidl_string detailedError;
495 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
496
497 if (key != nullptr) {
498 sctrl = (ScramblingControl)key[0];
499 // Adjust for the PES offset
500 codecDataOffset = key[2] | (key[3] << 8);
501 }
502
503 auto returnVoid = mDescrambler->descramble(
504 sctrl,
505 hidlSubSamples,
506 src,
507 0,
508 dst,
509 0,
510 [&status, &result, &detailedError] (
511 CasStatus _status, uint32_t _bytesWritten,
512 const hidl_string& _detailedError) {
513 status = _status;
514 result = (ssize_t)_bytesWritten;
515 detailedError = _detailedError;
516 });
517
518 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
519 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
520 mName, returnVoid.description().c_str(), status, result);
521 return UNKNOWN_ERROR;
522 }
523
524 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700525 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
526 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800527 return BAD_VALUE;
528 }
529 }
530 if (!secure) {
531 C2WriteView view = block->map().get();
532 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700533 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
534 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800535 return UNKNOWN_ERROR;
536 }
537 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700538 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
539 "(non-secure)",
540 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800541 return UNKNOWN_ERROR;
542 }
543 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
544 }
545 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
546 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
547 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700548 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800549 return -ENOSYS;
550 }
551 return OK;
552}
553
Pawin Vongmasa36653902018-11-15 00:10:25 -0800554status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
555 QueueGuard guard(mSync);
556 if (!guard.isRunning()) {
557 ALOGD("[%s] No more buffers should be queued at current state.", mName);
558 return -ENOSYS;
559 }
560 return queueInputBufferInternal(buffer);
561}
562
563status_t CCodecBufferChannel::queueSecureInputBuffer(
564 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
565 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
566 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
567 AString *errorDetailMsg) {
568 QueueGuard guard(mSync);
569 if (!guard.isRunning()) {
570 ALOGD("[%s] No more buffers should be queued at current state.", mName);
571 return -ENOSYS;
572 }
573
574 if (!hasCryptoOrDescrambler()) {
575 return -ENOSYS;
576 }
577 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
578
Sungtak Lee04b30352020-07-27 13:57:25 -0700579 std::shared_ptr<C2LinearBlock> block;
580 size_t allocSize = buffer->size();
581 size_t bufferSize = 0;
582 c2_status_t blockRes = C2_OK;
583 bool copied = false;
584 if (mSendEncryptedInfoBuffer) {
585 static const C2MemoryUsage kDefaultReadWriteUsage{
586 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
587 constexpr int kAllocGranule0 = 1024 * 64;
588 constexpr int kAllocGranule1 = 1024 * 1024;
589 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
590 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
591 if (allocSize <= kAllocGranule1) {
592 bufferSize = align(allocSize, kAllocGranule0);
593 } else {
594 bufferSize = align(allocSize, kAllocGranule1);
595 }
596 blockRes = pool->fetchLinearBlock(
597 bufferSize, kDefaultReadWriteUsage, &block);
598
599 if (blockRes == C2_OK) {
600 C2WriteView view = block->map().get();
601 if (view.error() == C2_OK && view.size() == bufferSize) {
602 copied = true;
603 // TODO: only copy clear sections
604 memcpy(view.data(), buffer->data(), allocSize);
605 }
606 }
607 }
608
609 if (!copied) {
610 block.reset();
611 }
612
Pawin Vongmasa36653902018-11-15 00:10:25 -0800613 ssize_t result = -1;
614 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700615 if (numSubSamples == 1
616 && subSamples[0].mNumBytesOfClearData == 0
617 && subSamples[0].mNumBytesOfEncryptedData == 0) {
618 // We don't need to go through crypto or descrambler if the input is empty.
619 result = 0;
620 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700621 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800622 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700623 destination.type = DrmBufferType::NATIVE_HANDLE;
624 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800625 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700626 destination.type = DrmBufferType::SHARED_MEMORY;
627 IMemoryToSharedBuffer(
628 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800629 }
Robert Shih895fba92019-07-16 16:29:44 -0700630 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800631 encryptedBuffer->fillSourceBuffer(&source);
632 result = mCrypto->decrypt(
633 key, iv, mode, pattern, source, buffer->offset(),
634 subSamples, numSubSamples, destination, errorDetailMsg);
635 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700636 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800637 return result;
638 }
Robert Shih895fba92019-07-16 16:29:44 -0700639 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800640 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
641 }
642 } else {
643 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
644 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
645 hidl_vec<SubSample> hidlSubSamples;
646 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
647
648 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
649 encryptedBuffer->fillSourceBuffer(&srcBuffer);
650
651 DestinationBuffer dstBuffer;
652 if (secure) {
653 dstBuffer.type = BufferType::NATIVE_HANDLE;
654 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
655 } else {
656 dstBuffer.type = BufferType::SHARED_MEMORY;
657 dstBuffer.nonsecureMemory = srcBuffer;
658 }
659
660 CasStatus status = CasStatus::OK;
661 hidl_string detailedError;
662 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
663
664 if (key != nullptr) {
665 sctrl = (ScramblingControl)key[0];
666 // Adjust for the PES offset
667 codecDataOffset = key[2] | (key[3] << 8);
668 }
669
670 auto returnVoid = mDescrambler->descramble(
671 sctrl,
672 hidlSubSamples,
673 srcBuffer,
674 0,
675 dstBuffer,
676 0,
677 [&status, &result, &detailedError] (
678 CasStatus _status, uint32_t _bytesWritten,
679 const hidl_string& _detailedError) {
680 status = _status;
681 result = (ssize_t)_bytesWritten;
682 detailedError = _detailedError;
683 });
684
685 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
686 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
687 mName, returnVoid.description().c_str(), status, result);
688 return UNKNOWN_ERROR;
689 }
690
691 if (result < codecDataOffset) {
692 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
693 return BAD_VALUE;
694 }
695
696 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
697
698 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
699 encryptedBuffer->copyDecryptedContentFromMemory(result);
700 }
701 }
702
703 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700704
705 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800706}
707
708void CCodecBufferChannel::feedInputBufferIfAvailable() {
709 QueueGuard guard(mSync);
710 if (!guard.isRunning()) {
711 ALOGV("[%s] We're not running --- no input buffer reported", mName);
712 return;
713 }
714 feedInputBufferIfAvailableInternal();
715}
716
717void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900718 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800719 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700720 }
721 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700722 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700723 if (!output->buffers ||
724 output->buffers->hasPending() ||
Wonsik Kim0487b782020-10-28 11:45:50 -0700725 output->buffers->numActiveSlots() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800726 return;
727 }
728 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700729 size_t numActiveSlots = 0;
730 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800731 sp<MediaCodecBuffer> inBuffer;
732 size_t index;
733 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700734 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700735 numActiveSlots = input->buffers->numActiveSlots();
736 if (numActiveSlots >= input->numSlots) {
737 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800738 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700739 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800740 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800741 break;
742 }
743 }
744 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
745 mCallback->onInputBufferAvailable(index, inBuffer);
746 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700747 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748}
749
750status_t CCodecBufferChannel::renderOutputBuffer(
751 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800752 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800753 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800754 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800755 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700756 Mutexed<Output>::Locked output(mOutput);
757 if (output->buffers) {
758 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759 }
760 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800761 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
762 // set to true.
763 sendOutputBuffers();
764 // input buffer feeding may have been gated by pending output buffers
765 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800766 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800767 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700768 std::call_once(mRenderWarningFlag, [this] {
769 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
770 "timestamp or render=true with non-video buffers. Apps should "
771 "call releaseOutputBuffer() with render=false for those.",
772 mName);
773 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800774 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800775 return INVALID_OPERATION;
776 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800777
778#if 0
779 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
780 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
781 for (const std::shared_ptr<const C2Info> &info : infoParams) {
782 AString res;
783 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
784 if (ix) res.append(", ");
785 res.append(*((int32_t*)info.get() + (ix / 4)));
786 }
787 ALOGV(" [%s]", res.c_str());
788 }
789#endif
790 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
791 std::static_pointer_cast<const C2StreamRotationInfo::output>(
792 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
793 bool flip = rotation && (rotation->flip & 1);
794 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900795
796 {
797 Mutexed<OutputSurface>::Locked output(mOutputSurface);
798 if (output->surface == nullptr) {
799 ALOGI("[%s] cannot render buffer without surface", mName);
800 return OK;
801 }
802 int64_t frameIndex;
803 buffer->meta()->findInt64("frameIndex", &frameIndex);
804 if (output->rotation.count(frameIndex) != 0) {
805 auto it = output->rotation.find(frameIndex);
806 quarters = (it->second / 90) & 3;
807 output->rotation.erase(it);
808 }
809 }
810
Pawin Vongmasa36653902018-11-15 00:10:25 -0800811 uint32_t transform = 0;
812 switch (quarters) {
813 case 0: // no rotation
814 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
815 break;
816 case 1: // 90 degrees counter-clockwise
817 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
818 : HAL_TRANSFORM_ROT_270;
819 break;
820 case 2: // 180 degrees
821 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
822 break;
823 case 3: // 90 degrees clockwise
824 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
825 : HAL_TRANSFORM_ROT_90;
826 break;
827 }
828
829 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
830 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
831 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
832 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
833 if (surfaceScaling) {
834 videoScalingMode = surfaceScaling->value;
835 }
836
837 // Use dataspace from format as it has the default aspects already applied
838 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
839 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
840
841 // HDR static info
842 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
843 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
844 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
845
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800846 // HDR10 plus info
847 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
848 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
849 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800850 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
851 hdr10PlusInfo.reset();
852 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800853
Wonsik Kima79c5522022-01-18 16:29:24 -0800854 // HDR dynamic info
855 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
856 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
857 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
858 // TODO: make this sticky & enable unset
859 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
860 hdrDynamicInfo.reset();
861 }
862
863 if (hdr10PlusInfo) {
864 // C2StreamHdr10PlusInfo is deprecated; components should use
865 // C2StreamHdrDynamicMetadataInfo
866 // TODO: #metric
867 if (hdrDynamicInfo) {
868 // It is unexpected that C2StreamHdr10PlusInfo and
869 // C2StreamHdrDynamicMetadataInfo is both present.
870 // C2StreamHdrDynamicMetadataInfo takes priority.
871 // TODO: #metric
872 } else {
873 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
874 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
875 hdr10PlusInfo->flexCount(),
876 0u,
877 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
878 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
879 hdrDynamicInfo = info;
880 }
881 }
882
Pawin Vongmasa36653902018-11-15 00:10:25 -0800883 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
884 if (blocks.size() != 1u) {
885 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
886 return UNKNOWN_ERROR;
887 }
888 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700889 C2Fence c2fence = block.fence();
890 sp<Fence> fence = Fence::NO_FENCE;
891 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
892 // Once C2Fence::type() is added, check the exact C2Fence type
893 if (c2fence.isHW()) {
894 int fenceFd = c2fence.fd();
895 fence = sp<Fence>::make(fenceFd);
896 if (!fence) {
897 ALOGE("[%s] Failed to allocate a fence", mName);
898 close(fenceFd);
899 return NO_MEMORY;
900 }
901 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800902
903 // TODO: revisit this after C2Fence implementation.
Brian Lindahlc953b462023-01-27 16:21:43 -0700904 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800905 timestampNs,
906 false, // droppable
907 dataSpace,
908 Rect(blocks.front().crop().left,
909 blocks.front().crop().top,
910 blocks.front().crop().right(),
911 blocks.front().crop().bottom()),
912 videoScalingMode,
913 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700914 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800915 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800916 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800917 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800918 // If mastering max and min luminance fields are 0, do not use them.
919 // It indicates the value may not be present in the stream.
920 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
921 hdrStaticInfo->mastering.minLuminance > 0.0f) {
922 struct android_smpte2086_metadata smpte2086_meta = {
923 .displayPrimaryRed = {
924 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
925 },
926 .displayPrimaryGreen = {
927 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
928 },
929 .displayPrimaryBlue = {
930 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
931 },
932 .whitePoint = {
933 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
934 },
935 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
936 .minLuminance = hdrStaticInfo->mastering.minLuminance,
937 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800938 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800939 hdr.smpte2086 = smpte2086_meta;
940 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700941 // If the content light level fields are 0, do not use them, it
942 // indicates the value may not be present in the stream.
943 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
944 struct android_cta861_3_metadata cta861_meta = {
945 .maxContentLightLevel = hdrStaticInfo->maxCll,
946 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
947 };
948 hdr.validTypes |= HdrMetadata::CTA861_3;
949 hdr.cta8613 = cta861_meta;
950 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900951
952 // does not have valid info
953 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
954 hdrStaticInfo.reset();
955 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800956 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800957 if (hdrDynamicInfo
958 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800959 hdr.validTypes |= HdrMetadata::HDR10PLUS;
960 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800961 hdrDynamicInfo->m.data,
962 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800963 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800964 qbi.setHdrMetadata(hdr);
965 }
Hongguangfc1478a2022-07-20 22:56:06 -0700966 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
967
Brian Lindahlc953b462023-01-27 16:21:43 -0700968 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
969 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
970 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800971 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
972 if (result != OK) {
973 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800974 if (result == NO_INIT) {
975 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
976 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800977 return result;
978 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800979
980 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
981 ALOGD("[%s] queue buffer successful", mName);
982 } else {
983 ALOGV("[%s] queue buffer successful", mName);
984 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800985
986 int64_t mediaTimeUs = 0;
987 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahle31a52d2023-04-05 08:49:23 -0600988 if (mIsSurfaceToDisplay) {
989 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
990 processRenderedFrames(qbo.frameTimestamps);
991 } else {
992 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
993 // when the frame is queued to the non-display surface
994 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
995 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800996
997 return OK;
998}
999
Brian Lindahlc953b462023-01-27 16:21:43 -07001000void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahle31a52d2023-04-05 08:49:23 -06001001 mTrackedFrames.clear();
1002
1003 int isSurfaceToDisplay = 0;
1004 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1005 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1006 // No frame tracking is needed if we're not sending frames to the display
1007 if (!mIsSurfaceToDisplay) {
1008 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1009 return;
1010 }
1011
Brian Lindahlc953b462023-01-27 16:21:43 -07001012 int hasPresentFenceTimes = 0;
1013 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1014 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
1015 if (mHasPresentFenceTimes) {
1016 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1017 }
Brian Lindahlc953b462023-01-27 16:21:43 -07001018}
1019
1020void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1021 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1022 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1023 // so track the frame as if the desired render time is now.
1024 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1025 if (desiredRenderTimeNs < nowNs) {
1026 desiredRenderTimeNs = nowNs;
1027 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001028 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1029 // actually rendered.
Brian Lindahlc953b462023-01-27 16:21:43 -07001030 TrackedFrame frame;
1031 frame.number = qbo.nextFrameNumber - 1;
1032 frame.mediaTimeUs = mediaTimeUs;
1033 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1034 frame.latchTime = -1;
1035 frame.presentFence = nullptr;
1036 mTrackedFrames.push_back(frame);
1037}
1038
1039void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1040 // Grab the latch times and present fences from the frame event deltas
1041 for (const auto& delta : deltas) {
1042 for (auto& frame : mTrackedFrames) {
1043 if (delta.getFrameNumber() == frame.number) {
1044 delta.getLatchTime(&frame.latchTime);
1045 delta.getDisplayPresentFence(&frame.presentFence);
1046 }
1047 }
1048 }
1049
1050 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1051 // in fact, been rendered.
1052 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1053 while (!mTrackedFrames.empty()) {
1054 TrackedFrame & frame = mTrackedFrames.front();
1055 // Frames that should have been rendered at least 100ms in the past are checked
1056 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1057 break;
1058 }
1059
1060 // If we don't have a render time by now, then consider the frame as dropped
1061 int64_t renderTimeNs = getRenderTimeNs(frame);
1062 if (renderTimeNs != -1) {
1063 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1064 }
1065 mTrackedFrames.pop_front();
1066 }
1067}
1068
1069int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1070 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1071 if (!mHasPresentFenceTimes) {
1072 if (frame.latchTime == -1) {
1073 ALOGD("no latch time for frame %d", (int) frame.number);
1074 return -1;
1075 }
1076 return frame.latchTime;
1077 }
1078
1079 if (frame.presentFence == nullptr) {
1080 ALOGW("no present fence for frame %d", (int) frame.number);
1081 return -1;
1082 }
1083
1084 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1085
1086 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1087 ALOGW("invalid signal time for frame %d", (int) frame.number);
1088 return -1;
1089 }
1090
1091 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1092 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1093 return -1;
1094 }
1095
1096 return actualRenderTimeNs;
1097}
1098
1099void CCodecBufferChannel::pollForRenderedBuffers() {
1100 FrameEventHistoryDelta delta;
1101 mComponent->pollForRenderedFrames(&delta);
1102 processRenderedFrames(delta);
1103}
1104
Pawin Vongmasa36653902018-11-15 00:10:25 -08001105status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1106 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1107 bool released = false;
1108 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001109 Mutexed<Input>::Locked input(mInput);
1110 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001111 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001112 }
1113 }
1114 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001115 Mutexed<Output>::Locked output(mOutput);
1116 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001117 released = true;
1118 }
1119 }
1120 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001121 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001122 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001123 } else {
1124 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1125 }
1126 return OK;
1127}
1128
1129void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1130 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001131 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001132
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001133 if (!input->buffers) {
1134 ALOGE("getInputBufferArray: No Input Buffers allocated");
1135 return;
1136 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001137 if (!input->buffers->isArrayMode()) {
1138 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001139 }
1140
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001141 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001142}
1143
1144void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1145 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001146 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001147 if (!output->buffers) {
1148 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1149 return;
1150 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001151 if (!output->buffers->isArrayMode()) {
1152 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001153 }
1154
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001155 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001156}
1157
1158status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001159 const sp<AMessage> &inputFormat,
1160 const sp<AMessage> &outputFormat,
1161 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001162 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1163 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001164 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001165 C2PortReorderBufferDepthTuning::output reorderDepth;
1166 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001167 C2PortActualDelayTuning::input inputDelay(0);
1168 C2PortActualDelayTuning::output outputDelay(0);
1169 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001170 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001171
Pawin Vongmasa36653902018-11-15 00:10:25 -08001172 c2_status_t err = mComponent->query(
1173 {
1174 &iStreamFormat,
1175 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001176 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001177 &reorderDepth,
1178 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001179 &inputDelay,
1180 &pipelineDelay,
1181 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001182 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001183 },
1184 {},
1185 C2_DONT_BLOCK,
1186 nullptr);
1187 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001188 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001189 return UNKNOWN_ERROR;
1190 }
1191 } else if (err != C2_OK) {
1192 return UNKNOWN_ERROR;
1193 }
1194
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001195 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1196 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1197 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1198
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001199 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1200 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001201
Pawin Vongmasa36653902018-11-15 00:10:25 -08001202 // TODO: get this from input format
1203 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1204
Sungtak Lee04b30352020-07-27 13:57:25 -07001205 // secure mode is a static parameter (shall not change in the executing state)
1206 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1207
Pawin Vongmasa36653902018-11-15 00:10:25 -08001208 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001209 int poolMask = GetCodec2PoolMask();
1210 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001211
1212 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001213 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001214 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001215 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1216 API_REFLECTION |
1217 API_VALUES |
1218 API_CURRENT_VALUES |
1219 API_DEPENDENCY |
1220 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001221 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1222 C2StreamSampleRateInfo::input sampleRate(0u);
1223 C2StreamChannelCountInfo::input channelCount(0u);
1224 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001225 std::shared_ptr<C2BlockPool> pool;
1226 {
1227 Mutexed<BlockPools>::Locked pools(mBlockPools);
1228
1229 // set default allocator ID.
1230 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001231 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001232
1233 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1234 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1235 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001236 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001237 std::vector<C2Param *> stackParams({&featuresSetting});
1238 if (audioEncoder) {
1239 stackParams.push_back(&encoderFrameSize);
1240 stackParams.push_back(&sampleRate);
1241 stackParams.push_back(&channelCount);
1242 stackParams.push_back(&pcmEncoding);
1243 } else {
1244 encoderFrameSize.invalidate();
1245 sampleRate.invalidate();
1246 channelCount.invalidate();
1247 pcmEncoding.invalidate();
1248 }
1249 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001250 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1251 C2_DONT_BLOCK,
1252 &params);
1253 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1254 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1255 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001256 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001257 C2PortAllocatorsTuning::input *inputAllocators =
1258 C2PortAllocatorsTuning::input::From(params[0].get());
1259 if (inputAllocators && inputAllocators->flexCount() > 0) {
1260 std::shared_ptr<C2Allocator> allocator;
1261 // verify allocator IDs and resolve default allocator
1262 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1263 if (allocator) {
1264 pools->inputAllocatorId = allocator->getId();
1265 } else {
1266 ALOGD("[%s] component requested invalid input allocator ID %u",
1267 mName, inputAllocators->m.values[0]);
1268 }
1269 }
1270 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001271 if (featuresSetting) {
1272 apiFeatures = featuresSetting.value;
1273 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001274
1275 // TODO: use C2Component wrapper to associate this pool with ourselves
1276 if ((poolMask >> pools->inputAllocatorId) & 1) {
1277 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1278 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1279 mName, pools->inputAllocatorId,
1280 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1281 asString(err), err);
1282 } else {
1283 err = C2_NOT_FOUND;
1284 }
1285 if (err != C2_OK) {
1286 C2BlockPool::local_id_t inputPoolId =
1287 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1288 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1289 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1290 mName, (unsigned long long)inputPoolId,
1291 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1292 asString(err), err);
1293 if (err != C2_OK) {
1294 return NO_MEMORY;
1295 }
1296 }
1297 pools->inputPool = pool;
1298 }
1299
Wonsik Kim51051262018-11-28 13:59:05 -08001300 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001301 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001302 input->inputDelay = inputDelayValue;
1303 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001304 input->numSlots = numInputSlots;
1305 input->extraBuffers.flush();
1306 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001307 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001308 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1309 input->frameReassembler.init(
1310 pool,
1311 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1312 encoderFrameSize.value,
1313 sampleRate.value,
1314 channelCount.value,
1315 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1316 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001317 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1318 // For encrypted content, framework decrypts source buffer (ashmem) into
1319 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001320 if (!buffersBoundToCodec
1321 && !input->frameReassembler
1322 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001323 input->buffers.reset(new SlotInputBuffers(mName));
1324 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001325 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001326 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001327 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001328 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001329 // This is to ensure buffers do not get released prematurely.
1330 // TODO: handle this without going into array mode
1331 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001332 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001333 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001334 }
1335 } else {
1336 if (hasCryptoOrDescrambler()) {
1337 int32_t capacity = kLinearBufferSize;
1338 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1339 if ((size_t)capacity > kMaxLinearBufferSize) {
1340 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1341 capacity = kMaxLinearBufferSize;
1342 }
1343 if (mDealer == nullptr) {
1344 mDealer = new MemoryDealer(
1345 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001346 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001347 "EncryptedLinearInputBuffers");
1348 mDecryptDestination = mDealer->allocate((size_t)capacity);
1349 }
1350 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001351 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1352 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001353 } else {
1354 mHeapSeqNum = -1;
1355 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001356 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001357 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001358 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001359 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001360 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001361 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001362 }
1363 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001364 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001365
1366 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001367 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001368 } else {
1369 // TODO: error
1370 }
Wonsik Kim51051262018-11-28 13:59:05 -08001371
1372 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001373 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001374 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001375 }
1376
1377 if (outputFormat != nullptr) {
1378 sp<IGraphicBufferProducer> outputSurface;
1379 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001380 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001381 {
1382 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001383 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001384 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001385 outputSurface = output->surface ?
1386 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001387 if (outputSurface) {
1388 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1389 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001390 outputGeneration = output->generation;
1391 }
1392
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001393 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001395 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001396
1397 {
1398 Mutexed<BlockPools>::Locked pools(mBlockPools);
1399
David Stevensc3fbb282021-01-18 18:11:20 +09001400 prevOutputPoolId = pools->outputPoolId;
1401
Pawin Vongmasa36653902018-11-15 00:10:25 -08001402 // set default allocator ID.
1403 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001404 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001405
1406 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1407 // unsuccessful.
1408 std::vector<std::unique_ptr<C2Param>> params;
1409 err = mComponent->query({ },
1410 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1411 C2_DONT_BLOCK,
1412 &params);
1413 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1414 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1415 mName, params.size(), asString(err), err);
1416 } else if (err == C2_OK && params.size() == 1) {
1417 C2PortAllocatorsTuning::output *outputAllocators =
1418 C2PortAllocatorsTuning::output::From(params[0].get());
1419 if (outputAllocators && outputAllocators->flexCount() > 0) {
1420 std::shared_ptr<C2Allocator> allocator;
1421 // verify allocator IDs and resolve default allocator
1422 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1423 if (allocator) {
1424 pools->outputAllocatorId = allocator->getId();
1425 } else {
1426 ALOGD("[%s] component requested invalid output allocator ID %u",
1427 mName, outputAllocators->m.values[0]);
1428 }
1429 }
1430 }
1431
1432 // use bufferqueue if outputting to a surface.
1433 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1434 // if unsuccessful.
1435 if (outputSurface) {
1436 params.clear();
1437 err = mComponent->query({ },
1438 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1439 C2_DONT_BLOCK,
1440 &params);
1441 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1442 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1443 mName, params.size(), asString(err), err);
1444 } else if (err == C2_OK && params.size() == 1) {
1445 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1446 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1447 if (surfaceAllocator) {
1448 std::shared_ptr<C2Allocator> allocator;
1449 // verify allocator IDs and resolve default allocator
1450 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1451 if (allocator) {
1452 pools->outputAllocatorId = allocator->getId();
1453 } else {
1454 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1455 mName, surfaceAllocator->value);
1456 err = C2_BAD_VALUE;
1457 }
1458 }
1459 }
1460 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1461 && err != C2_OK
1462 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1463 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1464 }
1465 }
1466
1467 if ((poolMask >> pools->outputAllocatorId) & 1) {
1468 err = mComponent->createBlockPool(
1469 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1470 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1471 mName, pools->outputAllocatorId,
1472 (unsigned long long)pools->outputPoolId,
1473 asString(err));
1474 } else {
1475 err = C2_NOT_FOUND;
1476 }
1477 if (err != C2_OK) {
1478 // use basic pool instead
1479 pools->outputPoolId =
1480 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1481 }
1482
1483 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1484 // component.
1485 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1486 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1487
1488 std::vector<std::unique_ptr<C2SettingResult>> failures;
1489 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1490 ALOGD("[%s] Configured output block pool ids %llu => %s",
1491 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1492 outputPoolId_ = pools->outputPoolId;
1493 }
1494
David Stevensc3fbb282021-01-18 18:11:20 +09001495 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1496 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1497 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1498 if (err != C2_OK) {
1499 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1500 (unsigned long long) prevOutputPoolId, asString(err), err);
1501 }
1502 }
1503
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001504 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001505 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001506 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001507 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001508 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001509 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001510 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001511 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001512 }
1513 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001514 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001515 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001516 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001517
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001518 output->buffers->clearStash();
1519 if (reorderDepth) {
1520 output->buffers->setReorderDepth(reorderDepth.value);
1521 }
1522 if (reorderKey) {
1523 output->buffers->setReorderKey(reorderKey.value);
1524 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001525
1526 // Try to set output surface to created block pool if given.
1527 if (outputSurface) {
1528 mComponent->setOutputSurface(
1529 outputPoolId_,
1530 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001531 outputGeneration,
1532 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001533 } else {
1534 // configure CPU read consumer usage
1535 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1536 std::vector<std::unique_ptr<C2SettingResult>> failures;
1537 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1538 // do not print error message for now as most components may not yet
1539 // support this setting
1540 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1541 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001542 }
1543
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001544 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001545 if (buffersBoundToCodec) {
1546 // WORKAROUND: if we're using early CSD workaround we convert to
1547 // array mode, to appease apps assuming the output
1548 // buffers to be of the same size.
1549 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1550 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001551
1552 int32_t channelCount;
1553 int32_t sampleRate;
1554 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1555 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1556 int32_t delay = 0;
1557 int32_t padding = 0;;
1558 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1559 delay = 0;
1560 }
1561 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1562 padding = 0;
1563 }
1564 if (delay || padding) {
1565 // We need write access to the buffers, and we're already in
1566 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001567 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001568 }
1569 }
1570 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001571
1572 int32_t tunneled = 0;
1573 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1574 tunneled = 0;
1575 }
1576 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001577 }
1578
1579 // Set up pipeline control. This has to be done after mInputBuffers and
1580 // mOutputBuffers are initialized to make sure that lingering callbacks
1581 // about buffers from the previous generation do not interfere with the
1582 // newly initialized pipeline capacity.
1583
Wonsik Kim62545252021-01-20 11:25:41 -08001584 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001585 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001586 watcher->inputDelay(inputDelayValue)
1587 .pipelineDelay(pipelineDelayValue)
1588 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001589 .smoothnessFactor(kSmoothnessFactor);
1590 watcher->flush();
1591 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001592
1593 mInputMetEos = false;
1594 mSync.start();
1595 return OK;
1596}
1597
Wonsik Kim34b28b42022-05-20 15:49:32 -07001598status_t CCodecBufferChannel::prepareInitialInputBuffers(
1599 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001600 if (mInputSurface) {
1601 return OK;
1602 }
1603
Wonsik Kim34b28b42022-05-20 15:49:32 -07001604 size_t numInputSlots = mInput.lock()->numSlots;
1605
1606 {
1607 Mutexed<Input>::Locked input(mInput);
1608 while (clientInputBuffers->size() < numInputSlots) {
1609 size_t index;
1610 sp<MediaCodecBuffer> buffer;
1611 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1612 break;
1613 }
1614 clientInputBuffers->emplace(index, buffer);
1615 }
1616 }
1617 if (clientInputBuffers->empty()) {
1618 ALOGW("[%s] start: cannot allocate memory at all", mName);
1619 return NO_MEMORY;
1620 } else if (clientInputBuffers->size() < numInputSlots) {
1621 ALOGD("[%s] start: cannot allocate memory for all slots, "
1622 "only %zu buffers allocated",
1623 mName, clientInputBuffers->size());
1624 } else {
1625 ALOGV("[%s] %zu initial input buffers available",
1626 mName, clientInputBuffers->size());
1627 }
1628 return OK;
1629}
1630
1631status_t CCodecBufferChannel::requestInitialInputBuffers(
1632 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001633 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001634 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1635 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1636 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001637 return UNKNOWN_ERROR;
1638 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001639
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001640 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1641 mFlushedConfigs.lock()->swap(flushedConfigs);
1642 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001643 {
1644 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1645 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1646 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1647 watcher->onWorkQueued(
1648 work->input.ordinal.frameIndex.peeku(),
1649 std::vector(work->input.buffers),
1650 now);
1651 }
1652 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001653 err = mComponent->queue(&flushedConfigs);
1654 if (err != C2_OK) {
1655 ALOGW("[%s] Error while queueing a flushed config", mName);
1656 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001657 }
1658 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001659 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001660 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1661 !clientInputBuffers.empty()) {
1662 size_t minIndex = clientInputBuffers.begin()->first;
1663 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1664 for (const auto &[index, buffer] : clientInputBuffers) {
1665 if (minBuffer->capacity() > buffer->capacity()) {
1666 minIndex = index;
1667 minBuffer = buffer;
1668 }
1669 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001670 // WORKAROUND: Some apps expect CSD available without queueing
1671 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001672 minBuffer->setRange(0, 0);
1673 minBuffer->meta()->clear();
1674 minBuffer->meta()->setInt64("timeUs", 0);
1675 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001676 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1677 mName);
1678 return UNKNOWN_ERROR;
1679 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001680 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001681 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001682
Wonsik Kim34b28b42022-05-20 15:49:32 -07001683 for (const auto &[index, buffer] : clientInputBuffers) {
1684 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001685 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001686
Pawin Vongmasa36653902018-11-15 00:10:25 -08001687 return OK;
1688}
1689
1690void CCodecBufferChannel::stop() {
1691 mSync.stop();
1692 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001693}
1694
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001695void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
1696 sp<Surface> surface = mOutputSurface.lock()->surface;
1697 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00001698 C2BlockPool::local_id_t outputPoolId;
1699 {
1700 Mutexed<BlockPools>::Locked pools(mBlockPools);
1701 outputPoolId = pools->outputPoolId;
1702 }
1703 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001704
1705 if (pushBlankBuffer) {
1706 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
1707 if (anw) {
1708 pushBlankBuffersToNativeWindow(anw.get());
1709 }
1710 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00001711 }
1712}
1713
Wonsik Kim936a89c2020-05-08 16:07:50 -07001714void CCodecBufferChannel::reset() {
1715 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001716 if (mInputSurface != nullptr) {
1717 mInputSurface.reset();
1718 }
1719 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001720 {
1721 Mutexed<Input>::Locked input(mInput);
1722 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001723 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001724 }
1725 {
1726 Mutexed<Output>::Locked output(mOutput);
1727 output->buffers.reset();
1728 }
Brian Lindahlc953b462023-01-27 16:21:43 -07001729 // reset the frames that are being tracked for onFrameRendered callbacks
1730 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001731}
1732
1733void CCodecBufferChannel::release() {
1734 mComponent.reset();
1735 mInputAllocator.reset();
1736 mOutputSurface.lock()->surface.clear();
1737 {
1738 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1739 blockPools->inputPool.reset();
1740 blockPools->outputPoolIntf.reset();
1741 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001742 setCrypto(nullptr);
1743 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001744}
1745
Pawin Vongmasa36653902018-11-15 00:10:25 -08001746void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1747 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001748 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001749 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001750 {
1751 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1752 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1753 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1754 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1755 watcher->onWorkDone(frameIndex);
1756 continue;
1757 }
1758 if (work->input.buffers.empty()
1759 || work->input.buffers.front() == nullptr
1760 || work->input.buffers.front()->data().linearBlocks().empty()) {
1761 ALOGD("[%s] no linear codec config data found", mName);
1762 watcher->onWorkDone(frameIndex);
1763 continue;
1764 }
1765 std::unique_ptr<C2Work> copy(new C2Work);
1766 copy->input.flags = C2FrameData::flags_t(
1767 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1768 copy->input.ordinal = work->input.ordinal;
1769 copy->input.ordinal.frameIndex = mFrameIndex++;
1770 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1771 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1772 }
1773 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1774 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1775 }
1776 copy->input.infoBuffers.insert(
1777 copy->input.infoBuffers.begin(),
1778 work->input.infoBuffers.begin(),
1779 work->input.infoBuffers.end());
1780 copy->worklets.emplace_back(new C2Worklet);
1781 configs.push_back(std::move(copy));
1782 watcher->onWorkDone(frameIndex);
1783 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001784 }
1785 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001786 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001787 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001788 Mutexed<Input>::Locked input(mInput);
1789 input->buffers->flush();
1790 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001791 }
1792 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001793 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001794 if (output->buffers) {
1795 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001796 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001797 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001798 }
Brian Lindahlc953b462023-01-27 16:21:43 -07001799 // reset the frames that are being tracked for onFrameRendered callbacks
1800 mTrackedFrames.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001801}
1802
1803void CCodecBufferChannel::onWorkDone(
1804 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001805 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001806 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001807 feedInputBufferIfAvailable();
1808 }
1809}
1810
1811void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001812 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001813 if (mInputSurface) {
1814 return;
1815 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001816 std::shared_ptr<C2Buffer> buffer =
1817 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001818 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001819 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001820 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001821 if (input->lastFlushIndex >= frameIndex) {
1822 ALOGD("[%s] Ignoring stale input buffer done callback: "
1823 "last flush index = %lld, frameIndex = %lld",
1824 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1825 } else {
1826 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1827 if (!newInputSlotAvailable) {
1828 (void)input->extraBuffers.expireComponentBuffer(buffer);
1829 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001830 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001831 }
1832 if (newInputSlotAvailable) {
1833 feedInputBufferIfAvailable();
1834 }
1835}
1836
1837bool CCodecBufferChannel::handleWork(
1838 std::unique_ptr<C2Work> work,
1839 const sp<AMessage> &outputFormat,
1840 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001841 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001842 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001843 if (!output->buffers) {
1844 return false;
1845 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001846 }
1847
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001848 // Whether the output buffer should be reported to the client or not.
1849 bool notifyClient = false;
1850
1851 if (work->result == C2_OK){
1852 notifyClient = true;
1853 } else if (work->result == C2_NOT_FOUND) {
1854 ALOGD("[%s] flushed work; ignored.", mName);
1855 } else {
1856 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1857 // the config update.
1858 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1859 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1860 return false;
1861 }
1862
1863 if ((work->input.ordinal.frameIndex -
1864 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001865 // Discard frames from previous generation.
1866 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001867 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001868 }
1869
Wonsik Kim524b0582019-03-12 11:28:57 -07001870 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001871 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001872 || !(work->worklets.front()->output.flags &
1873 C2FrameData::FLAG_INCOMPLETE))) {
1874 mPipelineWatcher.lock()->onWorkDone(
1875 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001876 }
1877
1878 // NOTE: MediaCodec usage supposedly have only one worklet
1879 if (work->worklets.size() != 1u) {
1880 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1881 mName, work->worklets.size());
1882 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1883 return false;
1884 }
1885
1886 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1887
1888 std::shared_ptr<C2Buffer> buffer;
1889 // NOTE: MediaCodec usage supposedly have only one output stream.
1890 if (worklet->output.buffers.size() > 1u) {
1891 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1892 mName, worklet->output.buffers.size());
1893 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1894 return false;
1895 } else if (worklet->output.buffers.size() == 1u) {
1896 buffer = worklet->output.buffers[0];
1897 if (!buffer) {
1898 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1899 }
1900 }
1901
Wonsik Kim3dedf682021-05-03 10:57:09 -07001902 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1903 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001904 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001905 while (!worklet->output.configUpdate.empty()) {
1906 std::unique_ptr<C2Param> param;
1907 worklet->output.configUpdate.back().swap(param);
1908 worklet->output.configUpdate.pop_back();
1909 switch (param->coreIndex().coreIndex()) {
1910 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1911 C2PortReorderBufferDepthTuning::output reorderDepth;
1912 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001913 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1914 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001915 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001916 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001917 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001918 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1919 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001920 }
1921 break;
1922 }
1923 case C2PortReorderKeySetting::CORE_INDEX: {
1924 C2PortReorderKeySetting::output reorderKey;
1925 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001926 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001927 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1928 mName, reorderKey.value);
1929 } else {
1930 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1931 }
1932 break;
1933 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001934 case C2PortActualDelayTuning::CORE_INDEX: {
1935 if (param->isGlobal()) {
1936 C2ActualPipelineDelayTuning pipelineDelay;
1937 if (pipelineDelay.updateFrom(*param)) {
1938 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1939 mName, pipelineDelay.value);
1940 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001941 (void)mPipelineWatcher.lock()->pipelineDelay(
1942 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001943 }
1944 }
1945 if (param->forInput()) {
1946 C2PortActualDelayTuning::input inputDelay;
1947 if (inputDelay.updateFrom(*param)) {
1948 ALOGV("[%s] onWorkDone: updating input delay %u",
1949 mName, inputDelay.value);
1950 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001951 (void)mPipelineWatcher.lock()->inputDelay(
1952 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001953 }
1954 }
1955 if (param->forOutput()) {
1956 C2PortActualDelayTuning::output outputDelay;
1957 if (outputDelay.updateFrom(*param)) {
1958 ALOGV("[%s] onWorkDone: updating output delay %u",
1959 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001960 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001961 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001962 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001963
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001964 }
1965 }
1966 break;
1967 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001968 case C2PortTunnelSystemTime::CORE_INDEX: {
1969 C2PortTunnelSystemTime::output frameRenderTime;
1970 if (frameRenderTime.updateFrom(*param)) {
1971 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1972 mName, (long long)frameRenderTime.value,
1973 (long long)worklet->output.ordinal.timestamp.peekll());
1974 mCCodecCallback->onOutputFramesRendered(
1975 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1976 }
1977 break;
1978 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001979 case C2StreamTunnelHoldRender::CORE_INDEX: {
1980 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1981 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1982 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1983 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1984 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1985 mCCodecCallback->onFirstTunnelFrameReady();
1986 break;
1987 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001988 default:
1989 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1990 mName, param->index());
1991 break;
1992 }
1993 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001994 if (newInputDelay || newPipelineDelay) {
1995 Mutexed<Input>::Locked input(mInput);
1996 size_t newNumSlots =
1997 newInputDelay.value_or(input->inputDelay) +
1998 newPipelineDelay.value_or(input->pipelineDelay) +
1999 kSmoothnessFactor;
2000 if (input->buffers->isArrayMode()) {
2001 if (input->numSlots >= newNumSlots) {
2002 input->numExtraSlots = 0;
2003 } else {
2004 input->numExtraSlots = newNumSlots - input->numSlots;
2005 }
2006 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2007 mName, input->numExtraSlots);
2008 } else {
2009 input->numSlots = newNumSlots;
2010 }
2011 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002012 size_t numOutputSlots = 0;
2013 uint32_t reorderDepth = 0;
2014 bool outputBuffersChanged = false;
2015 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2016 Mutexed<Output>::Locked output(mOutput);
2017 if (!output->buffers) {
2018 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002019 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002020 numOutputSlots = output->numSlots;
2021 if (newReorderKey) {
2022 output->buffers->setReorderKey(newReorderKey.value());
2023 }
2024 if (newReorderDepth) {
2025 output->buffers->setReorderDepth(newReorderDepth.value());
2026 }
2027 reorderDepth = output->buffers->getReorderDepth();
2028 if (newOutputDelay) {
2029 output->outputDelay = newOutputDelay.value();
2030 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2031 if (output->numSlots < numOutputSlots) {
2032 output->numSlots = numOutputSlots;
2033 if (output->buffers->isArrayMode()) {
2034 OutputBuffersArray *array =
2035 (OutputBuffersArray *)output->buffers.get();
2036 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2037 mName, numOutputSlots);
2038 array->grow(numOutputSlots);
2039 outputBuffersChanged = true;
2040 }
2041 }
2042 }
2043 numOutputSlots = output->numSlots;
2044 }
2045 if (outputBuffersChanged) {
2046 mCCodecCallback->onOutputBuffersChanged();
2047 }
2048 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002049 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002050 {
2051 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2052 maxDequeueCount = output->maxDequeueBuffers =
2053 numOutputSlots + reorderDepth + kRenderingDepth;
2054 if (output->surface) {
2055 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2056 }
2057 }
2058 if (maxDequeueCount > 0) {
2059 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002060 }
2061 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002062
Pawin Vongmasa36653902018-11-15 00:10:25 -08002063 int32_t flags = 0;
2064 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002065 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002066 ALOGV("[%s] onWorkDone: output EOS", mName);
2067 }
2068
Pawin Vongmasa36653902018-11-15 00:10:25 -08002069 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2070 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2071 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2072 // shall correspond to the client input timesamp (in customOrdinal). By using the
2073 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2074 // produces multiple output.
2075 c2_cntr64_t timestamp =
2076 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2077 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002078 if (mInputSurface != nullptr) {
2079 // When using input surface we need to restore the original input timestamp.
2080 timestamp = work->input.ordinal.customOrdinal;
2081 }
My Name6bd9a7d2022-03-25 12:37:58 -07002082 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2083 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002084 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2085 mName,
2086 work->input.ordinal.customOrdinal.peekll(),
2087 work->input.ordinal.timestamp.peekll(),
2088 worklet->output.ordinal.timestamp.peekll(),
2089 timestamp.peekll());
2090
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002091 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002092 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002093 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002094 if (!output->buffers) {
2095 return false;
2096 }
2097 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002098 output->buffers->updateSkipCutBuffer(outputFormat);
2099 output->buffers->setFormat(outputFormat);
2100 }
2101 if (!notifyClient) {
2102 return false;
2103 }
2104 size_t index;
2105 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002106 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002107 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002108 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002109 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2110
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002111 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002112 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002113 } else {
2114 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002115 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002116 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002117 return false;
2118 }
2119 }
2120
Wonsik Kimec585c32021-10-01 01:11:00 -07002121 bool drop = false;
2122 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2123 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2124 drop = true;
2125 }
2126
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002127 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002128 if (mTunneled && drop && outputFormat) {
2129 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2130 mName, work->input.ordinal.frameIndex.peekull());
2131 } else {
2132 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2133 mName, work->input.ordinal.frameIndex.peekull());
2134 notifyClient = false;
2135 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002136 }
2137
2138 if (buffer) {
2139 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2140 // TODO: properly translate these to metadata
2141 switch (info->coreIndex().coreIndex()) {
2142 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002143 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002144 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002145 }
2146 break;
2147 default:
2148 break;
2149 }
2150 }
2151 }
2152
2153 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002154 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002155 if (!output->buffers) {
2156 return false;
2157 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002158 output->buffers->pushToStash(
2159 buffer,
2160 notifyClient,
2161 timestamp.peek(),
2162 flags,
2163 outputFormat,
2164 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002165 }
2166 sendOutputBuffers();
2167 return true;
2168}
2169
2170void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002171 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002172 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002173 sp<MediaCodecBuffer> outBuffer;
2174 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002175
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002176 constexpr int kMaxReallocTry = 5;
2177 int reallocTryNum = 0;
2178
Pawin Vongmasa36653902018-11-15 00:10:25 -08002179 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002180 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002181 if (!output->buffers) {
2182 return;
2183 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002184 action = output->buffers->popFromStashAndRegister(
2185 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002186 if (action != OutputBuffers::REALLOCATE) {
2187 reallocTryNum = 0;
2188 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002189 switch (action) {
2190 case OutputBuffers::SKIP:
2191 return;
2192 case OutputBuffers::DISCARD:
2193 break;
2194 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00002195 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002196 mCallback->onOutputBufferAvailable(index, outBuffer);
2197 break;
2198 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002199 if (++reallocTryNum > kMaxReallocTry) {
2200 output.unlock();
2201 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2202 mName, kMaxReallocTry);
2203 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2204 return;
2205 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002206 if (!output->buffers->isArrayMode()) {
2207 output->buffers =
2208 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002209 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002210 static_cast<OutputBuffersArray*>(output->buffers.get())->
2211 realloc(c2Buffer);
2212 output.unlock();
2213 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002214 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002215 case OutputBuffers::RETRY:
2216 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2217 mName);
2218 return;
2219 default:
2220 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2221 "corrupted BufferAction value (%d) "
2222 "returned from popFromStashAndRegister.",
2223 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002224 return;
2225 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002226 }
2227}
2228
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002229status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002230 static std::atomic_uint32_t surfaceGeneration{0};
2231 uint32_t generation = (getpid() << 10) |
2232 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2233 & ((1 << 10) - 1));
2234
2235 sp<IGraphicBufferProducer> producer;
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002236 int maxDequeueCount;
2237 sp<Surface> oldSurface;
2238 {
2239 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2240 maxDequeueCount = outputSurface->maxDequeueBuffers;
2241 oldSurface = outputSurface->surface;
2242 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002243 if (newSurface) {
2244 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002245 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002246 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002247 producer = newSurface->getIGraphicBufferProducer();
2248 producer->setGenerationNumber(generation);
2249 } else {
2250 ALOGE("[%s] setting output surface to null", mName);
2251 return INVALID_OPERATION;
2252 }
2253
2254 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2255 C2BlockPool::local_id_t outputPoolId;
2256 {
2257 Mutexed<BlockPools>::Locked pools(mBlockPools);
2258 outputPoolId = pools->outputPoolId;
2259 outputPoolIntf = pools->outputPoolIntf;
2260 }
2261
2262 if (outputPoolIntf) {
2263 if (mComponent->setOutputSurface(
2264 outputPoolId,
2265 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002266 generation,
2267 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002268 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2269 return INVALID_OPERATION;
2270 }
2271 }
2272
2273 {
2274 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2275 output->surface = newSurface;
2276 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002277 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002278 }
2279
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002280 if (oldSurface && pushBlankBuffer) {
2281 // When ReleaseSurface was set from MediaCodec,
2282 // pushing a blank buffer at the end might be necessary.
2283 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2284 if (anw) {
2285 pushBlankBuffersToNativeWindow(anw.get());
2286 }
2287 }
2288
Pawin Vongmasa36653902018-11-15 00:10:25 -08002289 return OK;
2290}
2291
Wonsik Kimab34ed62019-01-31 15:28:46 -08002292PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002293 // Otherwise, component may have stalled work due to input starvation up to
2294 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002295 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2296 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002297 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002298 size_t outputDelay = mOutput.lock()->outputDelay;
2299 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002300 Mutexed<Input>::Locked input(mInput);
2301 n = input->inputDelay + input->pipelineDelay + outputDelay;
2302 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002303 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002304}
2305
Pawin Vongmasa36653902018-11-15 00:10:25 -08002306void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2307 mMetaMode = mode;
2308}
2309
Wonsik Kim596187e2019-10-25 12:44:10 -07002310void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002311 if (mCrypto != nullptr) {
2312 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2313 mCrypto->unsetHeap(entry.second);
2314 }
2315 mHeapSeqNumMap.clear();
2316 if (mHeapSeqNum >= 0) {
2317 mCrypto->unsetHeap(mHeapSeqNum);
2318 mHeapSeqNum = -1;
2319 }
2320 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002321 mCrypto = crypto;
2322}
2323
2324void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2325 mDescrambler = descrambler;
2326}
2327
Pawin Vongmasa36653902018-11-15 00:10:25 -08002328status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2329 // C2_OK is always translated to OK.
2330 if (c2s == C2_OK) {
2331 return OK;
2332 }
2333
2334 // Operation-dependent translation
2335 // TODO: Add as necessary
2336 switch (c2op) {
2337 case C2_OPERATION_Component_start:
2338 switch (c2s) {
2339 case C2_NO_MEMORY:
2340 return NO_MEMORY;
2341 default:
2342 return UNKNOWN_ERROR;
2343 }
2344 default:
2345 break;
2346 }
2347
2348 // Backup operation-agnostic translation
2349 switch (c2s) {
2350 case C2_BAD_INDEX:
2351 return BAD_INDEX;
2352 case C2_BAD_VALUE:
2353 return BAD_VALUE;
2354 case C2_BLOCKING:
2355 return WOULD_BLOCK;
2356 case C2_DUPLICATE:
2357 return ALREADY_EXISTS;
2358 case C2_NO_INIT:
2359 return NO_INIT;
2360 case C2_NO_MEMORY:
2361 return NO_MEMORY;
2362 case C2_NOT_FOUND:
2363 return NAME_NOT_FOUND;
2364 case C2_TIMED_OUT:
2365 return TIMED_OUT;
2366 case C2_BAD_STATE:
2367 case C2_CANCELED:
2368 case C2_CANNOT_DO:
2369 case C2_CORRUPTED:
2370 case C2_OMITTED:
2371 case C2_REFUSED:
2372 return UNKNOWN_ERROR;
2373 default:
2374 return -static_cast<status_t>(c2s);
2375 }
2376}
2377
Pawin Vongmasa36653902018-11-15 00:10:25 -08002378} // namespace android