blob: f8d529efc885a3dda2e17a0cc6ca066ad49746d2 [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 Lindahl2048d492023-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;
Wonsik Kim3722abc2023-05-17 13:26:31 -0700170 output->bounded = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700171 }
David Stevensc3fbb282021-01-18 18:11:20 +0900172 {
173 Mutexed<BlockPools>::Locked pools(mBlockPools);
174 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
175 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800176}
177
178CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800179 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800180 mCrypto->unsetHeap(mHeapSeqNum);
181 }
182}
183
184void CCodecBufferChannel::setComponent(
185 const std::shared_ptr<Codec2Client::Component> &component) {
186 mComponent = component;
187 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
188 mName = mComponentName.c_str();
189}
190
191status_t CCodecBufferChannel::setInputSurface(
192 const std::shared_ptr<InputSurfaceWrapper> &surface) {
193 ALOGV("[%s] setInputSurface", mName);
194 mInputSurface = surface;
195 return mInputSurface->connect(mComponent);
196}
197
198status_t CCodecBufferChannel::signalEndOfInputStream() {
199 if (mInputSurface == nullptr) {
200 return INVALID_OPERATION;
201 }
202 return mInputSurface->signalEndOfInputStream();
203}
204
Sungtak Lee04b30352020-07-27 13:57:25 -0700205status_t CCodecBufferChannel::queueInputBufferInternal(
206 sp<MediaCodecBuffer> buffer,
207 std::shared_ptr<C2LinearBlock> encryptedBlock,
208 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800209 int64_t timeUs;
210 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
211
212 if (mInputMetEos) {
213 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
214 return OK;
215 }
216
217 int32_t flags = 0;
218 int32_t tmp = 0;
219 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200220 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800221 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
222 eos = true;
223 mInputMetEos = true;
224 ALOGV("[%s] input EOS", mName);
225 }
226 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
227 flags |= C2FrameData::FLAG_CODEC_CONFIG;
228 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200229 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
230 tunnelFirstFrame = true;
231 }
Marc Kassis96343b42022-12-09 11:49:44 +0100232 if (buffer->meta()->findInt32("decode-only", &tmp) && tmp) {
233 flags |= C2FrameData::FLAG_DROP_FRAME;
234 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800235 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800236 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800237 std::unique_ptr<C2Work> work(new C2Work);
238 work->input.ordinal.timestamp = timeUs;
239 work->input.ordinal.frameIndex = mFrameIndex++;
240 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
241 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
242 // Keep client timestamp in customOrdinal
243 work->input.ordinal.customOrdinal = timeUs;
244 work->input.buffers.clear();
245
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700246 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800247 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800248
Pawin Vongmasa36653902018-11-15 00:10:25 -0800249 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700250 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800251 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700252 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800253 return -ENOENT;
254 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700255 // TODO: we want to delay copying buffers.
256 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
257 copy = input->buffers->cloneAndReleaseBuffer(buffer);
258 if (copy != nullptr) {
259 (void)input->extraBuffers.assignSlot(copy);
260 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
261 return UNKNOWN_ERROR;
262 }
263 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
264 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
265 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700266 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700267 } else {
268 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
269 "buffer starvation on component.", mName);
270 }
271 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800272 if (input->frameReassembler) {
273 usesFrameReassembler = true;
274 input->frameReassembler.process(buffer, &items);
275 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900276 int32_t cvo = 0;
277 if (buffer->meta()->findInt32("cvo", &cvo)) {
278 int32_t rotation = cvo % 360;
279 // change rotation to counter-clock wise.
280 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
281
282 Mutexed<OutputSurface>::Locked output(mOutputSurface);
283 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
284 output->rotation[frameIndex] = rotation;
285 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800286 work->input.buffers.push_back(c2buffer);
287 if (encryptedBlock) {
288 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
289 kParamIndexEncryptedBuffer,
290 encryptedBlock->share(0, blockSize, C2Fence())));
291 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700292 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800293 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700294 Mutexed<Input>::Locked input(mInput);
295 if (input->frameReassembler) {
296 usesFrameReassembler = true;
297 // drain any pending items with eos
298 input->frameReassembler.process(buffer, &items);
299 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800300 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800301 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800302 if (usesFrameReassembler) {
303 if (!items.empty()) {
304 items.front()->input.configUpdate = std::move(mParamsToBeSet);
305 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
306 }
307 } else {
308 work->input.flags = (C2FrameData::flags_t)flags;
309 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800310
Wonsik Kime1104ca2020-11-24 15:01:33 -0800311 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200312 if (tunnelFirstFrame) {
313 C2StreamTunnelHoldRender::input tunnelHoldRender{
314 0u /* stream */,
315 C2_TRUE /* value */
316 };
317 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
318 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800319 work->worklets.clear();
320 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800321
Wonsik Kime1104ca2020-11-24 15:01:33 -0800322 items.push_back(std::move(work));
323
324 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800325 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800326 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800327 work.reset(new C2Work);
328 work->input.ordinal.timestamp = timeUs;
329 work->input.ordinal.frameIndex = mFrameIndex++;
330 // WORKAROUND: keep client timestamp in customOrdinal
331 work->input.ordinal.customOrdinal = timeUs;
332 work->input.buffers.clear();
333 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800334 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800335 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800336 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800337 c2_status_t err = C2_OK;
338 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700339 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
340 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800341 {
342 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
343 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
344 for (const std::unique_ptr<C2Work> &work : items) {
345 watcher->onWorkQueued(
346 work->input.ordinal.frameIndex.peeku(),
347 std::vector(work->input.buffers),
348 now);
349 }
350 }
351 err = mComponent->queue(&items);
352 }
353 if (err != C2_OK) {
354 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
355 for (const std::unique_ptr<C2Work> &work : items) {
356 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
357 }
358 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700359 Mutexed<Input>::Locked input(mInput);
360 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700361 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700362 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700363 } else if (buffer) {
364 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700365 }
366 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
367 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800368 }
369
370 feedInputBufferIfAvailableInternal();
371 return err;
372}
373
374status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
375 QueueGuard guard(mSync);
376 if (!guard.isRunning()) {
377 ALOGD("[%s] setParameters is only supported in the running state.", mName);
378 return -ENOSYS;
379 }
380 mParamsToBeSet.insert(mParamsToBeSet.end(),
381 std::make_move_iterator(params.begin()),
382 std::make_move_iterator(params.end()));
383 params.clear();
384 return OK;
385}
386
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800387status_t CCodecBufferChannel::attachBuffer(
388 const std::shared_ptr<C2Buffer> &c2Buffer,
389 const sp<MediaCodecBuffer> &buffer) {
390 if (!buffer->copy(c2Buffer)) {
391 return -ENOSYS;
392 }
393 return OK;
394}
395
396void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
397 if (!mDecryptDestination || mDecryptDestination->size() < size) {
398 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
399 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
400 mCrypto->unsetHeap(mHeapSeqNum);
401 }
402 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
403 if (mCrypto) {
404 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
405 }
406 }
407}
408
409int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
410 CHECK(mCrypto);
411 auto it = mHeapSeqNumMap.find(memory);
412 int32_t heapSeqNum = -1;
413 if (it == mHeapSeqNumMap.end()) {
414 heapSeqNum = mCrypto->setHeap(memory);
415 mHeapSeqNumMap.emplace(memory, heapSeqNum);
416 } else {
417 heapSeqNum = it->second;
418 }
419 return heapSeqNum;
420}
421
422status_t CCodecBufferChannel::attachEncryptedBuffer(
423 const sp<hardware::HidlMemory> &memory,
424 bool secure,
425 const uint8_t *key,
426 const uint8_t *iv,
427 CryptoPlugin::Mode mode,
428 CryptoPlugin::Pattern pattern,
429 size_t offset,
430 const CryptoPlugin::SubSample *subSamples,
431 size_t numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000432 const sp<MediaCodecBuffer> &buffer,
433 AString* errorDetailMsg) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800434 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
435 static const C2MemoryUsage kDefaultReadWriteUsage{
436 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
437
438 size_t size = 0;
439 for (size_t i = 0; i < numSubSamples; ++i) {
440 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
441 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700442 if (size == 0) {
443 buffer->setRange(0, 0);
444 return OK;
445 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800446 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
447 std::shared_ptr<C2LinearBlock> block;
448 c2_status_t err = pool->fetchLinearBlock(
449 size,
450 secure ? kSecureUsage : kDefaultReadWriteUsage,
451 &block);
452 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700453 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
454 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800455 return NO_MEMORY;
456 }
457 if (!secure) {
458 ensureDecryptDestination(size);
459 }
460 ssize_t result = -1;
461 ssize_t codecDataOffset = 0;
462 if (mCrypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800463 int32_t heapSeqNum = getHeapSeqNum(memory);
464 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
465 hardware::drm::V1_0::DestinationBuffer dst;
466 if (secure) {
467 dst.type = DrmBufferType::NATIVE_HANDLE;
468 dst.secureMemory = hardware::hidl_handle(block->handle());
469 } else {
470 dst.type = DrmBufferType::SHARED_MEMORY;
471 IMemoryToSharedBuffer(
472 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
473 }
474 result = mCrypto->decrypt(
475 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000476 dst, errorDetailMsg);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800477 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700478 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800479 return result;
480 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800481 } else {
482 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
483 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
484 hidl_vec<SubSample> hidlSubSamples;
485 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
486
487 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
488 hardware::cas::native::V1_0::DestinationBuffer dst;
489 if (secure) {
490 dst.type = BufferType::NATIVE_HANDLE;
491 dst.secureMemory = hardware::hidl_handle(block->handle());
492 } else {
493 dst.type = BufferType::SHARED_MEMORY;
494 dst.nonsecureMemory = src;
495 }
496
497 CasStatus status = CasStatus::OK;
498 hidl_string detailedError;
499 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
500
501 if (key != nullptr) {
502 sctrl = (ScramblingControl)key[0];
503 // Adjust for the PES offset
504 codecDataOffset = key[2] | (key[3] << 8);
505 }
506
507 auto returnVoid = mDescrambler->descramble(
508 sctrl,
509 hidlSubSamples,
510 src,
511 0,
512 dst,
513 0,
514 [&status, &result, &detailedError] (
515 CasStatus _status, uint32_t _bytesWritten,
516 const hidl_string& _detailedError) {
517 status = _status;
518 result = (ssize_t)_bytesWritten;
519 detailedError = _detailedError;
520 });
Arun Johnson634d0802023-02-14 22:07:51 +0000521 if (errorDetailMsg) {
522 errorDetailMsg->setTo(detailedError.c_str(), detailedError.size());
523 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800524 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
525 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
526 mName, returnVoid.description().c_str(), status, result);
527 return UNKNOWN_ERROR;
528 }
529
530 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700531 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
532 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800533 return BAD_VALUE;
534 }
535 }
536 if (!secure) {
537 C2WriteView view = block->map().get();
538 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700539 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
540 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800541 return UNKNOWN_ERROR;
542 }
543 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700544 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
545 "(non-secure)",
546 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800547 return UNKNOWN_ERROR;
548 }
549 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
550 }
551 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
552 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
553 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700554 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800555 return -ENOSYS;
556 }
557 return OK;
558}
559
Pawin Vongmasa36653902018-11-15 00:10:25 -0800560status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
561 QueueGuard guard(mSync);
562 if (!guard.isRunning()) {
563 ALOGD("[%s] No more buffers should be queued at current state.", mName);
564 return -ENOSYS;
565 }
566 return queueInputBufferInternal(buffer);
567}
568
569status_t CCodecBufferChannel::queueSecureInputBuffer(
570 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
571 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
572 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
573 AString *errorDetailMsg) {
574 QueueGuard guard(mSync);
575 if (!guard.isRunning()) {
576 ALOGD("[%s] No more buffers should be queued at current state.", mName);
577 return -ENOSYS;
578 }
579
580 if (!hasCryptoOrDescrambler()) {
581 return -ENOSYS;
582 }
583 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
584
Sungtak Lee04b30352020-07-27 13:57:25 -0700585 std::shared_ptr<C2LinearBlock> block;
586 size_t allocSize = buffer->size();
587 size_t bufferSize = 0;
588 c2_status_t blockRes = C2_OK;
589 bool copied = false;
590 if (mSendEncryptedInfoBuffer) {
591 static const C2MemoryUsage kDefaultReadWriteUsage{
592 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
593 constexpr int kAllocGranule0 = 1024 * 64;
594 constexpr int kAllocGranule1 = 1024 * 1024;
595 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
596 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
597 if (allocSize <= kAllocGranule1) {
598 bufferSize = align(allocSize, kAllocGranule0);
599 } else {
600 bufferSize = align(allocSize, kAllocGranule1);
601 }
602 blockRes = pool->fetchLinearBlock(
603 bufferSize, kDefaultReadWriteUsage, &block);
604
605 if (blockRes == C2_OK) {
606 C2WriteView view = block->map().get();
607 if (view.error() == C2_OK && view.size() == bufferSize) {
608 copied = true;
609 // TODO: only copy clear sections
610 memcpy(view.data(), buffer->data(), allocSize);
611 }
612 }
613 }
614
615 if (!copied) {
616 block.reset();
617 }
618
Pawin Vongmasa36653902018-11-15 00:10:25 -0800619 ssize_t result = -1;
620 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700621 if (numSubSamples == 1
622 && subSamples[0].mNumBytesOfClearData == 0
623 && subSamples[0].mNumBytesOfEncryptedData == 0) {
624 // We don't need to go through crypto or descrambler if the input is empty.
625 result = 0;
626 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700627 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800628 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700629 destination.type = DrmBufferType::NATIVE_HANDLE;
630 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800631 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700632 destination.type = DrmBufferType::SHARED_MEMORY;
633 IMemoryToSharedBuffer(
634 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800635 }
Robert Shih895fba92019-07-16 16:29:44 -0700636 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800637 encryptedBuffer->fillSourceBuffer(&source);
638 result = mCrypto->decrypt(
639 key, iv, mode, pattern, source, buffer->offset(),
640 subSamples, numSubSamples, destination, errorDetailMsg);
641 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700642 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800643 return result;
644 }
Robert Shih895fba92019-07-16 16:29:44 -0700645 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800646 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
647 }
648 } else {
649 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
650 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
651 hidl_vec<SubSample> hidlSubSamples;
652 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
653
654 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
655 encryptedBuffer->fillSourceBuffer(&srcBuffer);
656
657 DestinationBuffer dstBuffer;
658 if (secure) {
659 dstBuffer.type = BufferType::NATIVE_HANDLE;
660 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
661 } else {
662 dstBuffer.type = BufferType::SHARED_MEMORY;
663 dstBuffer.nonsecureMemory = srcBuffer;
664 }
665
666 CasStatus status = CasStatus::OK;
667 hidl_string detailedError;
668 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
669
670 if (key != nullptr) {
671 sctrl = (ScramblingControl)key[0];
672 // Adjust for the PES offset
673 codecDataOffset = key[2] | (key[3] << 8);
674 }
675
676 auto returnVoid = mDescrambler->descramble(
677 sctrl,
678 hidlSubSamples,
679 srcBuffer,
680 0,
681 dstBuffer,
682 0,
683 [&status, &result, &detailedError] (
684 CasStatus _status, uint32_t _bytesWritten,
685 const hidl_string& _detailedError) {
686 status = _status;
687 result = (ssize_t)_bytesWritten;
688 detailedError = _detailedError;
689 });
690
691 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
692 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
693 mName, returnVoid.description().c_str(), status, result);
694 return UNKNOWN_ERROR;
695 }
696
697 if (result < codecDataOffset) {
698 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
699 return BAD_VALUE;
700 }
701
702 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
703
704 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
705 encryptedBuffer->copyDecryptedContentFromMemory(result);
706 }
707 }
708
709 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700710
711 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800712}
713
714void CCodecBufferChannel::feedInputBufferIfAvailable() {
715 QueueGuard guard(mSync);
716 if (!guard.isRunning()) {
717 ALOGV("[%s] We're not running --- no input buffer reported", mName);
718 return;
719 }
720 feedInputBufferIfAvailableInternal();
721}
722
723void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900724 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800725 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700726 }
727 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700728 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700729 if (!output->buffers ||
730 output->buffers->hasPending() ||
Wonsik Kim3722abc2023-05-17 13:26:31 -0700731 (!output->bounded && output->buffers->numActiveSlots() >= output->numSlots)) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800732 return;
733 }
734 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700735 size_t numActiveSlots = 0;
736 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800737 sp<MediaCodecBuffer> inBuffer;
738 size_t index;
739 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700740 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700741 numActiveSlots = input->buffers->numActiveSlots();
742 if (numActiveSlots >= input->numSlots) {
743 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800744 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700745 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800746 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800747 break;
748 }
749 }
750 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
751 mCallback->onInputBufferAvailable(index, inBuffer);
752 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700753 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800754}
755
756status_t CCodecBufferChannel::renderOutputBuffer(
757 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800758 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800760 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800761 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700762 Mutexed<Output>::Locked output(mOutput);
763 if (output->buffers) {
764 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800765 }
766 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800767 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
768 // set to true.
769 sendOutputBuffers();
770 // input buffer feeding may have been gated by pending output buffers
771 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800772 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800773 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700774 std::call_once(mRenderWarningFlag, [this] {
775 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
776 "timestamp or render=true with non-video buffers. Apps should "
777 "call releaseOutputBuffer() with render=false for those.",
778 mName);
779 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800780 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800781 return INVALID_OPERATION;
782 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800783
784#if 0
785 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
786 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
787 for (const std::shared_ptr<const C2Info> &info : infoParams) {
788 AString res;
789 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
790 if (ix) res.append(", ");
791 res.append(*((int32_t*)info.get() + (ix / 4)));
792 }
793 ALOGV(" [%s]", res.c_str());
794 }
795#endif
796 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
797 std::static_pointer_cast<const C2StreamRotationInfo::output>(
798 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
799 bool flip = rotation && (rotation->flip & 1);
800 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900801
802 {
803 Mutexed<OutputSurface>::Locked output(mOutputSurface);
804 if (output->surface == nullptr) {
805 ALOGI("[%s] cannot render buffer without surface", mName);
806 return OK;
807 }
808 int64_t frameIndex;
809 buffer->meta()->findInt64("frameIndex", &frameIndex);
810 if (output->rotation.count(frameIndex) != 0) {
811 auto it = output->rotation.find(frameIndex);
812 quarters = (it->second / 90) & 3;
813 output->rotation.erase(it);
814 }
815 }
816
Pawin Vongmasa36653902018-11-15 00:10:25 -0800817 uint32_t transform = 0;
818 switch (quarters) {
819 case 0: // no rotation
820 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
821 break;
822 case 1: // 90 degrees counter-clockwise
823 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
824 : HAL_TRANSFORM_ROT_270;
825 break;
826 case 2: // 180 degrees
827 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
828 break;
829 case 3: // 90 degrees clockwise
830 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
831 : HAL_TRANSFORM_ROT_90;
832 break;
833 }
834
835 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
836 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
837 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
838 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
839 if (surfaceScaling) {
840 videoScalingMode = surfaceScaling->value;
841 }
842
843 // Use dataspace from format as it has the default aspects already applied
844 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
845 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
846
847 // HDR static info
848 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
849 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
850 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
851
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800852 // HDR10 plus info
853 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
854 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
855 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800856 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
857 hdr10PlusInfo.reset();
858 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800859
Wonsik Kima79c5522022-01-18 16:29:24 -0800860 // HDR dynamic info
861 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
862 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
863 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
864 // TODO: make this sticky & enable unset
865 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
866 hdrDynamicInfo.reset();
867 }
868
869 if (hdr10PlusInfo) {
870 // C2StreamHdr10PlusInfo is deprecated; components should use
871 // C2StreamHdrDynamicMetadataInfo
872 // TODO: #metric
873 if (hdrDynamicInfo) {
874 // It is unexpected that C2StreamHdr10PlusInfo and
875 // C2StreamHdrDynamicMetadataInfo is both present.
876 // C2StreamHdrDynamicMetadataInfo takes priority.
877 // TODO: #metric
878 } else {
879 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
880 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
881 hdr10PlusInfo->flexCount(),
882 0u,
883 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
884 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
885 hdrDynamicInfo = info;
886 }
887 }
888
Pawin Vongmasa36653902018-11-15 00:10:25 -0800889 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
890 if (blocks.size() != 1u) {
891 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
892 return UNKNOWN_ERROR;
893 }
894 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700895 C2Fence c2fence = block.fence();
896 sp<Fence> fence = Fence::NO_FENCE;
897 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
898 // Once C2Fence::type() is added, check the exact C2Fence type
899 if (c2fence.isHW()) {
900 int fenceFd = c2fence.fd();
901 fence = sp<Fence>::make(fenceFd);
902 if (!fence) {
903 ALOGE("[%s] Failed to allocate a fence", mName);
904 close(fenceFd);
905 return NO_MEMORY;
906 }
907 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800908
909 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -0700910 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800911 timestampNs,
912 false, // droppable
913 dataSpace,
914 Rect(blocks.front().crop().left,
915 blocks.front().crop().top,
916 blocks.front().crop().right(),
917 blocks.front().crop().bottom()),
918 videoScalingMode,
919 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700920 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800921 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800922 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800923 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800924 // If mastering max and min luminance fields are 0, do not use them.
925 // It indicates the value may not be present in the stream.
926 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
927 hdrStaticInfo->mastering.minLuminance > 0.0f) {
928 struct android_smpte2086_metadata smpte2086_meta = {
929 .displayPrimaryRed = {
930 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
931 },
932 .displayPrimaryGreen = {
933 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
934 },
935 .displayPrimaryBlue = {
936 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
937 },
938 .whitePoint = {
939 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
940 },
941 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
942 .minLuminance = hdrStaticInfo->mastering.minLuminance,
943 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800944 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800945 hdr.smpte2086 = smpte2086_meta;
946 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700947 // If the content light level fields are 0, do not use them, it
948 // indicates the value may not be present in the stream.
949 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
950 struct android_cta861_3_metadata cta861_meta = {
951 .maxContentLightLevel = hdrStaticInfo->maxCll,
952 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
953 };
954 hdr.validTypes |= HdrMetadata::CTA861_3;
955 hdr.cta8613 = cta861_meta;
956 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900957
958 // does not have valid info
959 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
960 hdrStaticInfo.reset();
961 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800962 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800963 if (hdrDynamicInfo
964 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800965 hdr.validTypes |= HdrMetadata::HDR10PLUS;
966 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800967 hdrDynamicInfo->m.data,
968 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800969 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800970 qbi.setHdrMetadata(hdr);
971 }
Hongguangfc1478a2022-07-20 22:56:06 -0700972 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
973
Brian Lindahl932bf602023-03-09 11:59:48 -0700974 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
975 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
976 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800977 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
978 if (result != OK) {
979 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800980 if (result == NO_INIT) {
981 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
982 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800983 return result;
984 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800985
986 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
987 ALOGD("[%s] queue buffer successful", mName);
988 } else {
989 ALOGV("[%s] queue buffer successful", mName);
990 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800991
992 int64_t mediaTimeUs = 0;
993 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahl2048d492023-04-05 08:49:23 -0600994 if (mIsSurfaceToDisplay) {
995 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
996 processRenderedFrames(qbo.frameTimestamps);
997 } else {
998 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
999 // when the frame is queued to the non-display surface
1000 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1001 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001002
1003 return OK;
1004}
1005
Brian Lindahl932bf602023-03-09 11:59:48 -07001006void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001007 mTrackedFrames.clear();
1008
1009 int isSurfaceToDisplay = 0;
1010 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1011 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1012 // No frame tracking is needed if we're not sending frames to the display
1013 if (!mIsSurfaceToDisplay) {
1014 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1015 return;
1016 }
1017
Brian Lindahl932bf602023-03-09 11:59:48 -07001018 int hasPresentFenceTimes = 0;
1019 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1020 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
1021 if (mHasPresentFenceTimes) {
1022 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1023 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001024}
1025
1026void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1027 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1028 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1029 // so track the frame as if the desired render time is now.
1030 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1031 if (desiredRenderTimeNs < nowNs) {
1032 desiredRenderTimeNs = nowNs;
1033 }
1034 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1035 // actually rendered.
1036 TrackedFrame frame;
1037 frame.number = qbo.nextFrameNumber - 1;
1038 frame.mediaTimeUs = mediaTimeUs;
1039 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1040 frame.latchTime = -1;
1041 frame.presentFence = nullptr;
1042 mTrackedFrames.push_back(frame);
1043}
1044
1045void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1046 // Grab the latch times and present fences from the frame event deltas
1047 for (const auto& delta : deltas) {
1048 for (auto& frame : mTrackedFrames) {
1049 if (delta.getFrameNumber() == frame.number) {
1050 delta.getLatchTime(&frame.latchTime);
1051 delta.getDisplayPresentFence(&frame.presentFence);
1052 }
1053 }
1054 }
1055
1056 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1057 // in fact, been rendered.
1058 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1059 while (!mTrackedFrames.empty()) {
1060 TrackedFrame & frame = mTrackedFrames.front();
1061 // Frames that should have been rendered at least 100ms in the past are checked
1062 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1063 break;
1064 }
1065
1066 // If we don't have a render time by now, then consider the frame as dropped
1067 int64_t renderTimeNs = getRenderTimeNs(frame);
1068 if (renderTimeNs != -1) {
1069 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1070 }
1071 mTrackedFrames.pop_front();
1072 }
1073}
1074
1075int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1076 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1077 if (!mHasPresentFenceTimes) {
1078 if (frame.latchTime == -1) {
1079 ALOGD("no latch time for frame %d", (int) frame.number);
1080 return -1;
1081 }
1082 return frame.latchTime;
1083 }
1084
1085 if (frame.presentFence == nullptr) {
1086 ALOGW("no present fence for frame %d", (int) frame.number);
1087 return -1;
1088 }
1089
1090 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1091
1092 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1093 ALOGW("invalid signal time for frame %d", (int) frame.number);
1094 return -1;
1095 }
1096
1097 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1098 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1099 return -1;
1100 }
1101
1102 return actualRenderTimeNs;
1103}
1104
1105void CCodecBufferChannel::pollForRenderedBuffers() {
1106 FrameEventHistoryDelta delta;
1107 mComponent->pollForRenderedFrames(&delta);
1108 processRenderedFrames(delta);
1109}
1110
Pawin Vongmasa36653902018-11-15 00:10:25 -08001111status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1112 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1113 bool released = false;
1114 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001115 Mutexed<Input>::Locked input(mInput);
1116 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001117 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001118 }
1119 }
1120 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001121 Mutexed<Output>::Locked output(mOutput);
1122 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001123 released = true;
1124 }
1125 }
1126 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001127 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001128 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001129 } else {
1130 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1131 }
1132 return OK;
1133}
1134
1135void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1136 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001137 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001138
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001139 if (!input->buffers) {
1140 ALOGE("getInputBufferArray: No Input Buffers allocated");
1141 return;
1142 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001143 if (!input->buffers->isArrayMode()) {
1144 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001145 }
1146
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001147 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001148}
1149
1150void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1151 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001152 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001153 if (!output->buffers) {
1154 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1155 return;
1156 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001157 if (!output->buffers->isArrayMode()) {
1158 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001159 }
1160
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001161 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001162}
1163
1164status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001165 const sp<AMessage> &inputFormat,
1166 const sp<AMessage> &outputFormat,
1167 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001168 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1169 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001170 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001171 C2PortReorderBufferDepthTuning::output reorderDepth;
1172 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001173 C2PortActualDelayTuning::input inputDelay(0);
1174 C2PortActualDelayTuning::output outputDelay(0);
1175 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001176 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001177
Pawin Vongmasa36653902018-11-15 00:10:25 -08001178 c2_status_t err = mComponent->query(
1179 {
1180 &iStreamFormat,
1181 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001182 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001183 &reorderDepth,
1184 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001185 &inputDelay,
1186 &pipelineDelay,
1187 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001188 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001189 },
1190 {},
1191 C2_DONT_BLOCK,
1192 nullptr);
1193 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001194 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001195 return UNKNOWN_ERROR;
1196 }
1197 } else if (err != C2_OK) {
1198 return UNKNOWN_ERROR;
1199 }
1200
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001201 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1202 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1203 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1204
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001205 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1206 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001207
Pawin Vongmasa36653902018-11-15 00:10:25 -08001208 // TODO: get this from input format
1209 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1210
Sungtak Lee04b30352020-07-27 13:57:25 -07001211 // secure mode is a static parameter (shall not change in the executing state)
1212 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1213
Pawin Vongmasa36653902018-11-15 00:10:25 -08001214 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001215 int poolMask = GetCodec2PoolMask();
1216 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001217
1218 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001219 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001220 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001221 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1222 API_REFLECTION |
1223 API_VALUES |
1224 API_CURRENT_VALUES |
1225 API_DEPENDENCY |
1226 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001227 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1228 C2StreamSampleRateInfo::input sampleRate(0u);
1229 C2StreamChannelCountInfo::input channelCount(0u);
1230 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001231 std::shared_ptr<C2BlockPool> pool;
1232 {
1233 Mutexed<BlockPools>::Locked pools(mBlockPools);
1234
1235 // set default allocator ID.
1236 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001237 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001238
1239 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1240 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1241 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001242 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001243 std::vector<C2Param *> stackParams({&featuresSetting});
1244 if (audioEncoder) {
1245 stackParams.push_back(&encoderFrameSize);
1246 stackParams.push_back(&sampleRate);
1247 stackParams.push_back(&channelCount);
1248 stackParams.push_back(&pcmEncoding);
1249 } else {
1250 encoderFrameSize.invalidate();
1251 sampleRate.invalidate();
1252 channelCount.invalidate();
1253 pcmEncoding.invalidate();
1254 }
1255 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001256 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1257 C2_DONT_BLOCK,
1258 &params);
1259 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1260 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1261 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001262 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001263 C2PortAllocatorsTuning::input *inputAllocators =
1264 C2PortAllocatorsTuning::input::From(params[0].get());
1265 if (inputAllocators && inputAllocators->flexCount() > 0) {
1266 std::shared_ptr<C2Allocator> allocator;
1267 // verify allocator IDs and resolve default allocator
1268 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1269 if (allocator) {
1270 pools->inputAllocatorId = allocator->getId();
1271 } else {
1272 ALOGD("[%s] component requested invalid input allocator ID %u",
1273 mName, inputAllocators->m.values[0]);
1274 }
1275 }
1276 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001277 if (featuresSetting) {
1278 apiFeatures = featuresSetting.value;
1279 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001280
1281 // TODO: use C2Component wrapper to associate this pool with ourselves
1282 if ((poolMask >> pools->inputAllocatorId) & 1) {
1283 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1284 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1285 mName, pools->inputAllocatorId,
1286 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1287 asString(err), err);
1288 } else {
1289 err = C2_NOT_FOUND;
1290 }
1291 if (err != C2_OK) {
1292 C2BlockPool::local_id_t inputPoolId =
1293 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1294 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1295 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1296 mName, (unsigned long long)inputPoolId,
1297 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1298 asString(err), err);
1299 if (err != C2_OK) {
1300 return NO_MEMORY;
1301 }
1302 }
1303 pools->inputPool = pool;
1304 }
1305
Wonsik Kim51051262018-11-28 13:59:05 -08001306 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001307 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001308 input->inputDelay = inputDelayValue;
1309 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001310 input->numSlots = numInputSlots;
1311 input->extraBuffers.flush();
1312 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001313 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001314 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1315 input->frameReassembler.init(
1316 pool,
1317 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1318 encoderFrameSize.value,
1319 sampleRate.value,
1320 channelCount.value,
1321 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1322 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001323 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1324 // For encrypted content, framework decrypts source buffer (ashmem) into
1325 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001326 if (!buffersBoundToCodec
1327 && !input->frameReassembler
1328 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001329 input->buffers.reset(new SlotInputBuffers(mName));
1330 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001331 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001332 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001333 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001334 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001335 // This is to ensure buffers do not get released prematurely.
1336 // TODO: handle this without going into array mode
1337 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001338 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001339 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001340 }
1341 } else {
1342 if (hasCryptoOrDescrambler()) {
1343 int32_t capacity = kLinearBufferSize;
1344 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1345 if ((size_t)capacity > kMaxLinearBufferSize) {
1346 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1347 capacity = kMaxLinearBufferSize;
1348 }
1349 if (mDealer == nullptr) {
1350 mDealer = new MemoryDealer(
1351 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001352 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001353 "EncryptedLinearInputBuffers");
1354 mDecryptDestination = mDealer->allocate((size_t)capacity);
1355 }
1356 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001357 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1358 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001359 } else {
1360 mHeapSeqNum = -1;
1361 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001362 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001363 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001364 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001365 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001366 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001367 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001368 }
1369 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001370 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001371
1372 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001373 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001374 } else {
1375 // TODO: error
1376 }
Wonsik Kim51051262018-11-28 13:59:05 -08001377
1378 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001379 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001380 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001381 }
1382
1383 if (outputFormat != nullptr) {
1384 sp<IGraphicBufferProducer> outputSurface;
1385 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001386 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001387 {
1388 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001389 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001390 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001391 outputSurface = output->surface ?
1392 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001393 if (outputSurface) {
1394 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1395 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001396 outputGeneration = output->generation;
1397 }
1398
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001399 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001400 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001401 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001402
1403 {
1404 Mutexed<BlockPools>::Locked pools(mBlockPools);
1405
David Stevensc3fbb282021-01-18 18:11:20 +09001406 prevOutputPoolId = pools->outputPoolId;
1407
Pawin Vongmasa36653902018-11-15 00:10:25 -08001408 // set default allocator ID.
1409 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001410 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001411
1412 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1413 // unsuccessful.
1414 std::vector<std::unique_ptr<C2Param>> params;
1415 err = mComponent->query({ },
1416 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1417 C2_DONT_BLOCK,
1418 &params);
1419 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1420 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1421 mName, params.size(), asString(err), err);
1422 } else if (err == C2_OK && params.size() == 1) {
1423 C2PortAllocatorsTuning::output *outputAllocators =
1424 C2PortAllocatorsTuning::output::From(params[0].get());
1425 if (outputAllocators && outputAllocators->flexCount() > 0) {
1426 std::shared_ptr<C2Allocator> allocator;
1427 // verify allocator IDs and resolve default allocator
1428 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1429 if (allocator) {
1430 pools->outputAllocatorId = allocator->getId();
1431 } else {
1432 ALOGD("[%s] component requested invalid output allocator ID %u",
1433 mName, outputAllocators->m.values[0]);
1434 }
1435 }
1436 }
1437
1438 // use bufferqueue if outputting to a surface.
1439 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1440 // if unsuccessful.
1441 if (outputSurface) {
1442 params.clear();
1443 err = mComponent->query({ },
1444 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1445 C2_DONT_BLOCK,
1446 &params);
1447 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1448 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1449 mName, params.size(), asString(err), err);
1450 } else if (err == C2_OK && params.size() == 1) {
1451 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1452 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1453 if (surfaceAllocator) {
1454 std::shared_ptr<C2Allocator> allocator;
1455 // verify allocator IDs and resolve default allocator
1456 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1457 if (allocator) {
1458 pools->outputAllocatorId = allocator->getId();
1459 } else {
1460 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1461 mName, surfaceAllocator->value);
1462 err = C2_BAD_VALUE;
1463 }
1464 }
1465 }
1466 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1467 && err != C2_OK
1468 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1469 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1470 }
1471 }
1472
1473 if ((poolMask >> pools->outputAllocatorId) & 1) {
1474 err = mComponent->createBlockPool(
1475 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1476 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1477 mName, pools->outputAllocatorId,
1478 (unsigned long long)pools->outputPoolId,
1479 asString(err));
1480 } else {
1481 err = C2_NOT_FOUND;
1482 }
1483 if (err != C2_OK) {
1484 // use basic pool instead
1485 pools->outputPoolId =
1486 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1487 }
1488
1489 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1490 // component.
1491 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1492 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1493
1494 std::vector<std::unique_ptr<C2SettingResult>> failures;
1495 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1496 ALOGD("[%s] Configured output block pool ids %llu => %s",
1497 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1498 outputPoolId_ = pools->outputPoolId;
1499 }
1500
David Stevensc3fbb282021-01-18 18:11:20 +09001501 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1502 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1503 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1504 if (err != C2_OK) {
1505 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1506 (unsigned long long) prevOutputPoolId, asString(err), err);
1507 }
1508 }
1509
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001510 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001511 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001512 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001513 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001514 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001515 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001516 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001517 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001518 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001519 }
1520 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001521 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001522 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001523 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001524
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001525 output->buffers->clearStash();
1526 if (reorderDepth) {
1527 output->buffers->setReorderDepth(reorderDepth.value);
1528 }
1529 if (reorderKey) {
1530 output->buffers->setReorderKey(reorderKey.value);
1531 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001532
1533 // Try to set output surface to created block pool if given.
1534 if (outputSurface) {
1535 mComponent->setOutputSurface(
1536 outputPoolId_,
1537 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001538 outputGeneration,
1539 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001540 } else {
1541 // configure CPU read consumer usage
1542 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1543 std::vector<std::unique_ptr<C2SettingResult>> failures;
1544 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1545 // do not print error message for now as most components may not yet
1546 // support this setting
1547 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1548 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001549 }
1550
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001551 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001552 if (buffersBoundToCodec) {
1553 // WORKAROUND: if we're using early CSD workaround we convert to
1554 // array mode, to appease apps assuming the output
1555 // buffers to be of the same size.
1556 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1557 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001558
1559 int32_t channelCount;
1560 int32_t sampleRate;
1561 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1562 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1563 int32_t delay = 0;
1564 int32_t padding = 0;;
1565 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1566 delay = 0;
1567 }
1568 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1569 padding = 0;
1570 }
1571 if (delay || padding) {
1572 // We need write access to the buffers, and we're already in
1573 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001574 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001575 }
1576 }
1577 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001578
1579 int32_t tunneled = 0;
1580 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1581 tunneled = 0;
1582 }
1583 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001584 }
1585
1586 // Set up pipeline control. This has to be done after mInputBuffers and
1587 // mOutputBuffers are initialized to make sure that lingering callbacks
1588 // about buffers from the previous generation do not interfere with the
1589 // newly initialized pipeline capacity.
1590
Wonsik Kim62545252021-01-20 11:25:41 -08001591 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001592 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001593 watcher->inputDelay(inputDelayValue)
1594 .pipelineDelay(pipelineDelayValue)
1595 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001596 .smoothnessFactor(kSmoothnessFactor);
1597 watcher->flush();
1598 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001599
1600 mInputMetEos = false;
1601 mSync.start();
1602 return OK;
1603}
1604
Wonsik Kim34b28b42022-05-20 15:49:32 -07001605status_t CCodecBufferChannel::prepareInitialInputBuffers(
1606 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001607 if (mInputSurface) {
1608 return OK;
1609 }
1610
Wonsik Kim34b28b42022-05-20 15:49:32 -07001611 size_t numInputSlots = mInput.lock()->numSlots;
1612
1613 {
1614 Mutexed<Input>::Locked input(mInput);
1615 while (clientInputBuffers->size() < numInputSlots) {
1616 size_t index;
1617 sp<MediaCodecBuffer> buffer;
1618 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1619 break;
1620 }
1621 clientInputBuffers->emplace(index, buffer);
1622 }
1623 }
1624 if (clientInputBuffers->empty()) {
1625 ALOGW("[%s] start: cannot allocate memory at all", mName);
1626 return NO_MEMORY;
1627 } else if (clientInputBuffers->size() < numInputSlots) {
1628 ALOGD("[%s] start: cannot allocate memory for all slots, "
1629 "only %zu buffers allocated",
1630 mName, clientInputBuffers->size());
1631 } else {
1632 ALOGV("[%s] %zu initial input buffers available",
1633 mName, clientInputBuffers->size());
1634 }
1635 return OK;
1636}
1637
1638status_t CCodecBufferChannel::requestInitialInputBuffers(
1639 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001640 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001641 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1642 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1643 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001644 return UNKNOWN_ERROR;
1645 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001646
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001647 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1648 mFlushedConfigs.lock()->swap(flushedConfigs);
1649 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001650 {
1651 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1652 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1653 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1654 watcher->onWorkQueued(
1655 work->input.ordinal.frameIndex.peeku(),
1656 std::vector(work->input.buffers),
1657 now);
1658 }
1659 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001660 err = mComponent->queue(&flushedConfigs);
1661 if (err != C2_OK) {
1662 ALOGW("[%s] Error while queueing a flushed config", mName);
1663 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001664 }
1665 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001666 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001667 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1668 !clientInputBuffers.empty()) {
1669 size_t minIndex = clientInputBuffers.begin()->first;
1670 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1671 for (const auto &[index, buffer] : clientInputBuffers) {
1672 if (minBuffer->capacity() > buffer->capacity()) {
1673 minIndex = index;
1674 minBuffer = buffer;
1675 }
1676 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001677 // WORKAROUND: Some apps expect CSD available without queueing
1678 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001679 minBuffer->setRange(0, 0);
1680 minBuffer->meta()->clear();
1681 minBuffer->meta()->setInt64("timeUs", 0);
1682 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001683 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1684 mName);
1685 return UNKNOWN_ERROR;
1686 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001687 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001688 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001689
Wonsik Kim34b28b42022-05-20 15:49:32 -07001690 for (const auto &[index, buffer] : clientInputBuffers) {
1691 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001692 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001693
Pawin Vongmasa36653902018-11-15 00:10:25 -08001694 return OK;
1695}
1696
1697void CCodecBufferChannel::stop() {
1698 mSync.stop();
1699 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001700}
1701
Sungtak Lee99144332023-01-26 11:03:14 +00001702void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
1703 sp<Surface> surface = mOutputSurface.lock()->surface;
1704 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00001705 C2BlockPool::local_id_t outputPoolId;
1706 {
1707 Mutexed<BlockPools>::Locked pools(mBlockPools);
1708 outputPoolId = pools->outputPoolId;
1709 }
1710 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00001711
1712 if (pushBlankBuffer) {
1713 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
1714 if (anw) {
1715 pushBlankBuffersToNativeWindow(anw.get());
1716 }
1717 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00001718 }
1719}
1720
Wonsik Kim936a89c2020-05-08 16:07:50 -07001721void CCodecBufferChannel::reset() {
1722 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001723 if (mInputSurface != nullptr) {
1724 mInputSurface.reset();
1725 }
1726 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001727 {
1728 Mutexed<Input>::Locked input(mInput);
1729 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001730 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001731 }
1732 {
1733 Mutexed<Output>::Locked output(mOutput);
1734 output->buffers.reset();
1735 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001736 // reset the frames that are being tracked for onFrameRendered callbacks
1737 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001738}
1739
1740void CCodecBufferChannel::release() {
1741 mComponent.reset();
1742 mInputAllocator.reset();
1743 mOutputSurface.lock()->surface.clear();
1744 {
1745 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1746 blockPools->inputPool.reset();
1747 blockPools->outputPoolIntf.reset();
1748 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001749 setCrypto(nullptr);
1750 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001751}
1752
Pawin Vongmasa36653902018-11-15 00:10:25 -08001753void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1754 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001755 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001756 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001757 {
1758 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1759 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1760 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1761 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1762 watcher->onWorkDone(frameIndex);
1763 continue;
1764 }
1765 if (work->input.buffers.empty()
1766 || work->input.buffers.front() == nullptr
1767 || work->input.buffers.front()->data().linearBlocks().empty()) {
1768 ALOGD("[%s] no linear codec config data found", mName);
1769 watcher->onWorkDone(frameIndex);
1770 continue;
1771 }
1772 std::unique_ptr<C2Work> copy(new C2Work);
1773 copy->input.flags = C2FrameData::flags_t(
1774 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1775 copy->input.ordinal = work->input.ordinal;
1776 copy->input.ordinal.frameIndex = mFrameIndex++;
1777 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1778 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1779 }
1780 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1781 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1782 }
1783 copy->input.infoBuffers.insert(
1784 copy->input.infoBuffers.begin(),
1785 work->input.infoBuffers.begin(),
1786 work->input.infoBuffers.end());
1787 copy->worklets.emplace_back(new C2Worklet);
1788 configs.push_back(std::move(copy));
1789 watcher->onWorkDone(frameIndex);
1790 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001791 }
1792 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001793 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001794 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001795 Mutexed<Input>::Locked input(mInput);
1796 input->buffers->flush();
1797 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001798 }
1799 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001800 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001801 if (output->buffers) {
1802 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001803 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001804 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001805 }
1806}
1807
1808void CCodecBufferChannel::onWorkDone(
1809 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001810 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001811 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001812 feedInputBufferIfAvailable();
1813 }
1814}
1815
1816void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001817 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001818 if (mInputSurface) {
1819 return;
1820 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001821 std::shared_ptr<C2Buffer> buffer =
1822 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001823 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001824 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001825 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001826 if (input->lastFlushIndex >= frameIndex) {
1827 ALOGD("[%s] Ignoring stale input buffer done callback: "
1828 "last flush index = %lld, frameIndex = %lld",
1829 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1830 } else {
1831 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1832 if (!newInputSlotAvailable) {
1833 (void)input->extraBuffers.expireComponentBuffer(buffer);
1834 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001835 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001836 }
1837 if (newInputSlotAvailable) {
1838 feedInputBufferIfAvailable();
1839 }
1840}
1841
1842bool CCodecBufferChannel::handleWork(
1843 std::unique_ptr<C2Work> work,
1844 const sp<AMessage> &outputFormat,
1845 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001846 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001847 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001848 if (!output->buffers) {
1849 return false;
1850 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001851 }
1852
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001853 // Whether the output buffer should be reported to the client or not.
1854 bool notifyClient = false;
1855
1856 if (work->result == C2_OK){
1857 notifyClient = true;
1858 } else if (work->result == C2_NOT_FOUND) {
1859 ALOGD("[%s] flushed work; ignored.", mName);
1860 } else {
1861 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1862 // the config update.
1863 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1864 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1865 return false;
1866 }
1867
1868 if ((work->input.ordinal.frameIndex -
1869 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001870 // Discard frames from previous generation.
1871 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001872 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001873 }
1874
Wonsik Kim524b0582019-03-12 11:28:57 -07001875 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001876 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001877 || !(work->worklets.front()->output.flags &
1878 C2FrameData::FLAG_INCOMPLETE))) {
1879 mPipelineWatcher.lock()->onWorkDone(
1880 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001881 }
1882
1883 // NOTE: MediaCodec usage supposedly have only one worklet
1884 if (work->worklets.size() != 1u) {
1885 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1886 mName, work->worklets.size());
1887 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1888 return false;
1889 }
1890
1891 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1892
1893 std::shared_ptr<C2Buffer> buffer;
1894 // NOTE: MediaCodec usage supposedly have only one output stream.
1895 if (worklet->output.buffers.size() > 1u) {
1896 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1897 mName, worklet->output.buffers.size());
1898 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1899 return false;
1900 } else if (worklet->output.buffers.size() == 1u) {
1901 buffer = worklet->output.buffers[0];
1902 if (!buffer) {
1903 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1904 }
1905 }
1906
Wonsik Kim3dedf682021-05-03 10:57:09 -07001907 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1908 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001909 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001910 while (!worklet->output.configUpdate.empty()) {
1911 std::unique_ptr<C2Param> param;
1912 worklet->output.configUpdate.back().swap(param);
1913 worklet->output.configUpdate.pop_back();
1914 switch (param->coreIndex().coreIndex()) {
1915 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1916 C2PortReorderBufferDepthTuning::output reorderDepth;
1917 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001918 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1919 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001920 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001921 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001922 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001923 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1924 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001925 }
1926 break;
1927 }
1928 case C2PortReorderKeySetting::CORE_INDEX: {
1929 C2PortReorderKeySetting::output reorderKey;
1930 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001931 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001932 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1933 mName, reorderKey.value);
1934 } else {
1935 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1936 }
1937 break;
1938 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001939 case C2PortActualDelayTuning::CORE_INDEX: {
1940 if (param->isGlobal()) {
1941 C2ActualPipelineDelayTuning pipelineDelay;
1942 if (pipelineDelay.updateFrom(*param)) {
1943 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1944 mName, pipelineDelay.value);
1945 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001946 (void)mPipelineWatcher.lock()->pipelineDelay(
1947 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001948 }
1949 }
1950 if (param->forInput()) {
1951 C2PortActualDelayTuning::input inputDelay;
1952 if (inputDelay.updateFrom(*param)) {
1953 ALOGV("[%s] onWorkDone: updating input delay %u",
1954 mName, inputDelay.value);
1955 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001956 (void)mPipelineWatcher.lock()->inputDelay(
1957 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001958 }
1959 }
1960 if (param->forOutput()) {
1961 C2PortActualDelayTuning::output outputDelay;
1962 if (outputDelay.updateFrom(*param)) {
1963 ALOGV("[%s] onWorkDone: updating output delay %u",
1964 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001965 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001966 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001967 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001968
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001969 }
1970 }
1971 break;
1972 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001973 case C2PortTunnelSystemTime::CORE_INDEX: {
1974 C2PortTunnelSystemTime::output frameRenderTime;
1975 if (frameRenderTime.updateFrom(*param)) {
1976 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1977 mName, (long long)frameRenderTime.value,
1978 (long long)worklet->output.ordinal.timestamp.peekll());
1979 mCCodecCallback->onOutputFramesRendered(
1980 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1981 }
1982 break;
1983 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001984 case C2StreamTunnelHoldRender::CORE_INDEX: {
1985 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1986 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1987 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1988 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1989 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1990 mCCodecCallback->onFirstTunnelFrameReady();
1991 break;
1992 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001993 default:
1994 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1995 mName, param->index());
1996 break;
1997 }
1998 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001999 if (newInputDelay || newPipelineDelay) {
2000 Mutexed<Input>::Locked input(mInput);
2001 size_t newNumSlots =
2002 newInputDelay.value_or(input->inputDelay) +
2003 newPipelineDelay.value_or(input->pipelineDelay) +
2004 kSmoothnessFactor;
2005 if (input->buffers->isArrayMode()) {
2006 if (input->numSlots >= newNumSlots) {
2007 input->numExtraSlots = 0;
2008 } else {
2009 input->numExtraSlots = newNumSlots - input->numSlots;
2010 }
2011 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2012 mName, input->numExtraSlots);
2013 } else {
2014 input->numSlots = newNumSlots;
2015 }
2016 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002017 size_t numOutputSlots = 0;
2018 uint32_t reorderDepth = 0;
2019 bool outputBuffersChanged = false;
2020 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2021 Mutexed<Output>::Locked output(mOutput);
2022 if (!output->buffers) {
2023 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002024 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002025 numOutputSlots = output->numSlots;
2026 if (newReorderKey) {
2027 output->buffers->setReorderKey(newReorderKey.value());
2028 }
2029 if (newReorderDepth) {
2030 output->buffers->setReorderDepth(newReorderDepth.value());
2031 }
2032 reorderDepth = output->buffers->getReorderDepth();
2033 if (newOutputDelay) {
2034 output->outputDelay = newOutputDelay.value();
2035 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2036 if (output->numSlots < numOutputSlots) {
2037 output->numSlots = numOutputSlots;
2038 if (output->buffers->isArrayMode()) {
2039 OutputBuffersArray *array =
2040 (OutputBuffersArray *)output->buffers.get();
2041 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2042 mName, numOutputSlots);
2043 array->grow(numOutputSlots);
2044 outputBuffersChanged = true;
2045 }
2046 }
2047 }
2048 numOutputSlots = output->numSlots;
2049 }
2050 if (outputBuffersChanged) {
2051 mCCodecCallback->onOutputBuffersChanged();
2052 }
2053 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002054 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002055 {
2056 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2057 maxDequeueCount = output->maxDequeueBuffers =
2058 numOutputSlots + reorderDepth + kRenderingDepth;
2059 if (output->surface) {
2060 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2061 }
2062 }
2063 if (maxDequeueCount > 0) {
2064 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002065 }
2066 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002067
Pawin Vongmasa36653902018-11-15 00:10:25 -08002068 int32_t flags = 0;
2069 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002070 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002071 ALOGV("[%s] onWorkDone: output EOS", mName);
2072 }
2073
Pawin Vongmasa36653902018-11-15 00:10:25 -08002074 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2075 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2076 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2077 // shall correspond to the client input timesamp (in customOrdinal). By using the
2078 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2079 // produces multiple output.
2080 c2_cntr64_t timestamp =
2081 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2082 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002083 if (mInputSurface != nullptr) {
2084 // When using input surface we need to restore the original input timestamp.
2085 timestamp = work->input.ordinal.customOrdinal;
2086 }
My Name6bd9a7d2022-03-25 12:37:58 -07002087 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2088 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002089 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2090 mName,
2091 work->input.ordinal.customOrdinal.peekll(),
2092 work->input.ordinal.timestamp.peekll(),
2093 worklet->output.ordinal.timestamp.peekll(),
2094 timestamp.peekll());
2095
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002096 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002097 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002098 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002099 if (!output->buffers) {
2100 return false;
2101 }
2102 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002103 output->buffers->updateSkipCutBuffer(outputFormat);
2104 output->buffers->setFormat(outputFormat);
2105 }
2106 if (!notifyClient) {
2107 return false;
2108 }
2109 size_t index;
2110 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002111 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002112 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002113 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002114 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2115
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002116 // TRICKY: we want popped buffers reported in order, so sending
2117 // the callback while holding the lock here. This assumes that
2118 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2119 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002120 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002121 } else {
2122 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002123 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002124 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002125 return false;
2126 }
2127 }
2128
Wonsik Kimec585c32021-10-01 01:11:00 -07002129 bool drop = false;
2130 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2131 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2132 drop = true;
2133 }
2134
Marc Kassisec910342022-11-25 11:43:05 +01002135 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2136 // HAL, the flag is then removed in the corresponding output buffer.
2137 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2138 flags |= BUFFER_FLAG_DECODE_ONLY;
2139 }
2140
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002141 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002142 if (mTunneled && drop && outputFormat) {
2143 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2144 mName, work->input.ordinal.frameIndex.peekull());
2145 } else {
2146 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2147 mName, work->input.ordinal.frameIndex.peekull());
2148 notifyClient = false;
2149 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002150 }
2151
2152 if (buffer) {
2153 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2154 // TODO: properly translate these to metadata
2155 switch (info->coreIndex().coreIndex()) {
2156 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002157 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002158 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002159 }
2160 break;
2161 default:
2162 break;
2163 }
2164 }
2165 }
2166
2167 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002168 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002169 if (!output->buffers) {
2170 return false;
2171 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002172 output->buffers->pushToStash(
2173 buffer,
2174 notifyClient,
2175 timestamp.peek(),
2176 flags,
2177 outputFormat,
2178 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002179 }
2180 sendOutputBuffers();
2181 return true;
2182}
2183
2184void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002185 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002186 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002187 sp<MediaCodecBuffer> outBuffer;
2188 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002189
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002190 constexpr int kMaxReallocTry = 5;
2191 int reallocTryNum = 0;
2192
Pawin Vongmasa36653902018-11-15 00:10:25 -08002193 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002194 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002195 if (!output->buffers) {
2196 return;
2197 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002198 action = output->buffers->popFromStashAndRegister(
2199 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002200 if (action != OutputBuffers::REALLOCATE) {
2201 reallocTryNum = 0;
2202 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002203 switch (action) {
2204 case OutputBuffers::SKIP:
2205 return;
2206 case OutputBuffers::DISCARD:
2207 break;
2208 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002209 // TRICKY: we want popped buffers reported in order, so sending
2210 // the callback while holding the lock here. This assumes that
2211 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2212 // callbacks are always sent with the Output lock held.
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002213 mCallback->onOutputBufferAvailable(index, outBuffer);
2214 break;
2215 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002216 if (++reallocTryNum > kMaxReallocTry) {
2217 output.unlock();
2218 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2219 mName, kMaxReallocTry);
2220 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2221 return;
2222 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002223 if (!output->buffers->isArrayMode()) {
2224 output->buffers =
2225 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002226 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002227 static_cast<OutputBuffersArray*>(output->buffers.get())->
2228 realloc(c2Buffer);
2229 output.unlock();
2230 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002231 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002232 case OutputBuffers::RETRY:
2233 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2234 mName);
2235 return;
2236 default:
2237 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2238 "corrupted BufferAction value (%d) "
2239 "returned from popFromStashAndRegister.",
2240 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002241 return;
2242 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002243 }
2244}
2245
Sungtak Lee99144332023-01-26 11:03:14 +00002246status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002247 static std::atomic_uint32_t surfaceGeneration{0};
2248 uint32_t generation = (getpid() << 10) |
2249 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2250 & ((1 << 10) - 1));
2251
2252 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002253 int maxDequeueCount;
2254 sp<Surface> oldSurface;
2255 {
2256 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2257 maxDequeueCount = outputSurface->maxDequeueBuffers;
2258 oldSurface = outputSurface->surface;
2259 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002260 if (newSurface) {
2261 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002262 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002263 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002264 producer = newSurface->getIGraphicBufferProducer();
2265 producer->setGenerationNumber(generation);
2266 } else {
2267 ALOGE("[%s] setting output surface to null", mName);
2268 return INVALID_OPERATION;
2269 }
2270
2271 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2272 C2BlockPool::local_id_t outputPoolId;
2273 {
2274 Mutexed<BlockPools>::Locked pools(mBlockPools);
2275 outputPoolId = pools->outputPoolId;
2276 outputPoolIntf = pools->outputPoolIntf;
2277 }
2278
2279 if (outputPoolIntf) {
2280 if (mComponent->setOutputSurface(
2281 outputPoolId,
2282 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002283 generation,
2284 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002285 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2286 return INVALID_OPERATION;
2287 }
2288 }
2289
2290 {
2291 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2292 output->surface = newSurface;
2293 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002294 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002295 }
2296
Sungtak Lee99144332023-01-26 11:03:14 +00002297 if (oldSurface && pushBlankBuffer) {
2298 // When ReleaseSurface was set from MediaCodec,
2299 // pushing a blank buffer at the end might be necessary.
2300 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2301 if (anw) {
2302 pushBlankBuffersToNativeWindow(anw.get());
2303 }
2304 }
2305
Pawin Vongmasa36653902018-11-15 00:10:25 -08002306 return OK;
2307}
2308
Wonsik Kimab34ed62019-01-31 15:28:46 -08002309PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002310 // Otherwise, component may have stalled work due to input starvation up to
2311 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002312 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2313 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002314 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002315 size_t outputDelay = mOutput.lock()->outputDelay;
2316 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002317 Mutexed<Input>::Locked input(mInput);
2318 n = input->inputDelay + input->pipelineDelay + outputDelay;
2319 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002320 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002321}
2322
Pawin Vongmasa36653902018-11-15 00:10:25 -08002323void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2324 mMetaMode = mode;
2325}
2326
Wonsik Kim596187e2019-10-25 12:44:10 -07002327void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002328 if (mCrypto != nullptr) {
2329 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2330 mCrypto->unsetHeap(entry.second);
2331 }
2332 mHeapSeqNumMap.clear();
2333 if (mHeapSeqNum >= 0) {
2334 mCrypto->unsetHeap(mHeapSeqNum);
2335 mHeapSeqNum = -1;
2336 }
2337 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002338 mCrypto = crypto;
2339}
2340
2341void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2342 mDescrambler = descrambler;
2343}
2344
Pawin Vongmasa36653902018-11-15 00:10:25 -08002345status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2346 // C2_OK is always translated to OK.
2347 if (c2s == C2_OK) {
2348 return OK;
2349 }
2350
2351 // Operation-dependent translation
2352 // TODO: Add as necessary
2353 switch (c2op) {
2354 case C2_OPERATION_Component_start:
2355 switch (c2s) {
2356 case C2_NO_MEMORY:
2357 return NO_MEMORY;
2358 default:
2359 return UNKNOWN_ERROR;
2360 }
2361 default:
2362 break;
2363 }
2364
2365 // Backup operation-agnostic translation
2366 switch (c2s) {
2367 case C2_BAD_INDEX:
2368 return BAD_INDEX;
2369 case C2_BAD_VALUE:
2370 return BAD_VALUE;
2371 case C2_BLOCKING:
2372 return WOULD_BLOCK;
2373 case C2_DUPLICATE:
2374 return ALREADY_EXISTS;
2375 case C2_NO_INIT:
2376 return NO_INIT;
2377 case C2_NO_MEMORY:
2378 return NO_MEMORY;
2379 case C2_NOT_FOUND:
2380 return NAME_NOT_FOUND;
2381 case C2_TIMED_OUT:
2382 return TIMED_OUT;
2383 case C2_BAD_STATE:
2384 case C2_CANCELED:
2385 case C2_CANNOT_DO:
2386 case C2_CORRUPTED:
2387 case C2_OMITTED:
2388 case C2_REFUSED:
2389 return UNKNOWN_ERROR;
2390 default:
2391 return -static_cast<status_t>(c2s);
2392 }
2393}
2394
Pawin Vongmasa36653902018-11-15 00:10:25 -08002395} // namespace android