blob: 593dbf336f30177cf662debf0a8df9b1b046e153 [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;
170 }
David Stevensc3fbb282021-01-18 18:11:20 +0900171 {
172 Mutexed<BlockPools>::Locked pools(mBlockPools);
173 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
174 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800175}
176
177CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800178 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800179 mCrypto->unsetHeap(mHeapSeqNum);
180 }
181}
182
183void CCodecBufferChannel::setComponent(
184 const std::shared_ptr<Codec2Client::Component> &component) {
185 mComponent = component;
186 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
187 mName = mComponentName.c_str();
188}
189
190status_t CCodecBufferChannel::setInputSurface(
191 const std::shared_ptr<InputSurfaceWrapper> &surface) {
192 ALOGV("[%s] setInputSurface", mName);
193 mInputSurface = surface;
194 return mInputSurface->connect(mComponent);
195}
196
197status_t CCodecBufferChannel::signalEndOfInputStream() {
198 if (mInputSurface == nullptr) {
199 return INVALID_OPERATION;
200 }
201 return mInputSurface->signalEndOfInputStream();
202}
203
Sungtak Lee04b30352020-07-27 13:57:25 -0700204status_t CCodecBufferChannel::queueInputBufferInternal(
205 sp<MediaCodecBuffer> buffer,
206 std::shared_ptr<C2LinearBlock> encryptedBlock,
207 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800208 int64_t timeUs;
209 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
210
211 if (mInputMetEos) {
212 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
213 return OK;
214 }
215
216 int32_t flags = 0;
217 int32_t tmp = 0;
218 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200219 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800220 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
221 eos = true;
222 mInputMetEos = true;
223 ALOGV("[%s] input EOS", mName);
224 }
225 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
226 flags |= C2FrameData::FLAG_CODEC_CONFIG;
227 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200228 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
229 tunnelFirstFrame = true;
230 }
Marc Kassis96343b42022-12-09 11:49:44 +0100231 if (buffer->meta()->findInt32("decode-only", &tmp) && tmp) {
232 flags |= C2FrameData::FLAG_DROP_FRAME;
233 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800234 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800235 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800236 std::unique_ptr<C2Work> work(new C2Work);
237 work->input.ordinal.timestamp = timeUs;
238 work->input.ordinal.frameIndex = mFrameIndex++;
239 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
240 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
241 // Keep client timestamp in customOrdinal
242 work->input.ordinal.customOrdinal = timeUs;
243 work->input.buffers.clear();
244
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700245 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800246 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800247
Pawin Vongmasa36653902018-11-15 00:10:25 -0800248 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700249 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800250 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700251 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800252 return -ENOENT;
253 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700254 // TODO: we want to delay copying buffers.
255 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
256 copy = input->buffers->cloneAndReleaseBuffer(buffer);
257 if (copy != nullptr) {
258 (void)input->extraBuffers.assignSlot(copy);
259 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
260 return UNKNOWN_ERROR;
261 }
262 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
263 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
264 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700265 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700266 } else {
267 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
268 "buffer starvation on component.", mName);
269 }
270 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800271 if (input->frameReassembler) {
272 usesFrameReassembler = true;
273 input->frameReassembler.process(buffer, &items);
274 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900275 int32_t cvo = 0;
276 if (buffer->meta()->findInt32("cvo", &cvo)) {
277 int32_t rotation = cvo % 360;
278 // change rotation to counter-clock wise.
279 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
280
281 Mutexed<OutputSurface>::Locked output(mOutputSurface);
282 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
283 output->rotation[frameIndex] = rotation;
284 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800285 work->input.buffers.push_back(c2buffer);
286 if (encryptedBlock) {
287 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
288 kParamIndexEncryptedBuffer,
289 encryptedBlock->share(0, blockSize, C2Fence())));
290 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700291 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800292 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700293 Mutexed<Input>::Locked input(mInput);
294 if (input->frameReassembler) {
295 usesFrameReassembler = true;
296 // drain any pending items with eos
297 input->frameReassembler.process(buffer, &items);
298 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800299 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800300 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800301 if (usesFrameReassembler) {
302 if (!items.empty()) {
303 items.front()->input.configUpdate = std::move(mParamsToBeSet);
304 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
305 }
306 } else {
307 work->input.flags = (C2FrameData::flags_t)flags;
308 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800309
Wonsik Kime1104ca2020-11-24 15:01:33 -0800310 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200311 if (tunnelFirstFrame) {
312 C2StreamTunnelHoldRender::input tunnelHoldRender{
313 0u /* stream */,
314 C2_TRUE /* value */
315 };
316 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
317 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800318 work->worklets.clear();
319 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800320
Wonsik Kime1104ca2020-11-24 15:01:33 -0800321 items.push_back(std::move(work));
322
323 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800324 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800325 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800326 work.reset(new C2Work);
327 work->input.ordinal.timestamp = timeUs;
328 work->input.ordinal.frameIndex = mFrameIndex++;
329 // WORKAROUND: keep client timestamp in customOrdinal
330 work->input.ordinal.customOrdinal = timeUs;
331 work->input.buffers.clear();
332 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800333 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800334 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800335 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800336 c2_status_t err = C2_OK;
337 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700338 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
339 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800340 {
341 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
342 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
343 for (const std::unique_ptr<C2Work> &work : items) {
344 watcher->onWorkQueued(
345 work->input.ordinal.frameIndex.peeku(),
346 std::vector(work->input.buffers),
347 now);
348 }
349 }
350 err = mComponent->queue(&items);
351 }
352 if (err != C2_OK) {
353 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
354 for (const std::unique_ptr<C2Work> &work : items) {
355 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
356 }
357 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700358 Mutexed<Input>::Locked input(mInput);
359 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700360 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700361 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700362 } else if (buffer) {
363 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700364 }
365 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
366 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800367 }
368
369 feedInputBufferIfAvailableInternal();
370 return err;
371}
372
373status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
374 QueueGuard guard(mSync);
375 if (!guard.isRunning()) {
376 ALOGD("[%s] setParameters is only supported in the running state.", mName);
377 return -ENOSYS;
378 }
379 mParamsToBeSet.insert(mParamsToBeSet.end(),
380 std::make_move_iterator(params.begin()),
381 std::make_move_iterator(params.end()));
382 params.clear();
383 return OK;
384}
385
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800386status_t CCodecBufferChannel::attachBuffer(
387 const std::shared_ptr<C2Buffer> &c2Buffer,
388 const sp<MediaCodecBuffer> &buffer) {
389 if (!buffer->copy(c2Buffer)) {
390 return -ENOSYS;
391 }
392 return OK;
393}
394
395void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
396 if (!mDecryptDestination || mDecryptDestination->size() < size) {
397 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
398 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
399 mCrypto->unsetHeap(mHeapSeqNum);
400 }
401 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
402 if (mCrypto) {
403 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
404 }
405 }
406}
407
408int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
409 CHECK(mCrypto);
410 auto it = mHeapSeqNumMap.find(memory);
411 int32_t heapSeqNum = -1;
412 if (it == mHeapSeqNumMap.end()) {
413 heapSeqNum = mCrypto->setHeap(memory);
414 mHeapSeqNumMap.emplace(memory, heapSeqNum);
415 } else {
416 heapSeqNum = it->second;
417 }
418 return heapSeqNum;
419}
420
421status_t CCodecBufferChannel::attachEncryptedBuffer(
422 const sp<hardware::HidlMemory> &memory,
423 bool secure,
424 const uint8_t *key,
425 const uint8_t *iv,
426 CryptoPlugin::Mode mode,
427 CryptoPlugin::Pattern pattern,
428 size_t offset,
429 const CryptoPlugin::SubSample *subSamples,
430 size_t numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000431 const sp<MediaCodecBuffer> &buffer,
432 AString* errorDetailMsg) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800433 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
434 static const C2MemoryUsage kDefaultReadWriteUsage{
435 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
436
437 size_t size = 0;
438 for (size_t i = 0; i < numSubSamples; ++i) {
439 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
440 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700441 if (size == 0) {
442 buffer->setRange(0, 0);
443 return OK;
444 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800445 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
446 std::shared_ptr<C2LinearBlock> block;
447 c2_status_t err = pool->fetchLinearBlock(
448 size,
449 secure ? kSecureUsage : kDefaultReadWriteUsage,
450 &block);
451 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700452 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
453 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800454 return NO_MEMORY;
455 }
456 if (!secure) {
457 ensureDecryptDestination(size);
458 }
459 ssize_t result = -1;
460 ssize_t codecDataOffset = 0;
461 if (mCrypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800462 int32_t heapSeqNum = getHeapSeqNum(memory);
463 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
464 hardware::drm::V1_0::DestinationBuffer dst;
465 if (secure) {
466 dst.type = DrmBufferType::NATIVE_HANDLE;
467 dst.secureMemory = hardware::hidl_handle(block->handle());
468 } else {
469 dst.type = DrmBufferType::SHARED_MEMORY;
470 IMemoryToSharedBuffer(
471 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
472 }
473 result = mCrypto->decrypt(
474 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000475 dst, errorDetailMsg);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800476 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700477 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800478 return result;
479 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800480 } else {
481 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
482 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
483 hidl_vec<SubSample> hidlSubSamples;
484 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
485
486 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
487 hardware::cas::native::V1_0::DestinationBuffer dst;
488 if (secure) {
489 dst.type = BufferType::NATIVE_HANDLE;
490 dst.secureMemory = hardware::hidl_handle(block->handle());
491 } else {
492 dst.type = BufferType::SHARED_MEMORY;
493 dst.nonsecureMemory = src;
494 }
495
496 CasStatus status = CasStatus::OK;
497 hidl_string detailedError;
498 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
499
500 if (key != nullptr) {
501 sctrl = (ScramblingControl)key[0];
502 // Adjust for the PES offset
503 codecDataOffset = key[2] | (key[3] << 8);
504 }
505
506 auto returnVoid = mDescrambler->descramble(
507 sctrl,
508 hidlSubSamples,
509 src,
510 0,
511 dst,
512 0,
513 [&status, &result, &detailedError] (
514 CasStatus _status, uint32_t _bytesWritten,
515 const hidl_string& _detailedError) {
516 status = _status;
517 result = (ssize_t)_bytesWritten;
518 detailedError = _detailedError;
519 });
Arun Johnson634d0802023-02-14 22:07:51 +0000520 if (errorDetailMsg) {
521 errorDetailMsg->setTo(detailedError.c_str(), detailedError.size());
522 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800523 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
524 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
525 mName, returnVoid.description().c_str(), status, result);
526 return UNKNOWN_ERROR;
527 }
528
529 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700530 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
531 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800532 return BAD_VALUE;
533 }
534 }
535 if (!secure) {
536 C2WriteView view = block->map().get();
537 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700538 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
539 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800540 return UNKNOWN_ERROR;
541 }
542 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700543 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
544 "(non-secure)",
545 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800546 return UNKNOWN_ERROR;
547 }
548 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
549 }
550 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
551 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
552 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700553 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800554 return -ENOSYS;
555 }
556 return OK;
557}
558
Pawin Vongmasa36653902018-11-15 00:10:25 -0800559status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
560 QueueGuard guard(mSync);
561 if (!guard.isRunning()) {
562 ALOGD("[%s] No more buffers should be queued at current state.", mName);
563 return -ENOSYS;
564 }
565 return queueInputBufferInternal(buffer);
566}
567
568status_t CCodecBufferChannel::queueSecureInputBuffer(
569 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
570 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
571 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
572 AString *errorDetailMsg) {
573 QueueGuard guard(mSync);
574 if (!guard.isRunning()) {
575 ALOGD("[%s] No more buffers should be queued at current state.", mName);
576 return -ENOSYS;
577 }
578
579 if (!hasCryptoOrDescrambler()) {
580 return -ENOSYS;
581 }
582 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
583
Sungtak Lee04b30352020-07-27 13:57:25 -0700584 std::shared_ptr<C2LinearBlock> block;
585 size_t allocSize = buffer->size();
586 size_t bufferSize = 0;
587 c2_status_t blockRes = C2_OK;
588 bool copied = false;
589 if (mSendEncryptedInfoBuffer) {
590 static const C2MemoryUsage kDefaultReadWriteUsage{
591 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
592 constexpr int kAllocGranule0 = 1024 * 64;
593 constexpr int kAllocGranule1 = 1024 * 1024;
594 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
595 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
596 if (allocSize <= kAllocGranule1) {
597 bufferSize = align(allocSize, kAllocGranule0);
598 } else {
599 bufferSize = align(allocSize, kAllocGranule1);
600 }
601 blockRes = pool->fetchLinearBlock(
602 bufferSize, kDefaultReadWriteUsage, &block);
603
604 if (blockRes == C2_OK) {
605 C2WriteView view = block->map().get();
606 if (view.error() == C2_OK && view.size() == bufferSize) {
607 copied = true;
608 // TODO: only copy clear sections
609 memcpy(view.data(), buffer->data(), allocSize);
610 }
611 }
612 }
613
614 if (!copied) {
615 block.reset();
616 }
617
Pawin Vongmasa36653902018-11-15 00:10:25 -0800618 ssize_t result = -1;
619 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700620 if (numSubSamples == 1
621 && subSamples[0].mNumBytesOfClearData == 0
622 && subSamples[0].mNumBytesOfEncryptedData == 0) {
623 // We don't need to go through crypto or descrambler if the input is empty.
624 result = 0;
625 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700626 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800627 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700628 destination.type = DrmBufferType::NATIVE_HANDLE;
629 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800630 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700631 destination.type = DrmBufferType::SHARED_MEMORY;
632 IMemoryToSharedBuffer(
633 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800634 }
Robert Shih895fba92019-07-16 16:29:44 -0700635 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800636 encryptedBuffer->fillSourceBuffer(&source);
637 result = mCrypto->decrypt(
638 key, iv, mode, pattern, source, buffer->offset(),
639 subSamples, numSubSamples, destination, errorDetailMsg);
640 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700641 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800642 return result;
643 }
Robert Shih895fba92019-07-16 16:29:44 -0700644 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800645 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
646 }
647 } else {
648 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
649 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
650 hidl_vec<SubSample> hidlSubSamples;
651 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
652
653 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
654 encryptedBuffer->fillSourceBuffer(&srcBuffer);
655
656 DestinationBuffer dstBuffer;
657 if (secure) {
658 dstBuffer.type = BufferType::NATIVE_HANDLE;
659 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
660 } else {
661 dstBuffer.type = BufferType::SHARED_MEMORY;
662 dstBuffer.nonsecureMemory = srcBuffer;
663 }
664
665 CasStatus status = CasStatus::OK;
666 hidl_string detailedError;
667 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
668
669 if (key != nullptr) {
670 sctrl = (ScramblingControl)key[0];
671 // Adjust for the PES offset
672 codecDataOffset = key[2] | (key[3] << 8);
673 }
674
675 auto returnVoid = mDescrambler->descramble(
676 sctrl,
677 hidlSubSamples,
678 srcBuffer,
679 0,
680 dstBuffer,
681 0,
682 [&status, &result, &detailedError] (
683 CasStatus _status, uint32_t _bytesWritten,
684 const hidl_string& _detailedError) {
685 status = _status;
686 result = (ssize_t)_bytesWritten;
687 detailedError = _detailedError;
688 });
689
690 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
691 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
692 mName, returnVoid.description().c_str(), status, result);
693 return UNKNOWN_ERROR;
694 }
695
696 if (result < codecDataOffset) {
697 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
698 return BAD_VALUE;
699 }
700
701 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
702
703 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
704 encryptedBuffer->copyDecryptedContentFromMemory(result);
705 }
706 }
707
708 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700709
710 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800711}
712
713void CCodecBufferChannel::feedInputBufferIfAvailable() {
714 QueueGuard guard(mSync);
715 if (!guard.isRunning()) {
716 ALOGV("[%s] We're not running --- no input buffer reported", mName);
717 return;
718 }
719 feedInputBufferIfAvailableInternal();
720}
721
722void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900723 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800724 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700725 }
726 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700727 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700728 if (!output->buffers ||
729 output->buffers->hasPending() ||
Wonsik Kim0487b782020-10-28 11:45:50 -0700730 output->buffers->numActiveSlots() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800731 return;
732 }
733 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700734 size_t numActiveSlots = 0;
735 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800736 sp<MediaCodecBuffer> inBuffer;
737 size_t index;
738 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700739 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700740 numActiveSlots = input->buffers->numActiveSlots();
741 if (numActiveSlots >= input->numSlots) {
742 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800743 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700744 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800745 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800746 break;
747 }
748 }
749 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
750 mCallback->onInputBufferAvailable(index, inBuffer);
751 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700752 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800753}
754
755status_t CCodecBufferChannel::renderOutputBuffer(
756 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800757 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800758 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800759 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800760 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700761 Mutexed<Output>::Locked output(mOutput);
762 if (output->buffers) {
763 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800764 }
765 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800766 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
767 // set to true.
768 sendOutputBuffers();
769 // input buffer feeding may have been gated by pending output buffers
770 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800771 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800772 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700773 std::call_once(mRenderWarningFlag, [this] {
774 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
775 "timestamp or render=true with non-video buffers. Apps should "
776 "call releaseOutputBuffer() with render=false for those.",
777 mName);
778 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800779 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800780 return INVALID_OPERATION;
781 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800782
783#if 0
784 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
785 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
786 for (const std::shared_ptr<const C2Info> &info : infoParams) {
787 AString res;
788 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
789 if (ix) res.append(", ");
790 res.append(*((int32_t*)info.get() + (ix / 4)));
791 }
792 ALOGV(" [%s]", res.c_str());
793 }
794#endif
795 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
796 std::static_pointer_cast<const C2StreamRotationInfo::output>(
797 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
798 bool flip = rotation && (rotation->flip & 1);
799 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900800
801 {
802 Mutexed<OutputSurface>::Locked output(mOutputSurface);
803 if (output->surface == nullptr) {
804 ALOGI("[%s] cannot render buffer without surface", mName);
805 return OK;
806 }
807 int64_t frameIndex;
808 buffer->meta()->findInt64("frameIndex", &frameIndex);
809 if (output->rotation.count(frameIndex) != 0) {
810 auto it = output->rotation.find(frameIndex);
811 quarters = (it->second / 90) & 3;
812 output->rotation.erase(it);
813 }
814 }
815
Pawin Vongmasa36653902018-11-15 00:10:25 -0800816 uint32_t transform = 0;
817 switch (quarters) {
818 case 0: // no rotation
819 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
820 break;
821 case 1: // 90 degrees counter-clockwise
822 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
823 : HAL_TRANSFORM_ROT_270;
824 break;
825 case 2: // 180 degrees
826 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
827 break;
828 case 3: // 90 degrees clockwise
829 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
830 : HAL_TRANSFORM_ROT_90;
831 break;
832 }
833
834 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
835 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
836 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
837 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
838 if (surfaceScaling) {
839 videoScalingMode = surfaceScaling->value;
840 }
841
842 // Use dataspace from format as it has the default aspects already applied
843 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
844 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
845
846 // HDR static info
847 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
848 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
849 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
850
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800851 // HDR10 plus info
852 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
853 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
854 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800855 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
856 hdr10PlusInfo.reset();
857 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800858
Wonsik Kima79c5522022-01-18 16:29:24 -0800859 // HDR dynamic info
860 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
861 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
862 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
863 // TODO: make this sticky & enable unset
864 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
865 hdrDynamicInfo.reset();
866 }
867
868 if (hdr10PlusInfo) {
869 // C2StreamHdr10PlusInfo is deprecated; components should use
870 // C2StreamHdrDynamicMetadataInfo
871 // TODO: #metric
872 if (hdrDynamicInfo) {
873 // It is unexpected that C2StreamHdr10PlusInfo and
874 // C2StreamHdrDynamicMetadataInfo is both present.
875 // C2StreamHdrDynamicMetadataInfo takes priority.
876 // TODO: #metric
877 } else {
878 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
879 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
880 hdr10PlusInfo->flexCount(),
881 0u,
882 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
883 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
884 hdrDynamicInfo = info;
885 }
886 }
887
Pawin Vongmasa36653902018-11-15 00:10:25 -0800888 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
889 if (blocks.size() != 1u) {
890 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
891 return UNKNOWN_ERROR;
892 }
893 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700894 C2Fence c2fence = block.fence();
895 sp<Fence> fence = Fence::NO_FENCE;
896 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
897 // Once C2Fence::type() is added, check the exact C2Fence type
898 if (c2fence.isHW()) {
899 int fenceFd = c2fence.fd();
900 fence = sp<Fence>::make(fenceFd);
901 if (!fence) {
902 ALOGE("[%s] Failed to allocate a fence", mName);
903 close(fenceFd);
904 return NO_MEMORY;
905 }
906 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800907
908 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -0700909 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800910 timestampNs,
911 false, // droppable
912 dataSpace,
913 Rect(blocks.front().crop().left,
914 blocks.front().crop().top,
915 blocks.front().crop().right(),
916 blocks.front().crop().bottom()),
917 videoScalingMode,
918 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700919 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800920 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800921 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800922 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800923 // If mastering max and min luminance fields are 0, do not use them.
924 // It indicates the value may not be present in the stream.
925 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
926 hdrStaticInfo->mastering.minLuminance > 0.0f) {
927 struct android_smpte2086_metadata smpte2086_meta = {
928 .displayPrimaryRed = {
929 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
930 },
931 .displayPrimaryGreen = {
932 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
933 },
934 .displayPrimaryBlue = {
935 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
936 },
937 .whitePoint = {
938 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
939 },
940 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
941 .minLuminance = hdrStaticInfo->mastering.minLuminance,
942 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800943 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800944 hdr.smpte2086 = smpte2086_meta;
945 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700946 // If the content light level fields are 0, do not use them, it
947 // indicates the value may not be present in the stream.
948 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
949 struct android_cta861_3_metadata cta861_meta = {
950 .maxContentLightLevel = hdrStaticInfo->maxCll,
951 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
952 };
953 hdr.validTypes |= HdrMetadata::CTA861_3;
954 hdr.cta8613 = cta861_meta;
955 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900956
957 // does not have valid info
958 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
959 hdrStaticInfo.reset();
960 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800961 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800962 if (hdrDynamicInfo
963 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800964 hdr.validTypes |= HdrMetadata::HDR10PLUS;
965 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800966 hdrDynamicInfo->m.data,
967 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800968 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800969 qbi.setHdrMetadata(hdr);
970 }
Hongguangfc1478a2022-07-20 22:56:06 -0700971 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
972
Brian Lindahl932bf602023-03-09 11:59:48 -0700973 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
974 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
975 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800976 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
977 if (result != OK) {
978 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800979 if (result == NO_INIT) {
980 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
981 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800982 return result;
983 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800984
985 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
986 ALOGD("[%s] queue buffer successful", mName);
987 } else {
988 ALOGV("[%s] queue buffer successful", mName);
989 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800990
991 int64_t mediaTimeUs = 0;
992 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahl2048d492023-04-05 08:49:23 -0600993 if (mIsSurfaceToDisplay) {
994 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
995 processRenderedFrames(qbo.frameTimestamps);
996 } else {
997 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
998 // when the frame is queued to the non-display surface
999 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1000 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001001
1002 return OK;
1003}
1004
Brian Lindahl932bf602023-03-09 11:59:48 -07001005void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001006 mTrackedFrames.clear();
1007
1008 int isSurfaceToDisplay = 0;
1009 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1010 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1011 // No frame tracking is needed if we're not sending frames to the display
1012 if (!mIsSurfaceToDisplay) {
1013 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1014 return;
1015 }
1016
Brian Lindahl932bf602023-03-09 11:59:48 -07001017 int hasPresentFenceTimes = 0;
1018 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1019 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
1020 if (mHasPresentFenceTimes) {
1021 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1022 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001023}
1024
1025void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1026 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1027 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1028 // so track the frame as if the desired render time is now.
1029 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1030 if (desiredRenderTimeNs < nowNs) {
1031 desiredRenderTimeNs = nowNs;
1032 }
1033 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1034 // actually rendered.
1035 TrackedFrame frame;
1036 frame.number = qbo.nextFrameNumber - 1;
1037 frame.mediaTimeUs = mediaTimeUs;
1038 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1039 frame.latchTime = -1;
1040 frame.presentFence = nullptr;
1041 mTrackedFrames.push_back(frame);
1042}
1043
1044void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1045 // Grab the latch times and present fences from the frame event deltas
1046 for (const auto& delta : deltas) {
1047 for (auto& frame : mTrackedFrames) {
1048 if (delta.getFrameNumber() == frame.number) {
1049 delta.getLatchTime(&frame.latchTime);
1050 delta.getDisplayPresentFence(&frame.presentFence);
1051 }
1052 }
1053 }
1054
1055 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1056 // in fact, been rendered.
1057 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1058 while (!mTrackedFrames.empty()) {
1059 TrackedFrame & frame = mTrackedFrames.front();
1060 // Frames that should have been rendered at least 100ms in the past are checked
1061 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1062 break;
1063 }
1064
1065 // If we don't have a render time by now, then consider the frame as dropped
1066 int64_t renderTimeNs = getRenderTimeNs(frame);
1067 if (renderTimeNs != -1) {
1068 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1069 }
1070 mTrackedFrames.pop_front();
1071 }
1072}
1073
1074int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1075 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1076 if (!mHasPresentFenceTimes) {
1077 if (frame.latchTime == -1) {
1078 ALOGD("no latch time for frame %d", (int) frame.number);
1079 return -1;
1080 }
1081 return frame.latchTime;
1082 }
1083
1084 if (frame.presentFence == nullptr) {
1085 ALOGW("no present fence for frame %d", (int) frame.number);
1086 return -1;
1087 }
1088
1089 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1090
1091 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1092 ALOGW("invalid signal time for frame %d", (int) frame.number);
1093 return -1;
1094 }
1095
1096 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1097 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1098 return -1;
1099 }
1100
1101 return actualRenderTimeNs;
1102}
1103
1104void CCodecBufferChannel::pollForRenderedBuffers() {
1105 FrameEventHistoryDelta delta;
1106 mComponent->pollForRenderedFrames(&delta);
1107 processRenderedFrames(delta);
1108}
1109
Pawin Vongmasa36653902018-11-15 00:10:25 -08001110status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1111 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1112 bool released = false;
1113 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001114 Mutexed<Input>::Locked input(mInput);
1115 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001116 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001117 }
1118 }
1119 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001120 Mutexed<Output>::Locked output(mOutput);
1121 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001122 released = true;
1123 }
1124 }
1125 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001126 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001127 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001128 } else {
1129 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1130 }
1131 return OK;
1132}
1133
1134void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1135 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001136 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001137
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001138 if (!input->buffers) {
1139 ALOGE("getInputBufferArray: No Input Buffers allocated");
1140 return;
1141 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001142 if (!input->buffers->isArrayMode()) {
1143 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001144 }
1145
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001146 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001147}
1148
1149void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1150 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001151 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001152 if (!output->buffers) {
1153 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1154 return;
1155 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001156 if (!output->buffers->isArrayMode()) {
1157 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001158 }
1159
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001160 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001161}
1162
1163status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001164 const sp<AMessage> &inputFormat,
1165 const sp<AMessage> &outputFormat,
1166 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001167 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1168 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001169 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001170 C2PortReorderBufferDepthTuning::output reorderDepth;
1171 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001172 C2PortActualDelayTuning::input inputDelay(0);
1173 C2PortActualDelayTuning::output outputDelay(0);
1174 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001175 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001176
Pawin Vongmasa36653902018-11-15 00:10:25 -08001177 c2_status_t err = mComponent->query(
1178 {
1179 &iStreamFormat,
1180 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001181 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001182 &reorderDepth,
1183 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001184 &inputDelay,
1185 &pipelineDelay,
1186 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001187 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001188 },
1189 {},
1190 C2_DONT_BLOCK,
1191 nullptr);
1192 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001193 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001194 return UNKNOWN_ERROR;
1195 }
1196 } else if (err != C2_OK) {
1197 return UNKNOWN_ERROR;
1198 }
1199
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001200 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1201 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1202 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1203
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001204 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1205 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001206
Pawin Vongmasa36653902018-11-15 00:10:25 -08001207 // TODO: get this from input format
1208 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1209
Sungtak Lee04b30352020-07-27 13:57:25 -07001210 // secure mode is a static parameter (shall not change in the executing state)
1211 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1212
Pawin Vongmasa36653902018-11-15 00:10:25 -08001213 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001214 int poolMask = GetCodec2PoolMask();
1215 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001216
1217 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001218 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001219 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001220 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1221 API_REFLECTION |
1222 API_VALUES |
1223 API_CURRENT_VALUES |
1224 API_DEPENDENCY |
1225 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001226 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1227 C2StreamSampleRateInfo::input sampleRate(0u);
1228 C2StreamChannelCountInfo::input channelCount(0u);
1229 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001230 std::shared_ptr<C2BlockPool> pool;
1231 {
1232 Mutexed<BlockPools>::Locked pools(mBlockPools);
1233
1234 // set default allocator ID.
1235 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001236 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001237
1238 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1239 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1240 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001241 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001242 std::vector<C2Param *> stackParams({&featuresSetting});
1243 if (audioEncoder) {
1244 stackParams.push_back(&encoderFrameSize);
1245 stackParams.push_back(&sampleRate);
1246 stackParams.push_back(&channelCount);
1247 stackParams.push_back(&pcmEncoding);
1248 } else {
1249 encoderFrameSize.invalidate();
1250 sampleRate.invalidate();
1251 channelCount.invalidate();
1252 pcmEncoding.invalidate();
1253 }
1254 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001255 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1256 C2_DONT_BLOCK,
1257 &params);
1258 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1259 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1260 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001261 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001262 C2PortAllocatorsTuning::input *inputAllocators =
1263 C2PortAllocatorsTuning::input::From(params[0].get());
1264 if (inputAllocators && inputAllocators->flexCount() > 0) {
1265 std::shared_ptr<C2Allocator> allocator;
1266 // verify allocator IDs and resolve default allocator
1267 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1268 if (allocator) {
1269 pools->inputAllocatorId = allocator->getId();
1270 } else {
1271 ALOGD("[%s] component requested invalid input allocator ID %u",
1272 mName, inputAllocators->m.values[0]);
1273 }
1274 }
1275 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001276 if (featuresSetting) {
1277 apiFeatures = featuresSetting.value;
1278 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001279
1280 // TODO: use C2Component wrapper to associate this pool with ourselves
1281 if ((poolMask >> pools->inputAllocatorId) & 1) {
1282 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1283 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1284 mName, pools->inputAllocatorId,
1285 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1286 asString(err), err);
1287 } else {
1288 err = C2_NOT_FOUND;
1289 }
1290 if (err != C2_OK) {
1291 C2BlockPool::local_id_t inputPoolId =
1292 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1293 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1294 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1295 mName, (unsigned long long)inputPoolId,
1296 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1297 asString(err), err);
1298 if (err != C2_OK) {
1299 return NO_MEMORY;
1300 }
1301 }
1302 pools->inputPool = pool;
1303 }
1304
Wonsik Kim51051262018-11-28 13:59:05 -08001305 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001306 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001307 input->inputDelay = inputDelayValue;
1308 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001309 input->numSlots = numInputSlots;
1310 input->extraBuffers.flush();
1311 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001312 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001313 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1314 input->frameReassembler.init(
1315 pool,
1316 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1317 encoderFrameSize.value,
1318 sampleRate.value,
1319 channelCount.value,
1320 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1321 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001322 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1323 // For encrypted content, framework decrypts source buffer (ashmem) into
1324 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001325 if (!buffersBoundToCodec
1326 && !input->frameReassembler
1327 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001328 input->buffers.reset(new SlotInputBuffers(mName));
1329 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001330 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001331 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001332 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001333 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001334 // This is to ensure buffers do not get released prematurely.
1335 // TODO: handle this without going into array mode
1336 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001337 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001338 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001339 }
1340 } else {
1341 if (hasCryptoOrDescrambler()) {
1342 int32_t capacity = kLinearBufferSize;
1343 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1344 if ((size_t)capacity > kMaxLinearBufferSize) {
1345 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1346 capacity = kMaxLinearBufferSize;
1347 }
1348 if (mDealer == nullptr) {
1349 mDealer = new MemoryDealer(
1350 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001351 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001352 "EncryptedLinearInputBuffers");
1353 mDecryptDestination = mDealer->allocate((size_t)capacity);
1354 }
1355 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001356 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1357 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001358 } else {
1359 mHeapSeqNum = -1;
1360 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001361 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001362 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001363 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001364 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001365 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001366 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001367 }
1368 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001369 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001370
1371 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001372 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001373 } else {
1374 // TODO: error
1375 }
Wonsik Kim51051262018-11-28 13:59:05 -08001376
1377 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001378 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001379 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001380 }
1381
1382 if (outputFormat != nullptr) {
1383 sp<IGraphicBufferProducer> outputSurface;
1384 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001385 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001386 {
1387 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001388 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001389 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001390 outputSurface = output->surface ?
1391 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001392 if (outputSurface) {
1393 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1394 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001395 outputGeneration = output->generation;
1396 }
1397
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001398 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001399 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001400 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001401
1402 {
1403 Mutexed<BlockPools>::Locked pools(mBlockPools);
1404
David Stevensc3fbb282021-01-18 18:11:20 +09001405 prevOutputPoolId = pools->outputPoolId;
1406
Pawin Vongmasa36653902018-11-15 00:10:25 -08001407 // set default allocator ID.
1408 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001409 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001410
1411 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1412 // unsuccessful.
1413 std::vector<std::unique_ptr<C2Param>> params;
1414 err = mComponent->query({ },
1415 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1416 C2_DONT_BLOCK,
1417 &params);
1418 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1419 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1420 mName, params.size(), asString(err), err);
1421 } else if (err == C2_OK && params.size() == 1) {
1422 C2PortAllocatorsTuning::output *outputAllocators =
1423 C2PortAllocatorsTuning::output::From(params[0].get());
1424 if (outputAllocators && outputAllocators->flexCount() > 0) {
1425 std::shared_ptr<C2Allocator> allocator;
1426 // verify allocator IDs and resolve default allocator
1427 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1428 if (allocator) {
1429 pools->outputAllocatorId = allocator->getId();
1430 } else {
1431 ALOGD("[%s] component requested invalid output allocator ID %u",
1432 mName, outputAllocators->m.values[0]);
1433 }
1434 }
1435 }
1436
1437 // use bufferqueue if outputting to a surface.
1438 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1439 // if unsuccessful.
1440 if (outputSurface) {
1441 params.clear();
1442 err = mComponent->query({ },
1443 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1444 C2_DONT_BLOCK,
1445 &params);
1446 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1447 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1448 mName, params.size(), asString(err), err);
1449 } else if (err == C2_OK && params.size() == 1) {
1450 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1451 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1452 if (surfaceAllocator) {
1453 std::shared_ptr<C2Allocator> allocator;
1454 // verify allocator IDs and resolve default allocator
1455 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1456 if (allocator) {
1457 pools->outputAllocatorId = allocator->getId();
1458 } else {
1459 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1460 mName, surfaceAllocator->value);
1461 err = C2_BAD_VALUE;
1462 }
1463 }
1464 }
1465 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1466 && err != C2_OK
1467 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1468 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1469 }
1470 }
1471
1472 if ((poolMask >> pools->outputAllocatorId) & 1) {
1473 err = mComponent->createBlockPool(
1474 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1475 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1476 mName, pools->outputAllocatorId,
1477 (unsigned long long)pools->outputPoolId,
1478 asString(err));
1479 } else {
1480 err = C2_NOT_FOUND;
1481 }
1482 if (err != C2_OK) {
1483 // use basic pool instead
1484 pools->outputPoolId =
1485 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1486 }
1487
1488 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1489 // component.
1490 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1491 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1492
1493 std::vector<std::unique_ptr<C2SettingResult>> failures;
1494 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1495 ALOGD("[%s] Configured output block pool ids %llu => %s",
1496 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1497 outputPoolId_ = pools->outputPoolId;
1498 }
1499
David Stevensc3fbb282021-01-18 18:11:20 +09001500 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1501 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1502 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1503 if (err != C2_OK) {
1504 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1505 (unsigned long long) prevOutputPoolId, asString(err), err);
1506 }
1507 }
1508
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001509 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001510 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001511 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001512 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001513 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001514 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001515 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001516 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001517 }
1518 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001519 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001520 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001521 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001522
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001523 output->buffers->clearStash();
1524 if (reorderDepth) {
1525 output->buffers->setReorderDepth(reorderDepth.value);
1526 }
1527 if (reorderKey) {
1528 output->buffers->setReorderKey(reorderKey.value);
1529 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001530
1531 // Try to set output surface to created block pool if given.
1532 if (outputSurface) {
1533 mComponent->setOutputSurface(
1534 outputPoolId_,
1535 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001536 outputGeneration,
1537 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001538 } else {
1539 // configure CPU read consumer usage
1540 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1541 std::vector<std::unique_ptr<C2SettingResult>> failures;
1542 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1543 // do not print error message for now as most components may not yet
1544 // support this setting
1545 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1546 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001547 }
1548
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001549 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001550 if (buffersBoundToCodec) {
1551 // WORKAROUND: if we're using early CSD workaround we convert to
1552 // array mode, to appease apps assuming the output
1553 // buffers to be of the same size.
1554 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1555 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001556
1557 int32_t channelCount;
1558 int32_t sampleRate;
1559 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1560 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1561 int32_t delay = 0;
1562 int32_t padding = 0;;
1563 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1564 delay = 0;
1565 }
1566 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1567 padding = 0;
1568 }
1569 if (delay || padding) {
1570 // We need write access to the buffers, and we're already in
1571 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001572 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001573 }
1574 }
1575 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001576
1577 int32_t tunneled = 0;
1578 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1579 tunneled = 0;
1580 }
1581 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001582 }
1583
1584 // Set up pipeline control. This has to be done after mInputBuffers and
1585 // mOutputBuffers are initialized to make sure that lingering callbacks
1586 // about buffers from the previous generation do not interfere with the
1587 // newly initialized pipeline capacity.
1588
Wonsik Kim62545252021-01-20 11:25:41 -08001589 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001590 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001591 watcher->inputDelay(inputDelayValue)
1592 .pipelineDelay(pipelineDelayValue)
1593 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001594 .smoothnessFactor(kSmoothnessFactor);
1595 watcher->flush();
1596 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001597
1598 mInputMetEos = false;
1599 mSync.start();
1600 return OK;
1601}
1602
Wonsik Kim34b28b42022-05-20 15:49:32 -07001603status_t CCodecBufferChannel::prepareInitialInputBuffers(
1604 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001605 if (mInputSurface) {
1606 return OK;
1607 }
1608
Wonsik Kim34b28b42022-05-20 15:49:32 -07001609 size_t numInputSlots = mInput.lock()->numSlots;
1610
1611 {
1612 Mutexed<Input>::Locked input(mInput);
1613 while (clientInputBuffers->size() < numInputSlots) {
1614 size_t index;
1615 sp<MediaCodecBuffer> buffer;
1616 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1617 break;
1618 }
1619 clientInputBuffers->emplace(index, buffer);
1620 }
1621 }
1622 if (clientInputBuffers->empty()) {
1623 ALOGW("[%s] start: cannot allocate memory at all", mName);
1624 return NO_MEMORY;
1625 } else if (clientInputBuffers->size() < numInputSlots) {
1626 ALOGD("[%s] start: cannot allocate memory for all slots, "
1627 "only %zu buffers allocated",
1628 mName, clientInputBuffers->size());
1629 } else {
1630 ALOGV("[%s] %zu initial input buffers available",
1631 mName, clientInputBuffers->size());
1632 }
1633 return OK;
1634}
1635
1636status_t CCodecBufferChannel::requestInitialInputBuffers(
1637 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001638 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001639 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1640 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1641 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001642 return UNKNOWN_ERROR;
1643 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001644
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001645 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1646 mFlushedConfigs.lock()->swap(flushedConfigs);
1647 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001648 {
1649 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1650 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1651 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1652 watcher->onWorkQueued(
1653 work->input.ordinal.frameIndex.peeku(),
1654 std::vector(work->input.buffers),
1655 now);
1656 }
1657 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001658 err = mComponent->queue(&flushedConfigs);
1659 if (err != C2_OK) {
1660 ALOGW("[%s] Error while queueing a flushed config", mName);
1661 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001662 }
1663 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001664 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001665 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1666 !clientInputBuffers.empty()) {
1667 size_t minIndex = clientInputBuffers.begin()->first;
1668 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1669 for (const auto &[index, buffer] : clientInputBuffers) {
1670 if (minBuffer->capacity() > buffer->capacity()) {
1671 minIndex = index;
1672 minBuffer = buffer;
1673 }
1674 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001675 // WORKAROUND: Some apps expect CSD available without queueing
1676 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001677 minBuffer->setRange(0, 0);
1678 minBuffer->meta()->clear();
1679 minBuffer->meta()->setInt64("timeUs", 0);
1680 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001681 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1682 mName);
1683 return UNKNOWN_ERROR;
1684 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001685 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001686 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001687
Wonsik Kim34b28b42022-05-20 15:49:32 -07001688 for (const auto &[index, buffer] : clientInputBuffers) {
1689 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001690 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001691
Pawin Vongmasa36653902018-11-15 00:10:25 -08001692 return OK;
1693}
1694
1695void CCodecBufferChannel::stop() {
1696 mSync.stop();
1697 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001698}
1699
Sungtak Lee99144332023-01-26 11:03:14 +00001700void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
1701 sp<Surface> surface = mOutputSurface.lock()->surface;
1702 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00001703 C2BlockPool::local_id_t outputPoolId;
1704 {
1705 Mutexed<BlockPools>::Locked pools(mBlockPools);
1706 outputPoolId = pools->outputPoolId;
1707 }
1708 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00001709
1710 if (pushBlankBuffer) {
1711 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
1712 if (anw) {
1713 pushBlankBuffersToNativeWindow(anw.get());
1714 }
1715 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00001716 }
1717}
1718
Wonsik Kim936a89c2020-05-08 16:07:50 -07001719void CCodecBufferChannel::reset() {
1720 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001721 if (mInputSurface != nullptr) {
1722 mInputSurface.reset();
1723 }
1724 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001725 {
1726 Mutexed<Input>::Locked input(mInput);
1727 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001728 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001729 }
1730 {
1731 Mutexed<Output>::Locked output(mOutput);
1732 output->buffers.reset();
1733 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001734 // reset the frames that are being tracked for onFrameRendered callbacks
1735 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001736}
1737
1738void CCodecBufferChannel::release() {
1739 mComponent.reset();
1740 mInputAllocator.reset();
1741 mOutputSurface.lock()->surface.clear();
1742 {
1743 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1744 blockPools->inputPool.reset();
1745 blockPools->outputPoolIntf.reset();
1746 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001747 setCrypto(nullptr);
1748 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001749}
1750
Pawin Vongmasa36653902018-11-15 00:10:25 -08001751void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1752 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001753 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001754 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001755 {
1756 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1757 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1758 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1759 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1760 watcher->onWorkDone(frameIndex);
1761 continue;
1762 }
1763 if (work->input.buffers.empty()
1764 || work->input.buffers.front() == nullptr
1765 || work->input.buffers.front()->data().linearBlocks().empty()) {
1766 ALOGD("[%s] no linear codec config data found", mName);
1767 watcher->onWorkDone(frameIndex);
1768 continue;
1769 }
1770 std::unique_ptr<C2Work> copy(new C2Work);
1771 copy->input.flags = C2FrameData::flags_t(
1772 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1773 copy->input.ordinal = work->input.ordinal;
1774 copy->input.ordinal.frameIndex = mFrameIndex++;
1775 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1776 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1777 }
1778 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1779 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1780 }
1781 copy->input.infoBuffers.insert(
1782 copy->input.infoBuffers.begin(),
1783 work->input.infoBuffers.begin(),
1784 work->input.infoBuffers.end());
1785 copy->worklets.emplace_back(new C2Worklet);
1786 configs.push_back(std::move(copy));
1787 watcher->onWorkDone(frameIndex);
1788 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001789 }
1790 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001791 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001792 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001793 Mutexed<Input>::Locked input(mInput);
1794 input->buffers->flush();
1795 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001796 }
1797 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001798 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001799 if (output->buffers) {
1800 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001801 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001802 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001803 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001804 // reset the frames that are being tracked for onFrameRendered callbacks
1805 mTrackedFrames.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001806}
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