blob: d72d228b39d180540fa8d243d9931265911d8e88 [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>
Wonsik Kim3a692e62023-05-19 15:37:22 -070037#include <android-base/parseint.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080038#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080039#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080040#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080041#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070042#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080043#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070044#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080045#include <media/openmax/OMX_Core.h>
46#include <media/stagefright/foundation/ABuffer.h>
47#include <media/stagefright/foundation/ALookup.h>
48#include <media/stagefright/foundation/AMessage.h>
49#include <media/stagefright/foundation/AUtils.h>
50#include <media/stagefright/foundation/hexdump.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080051#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070052#include <media/stagefright/SkipCutBuffer.h>
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010053#include <media/stagefright/SurfaceUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080054#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070055#include <mediadrm/ICrypto.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070056#include <server_configurable_flags/get_flags.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080057#include <system/window.h>
58
59#include "CCodecBufferChannel.h"
60#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080061
62namespace android {
63
64using android::base::StringPrintf;
65using hardware::hidl_handle;
66using hardware::hidl_string;
67using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070068using hardware::fromHeap;
69using hardware::HidlMemory;
70
Pawin Vongmasa36653902018-11-15 00:10:25 -080071using namespace hardware::cas::V1_0;
72using namespace hardware::cas::native::V1_0;
73
74using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070075using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080076
Pawin Vongmasa36653902018-11-15 00:10:25 -080077namespace {
78
Wonsik Kim469c8342019-04-11 16:46:09 -070079constexpr size_t kSmoothnessFactor = 4;
Pawin Vongmasa36653902018-11-15 00:10:25 -080080
Sungtak Leeab6f2f32019-02-15 14:43:51 -080081// This is for keeping IGBP's buffer dropping logic in legacy mode other
82// than making it non-blocking. Do not change this value.
83const static size_t kDequeueTimeoutNs = 0;
84
Pawin Vongmasa36653902018-11-15 00:10:25 -080085} // namespace
86
87CCodecBufferChannel::QueueGuard::QueueGuard(
88 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
89 Mutex::Autolock l(mSync.mGuardLock);
90 // At this point it's guaranteed that mSync is not under state transition,
91 // as we are holding its mutex.
92
93 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
94 if (count->value == -1) {
95 mRunning = false;
96 } else {
97 ++count->value;
98 mRunning = true;
99 }
100}
101
102CCodecBufferChannel::QueueGuard::~QueueGuard() {
103 if (mRunning) {
104 // We are not holding mGuardLock at this point so that QueueSync::stop() can
105 // keep holding the lock until mCount reaches zero.
106 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
107 --count->value;
108 count->cond.broadcast();
109 }
110}
111
112void CCodecBufferChannel::QueueSync::start() {
113 Mutex::Autolock l(mGuardLock);
114 // If stopped, it goes to running state; otherwise no-op.
115 Mutexed<Counter>::Locked count(mCount);
116 if (count->value == -1) {
117 count->value = 0;
118 }
119}
120
121void CCodecBufferChannel::QueueSync::stop() {
122 Mutex::Autolock l(mGuardLock);
123 Mutexed<Counter>::Locked count(mCount);
124 if (count->value == -1) {
125 // no-op
126 return;
127 }
128 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
129 // mCount can only decrement. In other words, threads that acquired the lock
130 // are allowed to finish execution but additional threads trying to acquire
131 // the lock at this point will block, and then get QueueGuard at STOPPED
132 // state.
133 while (count->value != 0) {
134 count.waitForCondition(count->cond);
135 }
136 count->value = -1;
137}
138
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700139// Input
140
141CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
142
Pawin Vongmasa36653902018-11-15 00:10:25 -0800143// CCodecBufferChannel
144
145CCodecBufferChannel::CCodecBufferChannel(
146 const std::shared_ptr<CCodecCallback> &callback)
147 : mHeapSeqNum(-1),
148 mCCodecCallback(callback),
149 mFrameIndex(0u),
150 mFirstValidFrameIndex(0u),
Brian Lindahl2048d492023-04-05 08:49:23 -0600151 mIsSurfaceToDisplay(false),
152 mHasPresentFenceTimes(false),
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700153 mRenderingDepth(3u),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800154 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700155 mInputMetEos(false),
156 mSendEncryptedInfoBuffer(false) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700157 {
158 Mutexed<Input>::Locked input(mInput);
159 input->buffers.reset(new DummyInputBuffers(""));
160 input->extraBuffers.flush();
161 input->inputDelay = 0u;
162 input->pipelineDelay = 0u;
163 input->numSlots = kSmoothnessFactor;
164 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700165 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700166 }
167 {
168 Mutexed<Output>::Locked output(mOutput);
169 output->outputDelay = 0u;
170 output->numSlots = kSmoothnessFactor;
Wonsik Kim3722abc2023-05-17 13:26:31 -0700171 output->bounded = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700172 }
David Stevensc3fbb282021-01-18 18:11:20 +0900173 {
174 Mutexed<BlockPools>::Locked pools(mBlockPools);
175 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
176 }
Wonsik Kim3a692e62023-05-19 15:37:22 -0700177 std::string value = server_configurable_flags::GetServerConfigurableFlag(
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700178 "media_native", "ccodec_rendering_depth", "3");
Wonsik Kim3a692e62023-05-19 15:37:22 -0700179 android::base::ParseInt(value, &mRenderingDepth);
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700180 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800181}
182
183CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800184 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800185 mCrypto->unsetHeap(mHeapSeqNum);
186 }
187}
188
189void CCodecBufferChannel::setComponent(
190 const std::shared_ptr<Codec2Client::Component> &component) {
191 mComponent = component;
192 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
193 mName = mComponentName.c_str();
194}
195
196status_t CCodecBufferChannel::setInputSurface(
197 const std::shared_ptr<InputSurfaceWrapper> &surface) {
198 ALOGV("[%s] setInputSurface", mName);
199 mInputSurface = surface;
200 return mInputSurface->connect(mComponent);
201}
202
203status_t CCodecBufferChannel::signalEndOfInputStream() {
204 if (mInputSurface == nullptr) {
205 return INVALID_OPERATION;
206 }
207 return mInputSurface->signalEndOfInputStream();
208}
209
Sungtak Lee04b30352020-07-27 13:57:25 -0700210status_t CCodecBufferChannel::queueInputBufferInternal(
211 sp<MediaCodecBuffer> buffer,
212 std::shared_ptr<C2LinearBlock> encryptedBlock,
213 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800214 int64_t timeUs;
215 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
216
217 if (mInputMetEos) {
218 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
219 return OK;
220 }
221
222 int32_t flags = 0;
223 int32_t tmp = 0;
224 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200225 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800226 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
227 eos = true;
228 mInputMetEos = true;
229 ALOGV("[%s] input EOS", mName);
230 }
231 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
232 flags |= C2FrameData::FLAG_CODEC_CONFIG;
233 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200234 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
235 tunnelFirstFrame = true;
236 }
Marc Kassis96343b42022-12-09 11:49:44 +0100237 if (buffer->meta()->findInt32("decode-only", &tmp) && tmp) {
238 flags |= C2FrameData::FLAG_DROP_FRAME;
239 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800240 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800241 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800242 std::unique_ptr<C2Work> work(new C2Work);
243 work->input.ordinal.timestamp = timeUs;
244 work->input.ordinal.frameIndex = mFrameIndex++;
245 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
246 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
247 // Keep client timestamp in customOrdinal
248 work->input.ordinal.customOrdinal = timeUs;
249 work->input.buffers.clear();
250
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700251 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800252 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800253
Pawin Vongmasa36653902018-11-15 00:10:25 -0800254 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700255 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800256 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700257 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800258 return -ENOENT;
259 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700260 // TODO: we want to delay copying buffers.
261 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
262 copy = input->buffers->cloneAndReleaseBuffer(buffer);
263 if (copy != nullptr) {
264 (void)input->extraBuffers.assignSlot(copy);
265 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
266 return UNKNOWN_ERROR;
267 }
268 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
269 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
270 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700271 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700272 } else {
273 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
274 "buffer starvation on component.", mName);
275 }
276 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800277 if (input->frameReassembler) {
278 usesFrameReassembler = true;
279 input->frameReassembler.process(buffer, &items);
280 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900281 int32_t cvo = 0;
282 if (buffer->meta()->findInt32("cvo", &cvo)) {
283 int32_t rotation = cvo % 360;
284 // change rotation to counter-clock wise.
285 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
286
287 Mutexed<OutputSurface>::Locked output(mOutputSurface);
288 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
289 output->rotation[frameIndex] = rotation;
290 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800291 work->input.buffers.push_back(c2buffer);
292 if (encryptedBlock) {
293 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
294 kParamIndexEncryptedBuffer,
295 encryptedBlock->share(0, blockSize, C2Fence())));
296 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700297 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800298 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700299 Mutexed<Input>::Locked input(mInput);
300 if (input->frameReassembler) {
301 usesFrameReassembler = true;
302 // drain any pending items with eos
303 input->frameReassembler.process(buffer, &items);
304 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800305 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800306 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800307 if (usesFrameReassembler) {
308 if (!items.empty()) {
309 items.front()->input.configUpdate = std::move(mParamsToBeSet);
310 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
311 }
312 } else {
313 work->input.flags = (C2FrameData::flags_t)flags;
314 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800315
Wonsik Kime1104ca2020-11-24 15:01:33 -0800316 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200317 if (tunnelFirstFrame) {
318 C2StreamTunnelHoldRender::input tunnelHoldRender{
319 0u /* stream */,
320 C2_TRUE /* value */
321 };
322 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
323 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800324 work->worklets.clear();
325 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800326
Wonsik Kime1104ca2020-11-24 15:01:33 -0800327 items.push_back(std::move(work));
328
329 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800330 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800331 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800332 work.reset(new C2Work);
333 work->input.ordinal.timestamp = timeUs;
334 work->input.ordinal.frameIndex = mFrameIndex++;
335 // WORKAROUND: keep client timestamp in customOrdinal
336 work->input.ordinal.customOrdinal = timeUs;
337 work->input.buffers.clear();
338 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800339 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800340 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800341 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800342 c2_status_t err = C2_OK;
343 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700344 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
345 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800346 {
347 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
348 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
349 for (const std::unique_ptr<C2Work> &work : items) {
350 watcher->onWorkQueued(
351 work->input.ordinal.frameIndex.peeku(),
352 std::vector(work->input.buffers),
353 now);
354 }
355 }
356 err = mComponent->queue(&items);
357 }
358 if (err != C2_OK) {
359 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
360 for (const std::unique_ptr<C2Work> &work : items) {
361 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
362 }
363 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700364 Mutexed<Input>::Locked input(mInput);
365 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700366 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700367 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700368 } else if (buffer) {
369 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700370 }
371 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
372 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800373 }
374
375 feedInputBufferIfAvailableInternal();
376 return err;
377}
378
379status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
380 QueueGuard guard(mSync);
381 if (!guard.isRunning()) {
382 ALOGD("[%s] setParameters is only supported in the running state.", mName);
383 return -ENOSYS;
384 }
385 mParamsToBeSet.insert(mParamsToBeSet.end(),
386 std::make_move_iterator(params.begin()),
387 std::make_move_iterator(params.end()));
388 params.clear();
389 return OK;
390}
391
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800392status_t CCodecBufferChannel::attachBuffer(
393 const std::shared_ptr<C2Buffer> &c2Buffer,
394 const sp<MediaCodecBuffer> &buffer) {
395 if (!buffer->copy(c2Buffer)) {
396 return -ENOSYS;
397 }
398 return OK;
399}
400
401void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
402 if (!mDecryptDestination || mDecryptDestination->size() < size) {
403 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
404 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
405 mCrypto->unsetHeap(mHeapSeqNum);
406 }
407 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
408 if (mCrypto) {
409 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
410 }
411 }
412}
413
414int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
415 CHECK(mCrypto);
416 auto it = mHeapSeqNumMap.find(memory);
417 int32_t heapSeqNum = -1;
418 if (it == mHeapSeqNumMap.end()) {
419 heapSeqNum = mCrypto->setHeap(memory);
420 mHeapSeqNumMap.emplace(memory, heapSeqNum);
421 } else {
422 heapSeqNum = it->second;
423 }
424 return heapSeqNum;
425}
426
427status_t CCodecBufferChannel::attachEncryptedBuffer(
428 const sp<hardware::HidlMemory> &memory,
429 bool secure,
430 const uint8_t *key,
431 const uint8_t *iv,
432 CryptoPlugin::Mode mode,
433 CryptoPlugin::Pattern pattern,
434 size_t offset,
435 const CryptoPlugin::SubSample *subSamples,
436 size_t numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000437 const sp<MediaCodecBuffer> &buffer,
438 AString* errorDetailMsg) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800439 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
440 static const C2MemoryUsage kDefaultReadWriteUsage{
441 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
442
443 size_t size = 0;
444 for (size_t i = 0; i < numSubSamples; ++i) {
445 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
446 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700447 if (size == 0) {
448 buffer->setRange(0, 0);
449 return OK;
450 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800451 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
452 std::shared_ptr<C2LinearBlock> block;
453 c2_status_t err = pool->fetchLinearBlock(
454 size,
455 secure ? kSecureUsage : kDefaultReadWriteUsage,
456 &block);
457 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700458 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
459 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800460 return NO_MEMORY;
461 }
462 if (!secure) {
463 ensureDecryptDestination(size);
464 }
465 ssize_t result = -1;
466 ssize_t codecDataOffset = 0;
467 if (mCrypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800468 int32_t heapSeqNum = getHeapSeqNum(memory);
469 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
470 hardware::drm::V1_0::DestinationBuffer dst;
471 if (secure) {
472 dst.type = DrmBufferType::NATIVE_HANDLE;
473 dst.secureMemory = hardware::hidl_handle(block->handle());
474 } else {
475 dst.type = DrmBufferType::SHARED_MEMORY;
476 IMemoryToSharedBuffer(
477 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
478 }
479 result = mCrypto->decrypt(
480 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000481 dst, errorDetailMsg);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800482 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700483 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800484 return result;
485 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800486 } else {
487 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
488 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
489 hidl_vec<SubSample> hidlSubSamples;
490 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
491
492 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
493 hardware::cas::native::V1_0::DestinationBuffer dst;
494 if (secure) {
495 dst.type = BufferType::NATIVE_HANDLE;
496 dst.secureMemory = hardware::hidl_handle(block->handle());
497 } else {
498 dst.type = BufferType::SHARED_MEMORY;
499 dst.nonsecureMemory = src;
500 }
501
502 CasStatus status = CasStatus::OK;
503 hidl_string detailedError;
504 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
505
506 if (key != nullptr) {
507 sctrl = (ScramblingControl)key[0];
508 // Adjust for the PES offset
509 codecDataOffset = key[2] | (key[3] << 8);
510 }
511
512 auto returnVoid = mDescrambler->descramble(
513 sctrl,
514 hidlSubSamples,
515 src,
516 0,
517 dst,
518 0,
519 [&status, &result, &detailedError] (
520 CasStatus _status, uint32_t _bytesWritten,
521 const hidl_string& _detailedError) {
522 status = _status;
523 result = (ssize_t)_bytesWritten;
524 detailedError = _detailedError;
525 });
Arun Johnson634d0802023-02-14 22:07:51 +0000526 if (errorDetailMsg) {
527 errorDetailMsg->setTo(detailedError.c_str(), detailedError.size());
528 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800529 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
530 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
531 mName, returnVoid.description().c_str(), status, result);
532 return UNKNOWN_ERROR;
533 }
534
535 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700536 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
537 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800538 return BAD_VALUE;
539 }
540 }
541 if (!secure) {
542 C2WriteView view = block->map().get();
543 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700544 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
545 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800546 return UNKNOWN_ERROR;
547 }
548 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700549 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
550 "(non-secure)",
551 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800552 return UNKNOWN_ERROR;
553 }
554 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
555 }
556 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
557 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
558 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700559 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800560 return -ENOSYS;
561 }
562 return OK;
563}
564
Pawin Vongmasa36653902018-11-15 00:10:25 -0800565status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
566 QueueGuard guard(mSync);
567 if (!guard.isRunning()) {
568 ALOGD("[%s] No more buffers should be queued at current state.", mName);
569 return -ENOSYS;
570 }
571 return queueInputBufferInternal(buffer);
572}
573
574status_t CCodecBufferChannel::queueSecureInputBuffer(
575 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
576 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
577 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
578 AString *errorDetailMsg) {
579 QueueGuard guard(mSync);
580 if (!guard.isRunning()) {
581 ALOGD("[%s] No more buffers should be queued at current state.", mName);
582 return -ENOSYS;
583 }
584
585 if (!hasCryptoOrDescrambler()) {
586 return -ENOSYS;
587 }
588 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
589
Sungtak Lee04b30352020-07-27 13:57:25 -0700590 std::shared_ptr<C2LinearBlock> block;
591 size_t allocSize = buffer->size();
592 size_t bufferSize = 0;
593 c2_status_t blockRes = C2_OK;
594 bool copied = false;
595 if (mSendEncryptedInfoBuffer) {
596 static const C2MemoryUsage kDefaultReadWriteUsage{
597 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
598 constexpr int kAllocGranule0 = 1024 * 64;
599 constexpr int kAllocGranule1 = 1024 * 1024;
600 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
601 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
602 if (allocSize <= kAllocGranule1) {
603 bufferSize = align(allocSize, kAllocGranule0);
604 } else {
605 bufferSize = align(allocSize, kAllocGranule1);
606 }
607 blockRes = pool->fetchLinearBlock(
608 bufferSize, kDefaultReadWriteUsage, &block);
609
610 if (blockRes == C2_OK) {
611 C2WriteView view = block->map().get();
612 if (view.error() == C2_OK && view.size() == bufferSize) {
613 copied = true;
614 // TODO: only copy clear sections
615 memcpy(view.data(), buffer->data(), allocSize);
616 }
617 }
618 }
619
620 if (!copied) {
621 block.reset();
622 }
623
Pawin Vongmasa36653902018-11-15 00:10:25 -0800624 ssize_t result = -1;
625 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700626 if (numSubSamples == 1
627 && subSamples[0].mNumBytesOfClearData == 0
628 && subSamples[0].mNumBytesOfEncryptedData == 0) {
629 // We don't need to go through crypto or descrambler if the input is empty.
630 result = 0;
631 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700632 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800633 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700634 destination.type = DrmBufferType::NATIVE_HANDLE;
635 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800636 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700637 destination.type = DrmBufferType::SHARED_MEMORY;
638 IMemoryToSharedBuffer(
639 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800640 }
Robert Shih895fba92019-07-16 16:29:44 -0700641 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800642 encryptedBuffer->fillSourceBuffer(&source);
643 result = mCrypto->decrypt(
644 key, iv, mode, pattern, source, buffer->offset(),
645 subSamples, numSubSamples, destination, errorDetailMsg);
646 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700647 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800648 return result;
649 }
Robert Shih895fba92019-07-16 16:29:44 -0700650 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800651 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
652 }
653 } else {
654 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
655 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
656 hidl_vec<SubSample> hidlSubSamples;
657 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
658
659 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
660 encryptedBuffer->fillSourceBuffer(&srcBuffer);
661
662 DestinationBuffer dstBuffer;
663 if (secure) {
664 dstBuffer.type = BufferType::NATIVE_HANDLE;
665 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
666 } else {
667 dstBuffer.type = BufferType::SHARED_MEMORY;
668 dstBuffer.nonsecureMemory = srcBuffer;
669 }
670
671 CasStatus status = CasStatus::OK;
672 hidl_string detailedError;
673 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
674
675 if (key != nullptr) {
676 sctrl = (ScramblingControl)key[0];
677 // Adjust for the PES offset
678 codecDataOffset = key[2] | (key[3] << 8);
679 }
680
681 auto returnVoid = mDescrambler->descramble(
682 sctrl,
683 hidlSubSamples,
684 srcBuffer,
685 0,
686 dstBuffer,
687 0,
688 [&status, &result, &detailedError] (
689 CasStatus _status, uint32_t _bytesWritten,
690 const hidl_string& _detailedError) {
691 status = _status;
692 result = (ssize_t)_bytesWritten;
693 detailedError = _detailedError;
694 });
695
696 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
697 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
698 mName, returnVoid.description().c_str(), status, result);
699 return UNKNOWN_ERROR;
700 }
701
702 if (result < codecDataOffset) {
703 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
704 return BAD_VALUE;
705 }
706
707 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
708
709 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
710 encryptedBuffer->copyDecryptedContentFromMemory(result);
711 }
712 }
713
714 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700715
716 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800717}
718
719void CCodecBufferChannel::feedInputBufferIfAvailable() {
720 QueueGuard guard(mSync);
721 if (!guard.isRunning()) {
722 ALOGV("[%s] We're not running --- no input buffer reported", mName);
723 return;
724 }
725 feedInputBufferIfAvailableInternal();
726}
727
728void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900729 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800730 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700731 }
732 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700733 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700734 if (!output->buffers ||
735 output->buffers->hasPending() ||
Wonsik Kim3722abc2023-05-17 13:26:31 -0700736 (!output->bounded && output->buffers->numActiveSlots() >= output->numSlots)) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800737 return;
738 }
739 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700740 size_t numActiveSlots = 0;
741 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800742 sp<MediaCodecBuffer> inBuffer;
743 size_t index;
744 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700745 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700746 numActiveSlots = input->buffers->numActiveSlots();
747 if (numActiveSlots >= input->numSlots) {
748 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800749 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700750 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800751 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800752 break;
753 }
754 }
755 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
756 mCallback->onInputBufferAvailable(index, inBuffer);
757 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700758 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759}
760
761status_t CCodecBufferChannel::renderOutputBuffer(
762 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800763 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800764 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800765 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800766 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700767 Mutexed<Output>::Locked output(mOutput);
768 if (output->buffers) {
769 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800770 }
771 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800772 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
773 // set to true.
774 sendOutputBuffers();
775 // input buffer feeding may have been gated by pending output buffers
776 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800777 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800778 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700779 std::call_once(mRenderWarningFlag, [this] {
780 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
781 "timestamp or render=true with non-video buffers. Apps should "
782 "call releaseOutputBuffer() with render=false for those.",
783 mName);
784 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800785 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800786 return INVALID_OPERATION;
787 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800788
789#if 0
790 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
791 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
792 for (const std::shared_ptr<const C2Info> &info : infoParams) {
793 AString res;
794 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
795 if (ix) res.append(", ");
796 res.append(*((int32_t*)info.get() + (ix / 4)));
797 }
798 ALOGV(" [%s]", res.c_str());
799 }
800#endif
801 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
802 std::static_pointer_cast<const C2StreamRotationInfo::output>(
803 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
804 bool flip = rotation && (rotation->flip & 1);
805 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900806
807 {
808 Mutexed<OutputSurface>::Locked output(mOutputSurface);
809 if (output->surface == nullptr) {
810 ALOGI("[%s] cannot render buffer without surface", mName);
811 return OK;
812 }
813 int64_t frameIndex;
814 buffer->meta()->findInt64("frameIndex", &frameIndex);
815 if (output->rotation.count(frameIndex) != 0) {
816 auto it = output->rotation.find(frameIndex);
817 quarters = (it->second / 90) & 3;
818 output->rotation.erase(it);
819 }
820 }
821
Pawin Vongmasa36653902018-11-15 00:10:25 -0800822 uint32_t transform = 0;
823 switch (quarters) {
824 case 0: // no rotation
825 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
826 break;
827 case 1: // 90 degrees counter-clockwise
828 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
829 : HAL_TRANSFORM_ROT_270;
830 break;
831 case 2: // 180 degrees
832 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
833 break;
834 case 3: // 90 degrees clockwise
835 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
836 : HAL_TRANSFORM_ROT_90;
837 break;
838 }
839
840 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
841 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
842 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
843 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
844 if (surfaceScaling) {
845 videoScalingMode = surfaceScaling->value;
846 }
847
848 // Use dataspace from format as it has the default aspects already applied
849 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
850 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
851
852 // HDR static info
853 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
854 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
855 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
856
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800857 // HDR10 plus info
858 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
859 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
860 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800861 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
862 hdr10PlusInfo.reset();
863 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800864
Wonsik Kima79c5522022-01-18 16:29:24 -0800865 // HDR dynamic info
866 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
867 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
868 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
869 // TODO: make this sticky & enable unset
870 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
871 hdrDynamicInfo.reset();
872 }
873
874 if (hdr10PlusInfo) {
875 // C2StreamHdr10PlusInfo is deprecated; components should use
876 // C2StreamHdrDynamicMetadataInfo
877 // TODO: #metric
878 if (hdrDynamicInfo) {
879 // It is unexpected that C2StreamHdr10PlusInfo and
880 // C2StreamHdrDynamicMetadataInfo is both present.
881 // C2StreamHdrDynamicMetadataInfo takes priority.
882 // TODO: #metric
883 } else {
884 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
885 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
886 hdr10PlusInfo->flexCount(),
887 0u,
888 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
889 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
890 hdrDynamicInfo = info;
891 }
892 }
893
Pawin Vongmasa36653902018-11-15 00:10:25 -0800894 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
895 if (blocks.size() != 1u) {
896 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
897 return UNKNOWN_ERROR;
898 }
899 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700900 C2Fence c2fence = block.fence();
901 sp<Fence> fence = Fence::NO_FENCE;
902 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
903 // Once C2Fence::type() is added, check the exact C2Fence type
904 if (c2fence.isHW()) {
905 int fenceFd = c2fence.fd();
906 fence = sp<Fence>::make(fenceFd);
907 if (!fence) {
908 ALOGE("[%s] Failed to allocate a fence", mName);
909 close(fenceFd);
910 return NO_MEMORY;
911 }
912 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800913
914 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -0700915 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800916 timestampNs,
917 false, // droppable
918 dataSpace,
919 Rect(blocks.front().crop().left,
920 blocks.front().crop().top,
921 blocks.front().crop().right(),
922 blocks.front().crop().bottom()),
923 videoScalingMode,
924 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700925 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800926 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800927 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800928 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800929 // If mastering max and min luminance fields are 0, do not use them.
930 // It indicates the value may not be present in the stream.
931 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
932 hdrStaticInfo->mastering.minLuminance > 0.0f) {
933 struct android_smpte2086_metadata smpte2086_meta = {
934 .displayPrimaryRed = {
935 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
936 },
937 .displayPrimaryGreen = {
938 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
939 },
940 .displayPrimaryBlue = {
941 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
942 },
943 .whitePoint = {
944 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
945 },
946 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
947 .minLuminance = hdrStaticInfo->mastering.minLuminance,
948 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800949 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800950 hdr.smpte2086 = smpte2086_meta;
951 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700952 // If the content light level fields are 0, do not use them, it
953 // indicates the value may not be present in the stream.
954 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
955 struct android_cta861_3_metadata cta861_meta = {
956 .maxContentLightLevel = hdrStaticInfo->maxCll,
957 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
958 };
959 hdr.validTypes |= HdrMetadata::CTA861_3;
960 hdr.cta8613 = cta861_meta;
961 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900962
963 // does not have valid info
964 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
965 hdrStaticInfo.reset();
966 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800967 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800968 if (hdrDynamicInfo
969 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800970 hdr.validTypes |= HdrMetadata::HDR10PLUS;
971 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800972 hdrDynamicInfo->m.data,
973 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800974 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800975 qbi.setHdrMetadata(hdr);
976 }
Hongguangfc1478a2022-07-20 22:56:06 -0700977 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
978
Brian Lindahl932bf602023-03-09 11:59:48 -0700979 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
980 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
981 IGraphicBufferProducer::QueueBufferOutput qbo;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800982 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
983 if (result != OK) {
984 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800985 if (result == NO_INIT) {
986 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
987 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800988 return result;
989 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800990
991 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
992 ALOGD("[%s] queue buffer successful", mName);
993 } else {
994 ALOGV("[%s] queue buffer successful", mName);
995 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800996
997 int64_t mediaTimeUs = 0;
998 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahl2048d492023-04-05 08:49:23 -0600999 if (mIsSurfaceToDisplay) {
1000 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
1001 processRenderedFrames(qbo.frameTimestamps);
1002 } else {
1003 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
1004 // when the frame is queued to the non-display surface
1005 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1006 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001007
1008 return OK;
1009}
1010
Brian Lindahl932bf602023-03-09 11:59:48 -07001011void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001012 mTrackedFrames.clear();
1013
1014 int isSurfaceToDisplay = 0;
1015 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1016 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1017 // No frame tracking is needed if we're not sending frames to the display
1018 if (!mIsSurfaceToDisplay) {
1019 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1020 return;
1021 }
1022
Brian Lindahl932bf602023-03-09 11:59:48 -07001023 int hasPresentFenceTimes = 0;
1024 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1025 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
Brian Lindahl119e0c22023-05-19 15:42:13 -06001026 if (!mHasPresentFenceTimes) {
Brian Lindahl932bf602023-03-09 11:59:48 -07001027 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1028 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001029}
1030
1031void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1032 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1033 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1034 // so track the frame as if the desired render time is now.
1035 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1036 if (desiredRenderTimeNs < nowNs) {
1037 desiredRenderTimeNs = nowNs;
1038 }
1039 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1040 // actually rendered.
1041 TrackedFrame frame;
1042 frame.number = qbo.nextFrameNumber - 1;
1043 frame.mediaTimeUs = mediaTimeUs;
1044 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1045 frame.latchTime = -1;
1046 frame.presentFence = nullptr;
1047 mTrackedFrames.push_back(frame);
1048}
1049
1050void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1051 // Grab the latch times and present fences from the frame event deltas
1052 for (const auto& delta : deltas) {
1053 for (auto& frame : mTrackedFrames) {
1054 if (delta.getFrameNumber() == frame.number) {
1055 delta.getLatchTime(&frame.latchTime);
1056 delta.getDisplayPresentFence(&frame.presentFence);
1057 }
1058 }
1059 }
1060
1061 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1062 // in fact, been rendered.
1063 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1064 while (!mTrackedFrames.empty()) {
1065 TrackedFrame & frame = mTrackedFrames.front();
1066 // Frames that should have been rendered at least 100ms in the past are checked
1067 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1068 break;
1069 }
1070
1071 // If we don't have a render time by now, then consider the frame as dropped
1072 int64_t renderTimeNs = getRenderTimeNs(frame);
1073 if (renderTimeNs != -1) {
1074 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1075 }
1076 mTrackedFrames.pop_front();
1077 }
1078}
1079
1080int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1081 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1082 if (!mHasPresentFenceTimes) {
1083 if (frame.latchTime == -1) {
1084 ALOGD("no latch time for frame %d", (int) frame.number);
1085 return -1;
1086 }
1087 return frame.latchTime;
1088 }
1089
1090 if (frame.presentFence == nullptr) {
1091 ALOGW("no present fence for frame %d", (int) frame.number);
1092 return -1;
1093 }
1094
1095 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1096
1097 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1098 ALOGW("invalid signal time for frame %d", (int) frame.number);
1099 return -1;
1100 }
1101
1102 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1103 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1104 return -1;
1105 }
1106
1107 return actualRenderTimeNs;
1108}
1109
1110void CCodecBufferChannel::pollForRenderedBuffers() {
1111 FrameEventHistoryDelta delta;
1112 mComponent->pollForRenderedFrames(&delta);
1113 processRenderedFrames(delta);
1114}
1115
Pawin Vongmasa36653902018-11-15 00:10:25 -08001116status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1117 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1118 bool released = false;
1119 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001120 Mutexed<Input>::Locked input(mInput);
1121 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001122 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001123 }
1124 }
1125 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001126 Mutexed<Output>::Locked output(mOutput);
1127 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001128 released = true;
1129 }
1130 }
1131 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001132 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001133 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001134 } else {
1135 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1136 }
1137 return OK;
1138}
1139
1140void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1141 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001142 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001143
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001144 if (!input->buffers) {
1145 ALOGE("getInputBufferArray: No Input Buffers allocated");
1146 return;
1147 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001148 if (!input->buffers->isArrayMode()) {
1149 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001150 }
1151
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001152 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001153}
1154
1155void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1156 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001157 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001158 if (!output->buffers) {
1159 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1160 return;
1161 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001162 if (!output->buffers->isArrayMode()) {
1163 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001164 }
1165
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001166 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001167}
1168
1169status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001170 const sp<AMessage> &inputFormat,
1171 const sp<AMessage> &outputFormat,
1172 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001173 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1174 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001175 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001176 C2PortReorderBufferDepthTuning::output reorderDepth;
1177 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001178 C2PortActualDelayTuning::input inputDelay(0);
1179 C2PortActualDelayTuning::output outputDelay(0);
1180 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001181 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001182
Pawin Vongmasa36653902018-11-15 00:10:25 -08001183 c2_status_t err = mComponent->query(
1184 {
1185 &iStreamFormat,
1186 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001187 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001188 &reorderDepth,
1189 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001190 &inputDelay,
1191 &pipelineDelay,
1192 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001193 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001194 },
1195 {},
1196 C2_DONT_BLOCK,
1197 nullptr);
1198 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001199 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001200 return UNKNOWN_ERROR;
1201 }
1202 } else if (err != C2_OK) {
1203 return UNKNOWN_ERROR;
1204 }
1205
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001206 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1207 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1208 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1209
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001210 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1211 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001212
Pawin Vongmasa36653902018-11-15 00:10:25 -08001213 // TODO: get this from input format
1214 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1215
Sungtak Lee04b30352020-07-27 13:57:25 -07001216 // secure mode is a static parameter (shall not change in the executing state)
1217 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1218
Pawin Vongmasa36653902018-11-15 00:10:25 -08001219 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001220 int poolMask = GetCodec2PoolMask();
1221 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001222
1223 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001224 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001225 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001226 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1227 API_REFLECTION |
1228 API_VALUES |
1229 API_CURRENT_VALUES |
1230 API_DEPENDENCY |
1231 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001232 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1233 C2StreamSampleRateInfo::input sampleRate(0u);
1234 C2StreamChannelCountInfo::input channelCount(0u);
1235 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001236 std::shared_ptr<C2BlockPool> pool;
1237 {
1238 Mutexed<BlockPools>::Locked pools(mBlockPools);
1239
1240 // set default allocator ID.
1241 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001242 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001243
1244 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1245 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1246 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001247 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001248 std::vector<C2Param *> stackParams({&featuresSetting});
1249 if (audioEncoder) {
1250 stackParams.push_back(&encoderFrameSize);
1251 stackParams.push_back(&sampleRate);
1252 stackParams.push_back(&channelCount);
1253 stackParams.push_back(&pcmEncoding);
1254 } else {
1255 encoderFrameSize.invalidate();
1256 sampleRate.invalidate();
1257 channelCount.invalidate();
1258 pcmEncoding.invalidate();
1259 }
1260 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001261 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1262 C2_DONT_BLOCK,
1263 &params);
1264 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1265 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1266 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001267 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001268 C2PortAllocatorsTuning::input *inputAllocators =
1269 C2PortAllocatorsTuning::input::From(params[0].get());
1270 if (inputAllocators && inputAllocators->flexCount() > 0) {
1271 std::shared_ptr<C2Allocator> allocator;
1272 // verify allocator IDs and resolve default allocator
1273 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1274 if (allocator) {
1275 pools->inputAllocatorId = allocator->getId();
1276 } else {
1277 ALOGD("[%s] component requested invalid input allocator ID %u",
1278 mName, inputAllocators->m.values[0]);
1279 }
1280 }
1281 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001282 if (featuresSetting) {
1283 apiFeatures = featuresSetting.value;
1284 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001285
1286 // TODO: use C2Component wrapper to associate this pool with ourselves
1287 if ((poolMask >> pools->inputAllocatorId) & 1) {
1288 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1289 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1290 mName, pools->inputAllocatorId,
1291 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1292 asString(err), err);
1293 } else {
1294 err = C2_NOT_FOUND;
1295 }
1296 if (err != C2_OK) {
1297 C2BlockPool::local_id_t inputPoolId =
1298 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1299 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1300 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1301 mName, (unsigned long long)inputPoolId,
1302 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1303 asString(err), err);
1304 if (err != C2_OK) {
1305 return NO_MEMORY;
1306 }
1307 }
1308 pools->inputPool = pool;
1309 }
1310
Wonsik Kim51051262018-11-28 13:59:05 -08001311 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001312 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001313 input->inputDelay = inputDelayValue;
1314 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001315 input->numSlots = numInputSlots;
1316 input->extraBuffers.flush();
1317 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001318 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001319 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1320 input->frameReassembler.init(
1321 pool,
1322 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1323 encoderFrameSize.value,
1324 sampleRate.value,
1325 channelCount.value,
1326 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1327 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001328 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1329 // For encrypted content, framework decrypts source buffer (ashmem) into
1330 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001331 if (!buffersBoundToCodec
1332 && !input->frameReassembler
1333 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001334 input->buffers.reset(new SlotInputBuffers(mName));
1335 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001336 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001337 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001338 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001339 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001340 // This is to ensure buffers do not get released prematurely.
1341 // TODO: handle this without going into array mode
1342 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001343 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001344 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001345 }
1346 } else {
1347 if (hasCryptoOrDescrambler()) {
1348 int32_t capacity = kLinearBufferSize;
1349 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1350 if ((size_t)capacity > kMaxLinearBufferSize) {
1351 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1352 capacity = kMaxLinearBufferSize;
1353 }
1354 if (mDealer == nullptr) {
1355 mDealer = new MemoryDealer(
1356 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001357 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001358 "EncryptedLinearInputBuffers");
1359 mDecryptDestination = mDealer->allocate((size_t)capacity);
1360 }
1361 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001362 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1363 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001364 } else {
1365 mHeapSeqNum = -1;
1366 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001367 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001368 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001369 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001370 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001371 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001372 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001373 }
1374 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001375 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001376
1377 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001378 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001379 } else {
1380 // TODO: error
1381 }
Wonsik Kim51051262018-11-28 13:59:05 -08001382
1383 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001384 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001385 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001386 }
1387
1388 if (outputFormat != nullptr) {
1389 sp<IGraphicBufferProducer> outputSurface;
1390 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001391 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001392 {
1393 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001394 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001395 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001396 outputSurface = output->surface ?
1397 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001398 if (outputSurface) {
1399 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1400 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001401 outputGeneration = output->generation;
1402 }
1403
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001404 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001405 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001406 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001407
1408 {
1409 Mutexed<BlockPools>::Locked pools(mBlockPools);
1410
David Stevensc3fbb282021-01-18 18:11:20 +09001411 prevOutputPoolId = pools->outputPoolId;
1412
Pawin Vongmasa36653902018-11-15 00:10:25 -08001413 // set default allocator ID.
1414 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001415 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001416
1417 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1418 // unsuccessful.
1419 std::vector<std::unique_ptr<C2Param>> params;
1420 err = mComponent->query({ },
1421 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1422 C2_DONT_BLOCK,
1423 &params);
1424 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1425 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1426 mName, params.size(), asString(err), err);
1427 } else if (err == C2_OK && params.size() == 1) {
1428 C2PortAllocatorsTuning::output *outputAllocators =
1429 C2PortAllocatorsTuning::output::From(params[0].get());
1430 if (outputAllocators && outputAllocators->flexCount() > 0) {
1431 std::shared_ptr<C2Allocator> allocator;
1432 // verify allocator IDs and resolve default allocator
1433 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1434 if (allocator) {
1435 pools->outputAllocatorId = allocator->getId();
1436 } else {
1437 ALOGD("[%s] component requested invalid output allocator ID %u",
1438 mName, outputAllocators->m.values[0]);
1439 }
1440 }
1441 }
1442
1443 // use bufferqueue if outputting to a surface.
1444 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1445 // if unsuccessful.
1446 if (outputSurface) {
1447 params.clear();
1448 err = mComponent->query({ },
1449 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1450 C2_DONT_BLOCK,
1451 &params);
1452 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1453 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1454 mName, params.size(), asString(err), err);
1455 } else if (err == C2_OK && params.size() == 1) {
1456 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1457 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1458 if (surfaceAllocator) {
1459 std::shared_ptr<C2Allocator> allocator;
1460 // verify allocator IDs and resolve default allocator
1461 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1462 if (allocator) {
1463 pools->outputAllocatorId = allocator->getId();
1464 } else {
1465 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1466 mName, surfaceAllocator->value);
1467 err = C2_BAD_VALUE;
1468 }
1469 }
1470 }
1471 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1472 && err != C2_OK
1473 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1474 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1475 }
1476 }
1477
1478 if ((poolMask >> pools->outputAllocatorId) & 1) {
1479 err = mComponent->createBlockPool(
1480 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1481 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1482 mName, pools->outputAllocatorId,
1483 (unsigned long long)pools->outputPoolId,
1484 asString(err));
1485 } else {
1486 err = C2_NOT_FOUND;
1487 }
1488 if (err != C2_OK) {
1489 // use basic pool instead
1490 pools->outputPoolId =
1491 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1492 }
1493
1494 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1495 // component.
1496 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1497 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1498
1499 std::vector<std::unique_ptr<C2SettingResult>> failures;
1500 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1501 ALOGD("[%s] Configured output block pool ids %llu => %s",
1502 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1503 outputPoolId_ = pools->outputPoolId;
1504 }
1505
David Stevensc3fbb282021-01-18 18:11:20 +09001506 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1507 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1508 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1509 if (err != C2_OK) {
1510 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1511 (unsigned long long) prevOutputPoolId, asString(err), err);
1512 }
1513 }
1514
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001515 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001516 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001517 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001518 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001519 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001520 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001521 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001522 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001523 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001524 }
1525 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001526 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001527 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001528 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001529
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001530 output->buffers->clearStash();
1531 if (reorderDepth) {
1532 output->buffers->setReorderDepth(reorderDepth.value);
1533 }
1534 if (reorderKey) {
1535 output->buffers->setReorderKey(reorderKey.value);
1536 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001537
1538 // Try to set output surface to created block pool if given.
1539 if (outputSurface) {
1540 mComponent->setOutputSurface(
1541 outputPoolId_,
1542 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001543 outputGeneration,
1544 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001545 } else {
1546 // configure CPU read consumer usage
1547 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1548 std::vector<std::unique_ptr<C2SettingResult>> failures;
1549 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1550 // do not print error message for now as most components may not yet
1551 // support this setting
1552 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1553 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001554 }
1555
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001556 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001557 if (buffersBoundToCodec) {
1558 // WORKAROUND: if we're using early CSD workaround we convert to
1559 // array mode, to appease apps assuming the output
1560 // buffers to be of the same size.
1561 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1562 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001563
1564 int32_t channelCount;
1565 int32_t sampleRate;
1566 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1567 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1568 int32_t delay = 0;
1569 int32_t padding = 0;;
1570 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1571 delay = 0;
1572 }
1573 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1574 padding = 0;
1575 }
1576 if (delay || padding) {
1577 // We need write access to the buffers, and we're already in
1578 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001579 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001580 }
1581 }
1582 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001583
1584 int32_t tunneled = 0;
1585 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1586 tunneled = 0;
1587 }
1588 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001589 }
1590
1591 // Set up pipeline control. This has to be done after mInputBuffers and
1592 // mOutputBuffers are initialized to make sure that lingering callbacks
1593 // about buffers from the previous generation do not interfere with the
1594 // newly initialized pipeline capacity.
1595
Wonsik Kim62545252021-01-20 11:25:41 -08001596 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001597 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001598 watcher->inputDelay(inputDelayValue)
1599 .pipelineDelay(pipelineDelayValue)
1600 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001601 .smoothnessFactor(kSmoothnessFactor);
1602 watcher->flush();
1603 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001604
1605 mInputMetEos = false;
1606 mSync.start();
1607 return OK;
1608}
1609
Wonsik Kim34b28b42022-05-20 15:49:32 -07001610status_t CCodecBufferChannel::prepareInitialInputBuffers(
1611 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001612 if (mInputSurface) {
1613 return OK;
1614 }
1615
Wonsik Kim34b28b42022-05-20 15:49:32 -07001616 size_t numInputSlots = mInput.lock()->numSlots;
1617
1618 {
1619 Mutexed<Input>::Locked input(mInput);
1620 while (clientInputBuffers->size() < numInputSlots) {
1621 size_t index;
1622 sp<MediaCodecBuffer> buffer;
1623 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1624 break;
1625 }
1626 clientInputBuffers->emplace(index, buffer);
1627 }
1628 }
1629 if (clientInputBuffers->empty()) {
1630 ALOGW("[%s] start: cannot allocate memory at all", mName);
1631 return NO_MEMORY;
1632 } else if (clientInputBuffers->size() < numInputSlots) {
1633 ALOGD("[%s] start: cannot allocate memory for all slots, "
1634 "only %zu buffers allocated",
1635 mName, clientInputBuffers->size());
1636 } else {
1637 ALOGV("[%s] %zu initial input buffers available",
1638 mName, clientInputBuffers->size());
1639 }
1640 return OK;
1641}
1642
1643status_t CCodecBufferChannel::requestInitialInputBuffers(
1644 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001645 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001646 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1647 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1648 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001649 return UNKNOWN_ERROR;
1650 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001651
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001652 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1653 mFlushedConfigs.lock()->swap(flushedConfigs);
1654 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001655 {
1656 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1657 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1658 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1659 watcher->onWorkQueued(
1660 work->input.ordinal.frameIndex.peeku(),
1661 std::vector(work->input.buffers),
1662 now);
1663 }
1664 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001665 err = mComponent->queue(&flushedConfigs);
1666 if (err != C2_OK) {
1667 ALOGW("[%s] Error while queueing a flushed config", mName);
1668 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001669 }
1670 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001671 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001672 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1673 !clientInputBuffers.empty()) {
1674 size_t minIndex = clientInputBuffers.begin()->first;
1675 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1676 for (const auto &[index, buffer] : clientInputBuffers) {
1677 if (minBuffer->capacity() > buffer->capacity()) {
1678 minIndex = index;
1679 minBuffer = buffer;
1680 }
1681 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001682 // WORKAROUND: Some apps expect CSD available without queueing
1683 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001684 minBuffer->setRange(0, 0);
1685 minBuffer->meta()->clear();
1686 minBuffer->meta()->setInt64("timeUs", 0);
1687 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001688 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1689 mName);
1690 return UNKNOWN_ERROR;
1691 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001692 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001693 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001694
Wonsik Kim34b28b42022-05-20 15:49:32 -07001695 for (const auto &[index, buffer] : clientInputBuffers) {
1696 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001697 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001698
Pawin Vongmasa36653902018-11-15 00:10:25 -08001699 return OK;
1700}
1701
1702void CCodecBufferChannel::stop() {
1703 mSync.stop();
1704 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001705}
1706
Sungtak Lee99144332023-01-26 11:03:14 +00001707void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
1708 sp<Surface> surface = mOutputSurface.lock()->surface;
1709 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00001710 C2BlockPool::local_id_t outputPoolId;
1711 {
1712 Mutexed<BlockPools>::Locked pools(mBlockPools);
1713 outputPoolId = pools->outputPoolId;
1714 }
1715 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00001716
1717 if (pushBlankBuffer) {
1718 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
1719 if (anw) {
1720 pushBlankBuffersToNativeWindow(anw.get());
1721 }
1722 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00001723 }
1724}
1725
Wonsik Kim936a89c2020-05-08 16:07:50 -07001726void CCodecBufferChannel::reset() {
1727 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001728 if (mInputSurface != nullptr) {
1729 mInputSurface.reset();
1730 }
1731 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001732 {
1733 Mutexed<Input>::Locked input(mInput);
1734 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001735 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001736 }
1737 {
1738 Mutexed<Output>::Locked output(mOutput);
1739 output->buffers.reset();
1740 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001741 // reset the frames that are being tracked for onFrameRendered callbacks
1742 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001743}
1744
1745void CCodecBufferChannel::release() {
1746 mComponent.reset();
1747 mInputAllocator.reset();
1748 mOutputSurface.lock()->surface.clear();
1749 {
1750 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1751 blockPools->inputPool.reset();
1752 blockPools->outputPoolIntf.reset();
1753 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001754 setCrypto(nullptr);
1755 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001756}
1757
Pawin Vongmasa36653902018-11-15 00:10:25 -08001758void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1759 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001760 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001761 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001762 {
1763 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1764 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1765 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1766 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1767 watcher->onWorkDone(frameIndex);
1768 continue;
1769 }
1770 if (work->input.buffers.empty()
1771 || work->input.buffers.front() == nullptr
1772 || work->input.buffers.front()->data().linearBlocks().empty()) {
1773 ALOGD("[%s] no linear codec config data found", mName);
1774 watcher->onWorkDone(frameIndex);
1775 continue;
1776 }
1777 std::unique_ptr<C2Work> copy(new C2Work);
1778 copy->input.flags = C2FrameData::flags_t(
1779 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1780 copy->input.ordinal = work->input.ordinal;
1781 copy->input.ordinal.frameIndex = mFrameIndex++;
1782 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1783 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1784 }
1785 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1786 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1787 }
1788 copy->input.infoBuffers.insert(
1789 copy->input.infoBuffers.begin(),
1790 work->input.infoBuffers.begin(),
1791 work->input.infoBuffers.end());
1792 copy->worklets.emplace_back(new C2Worklet);
1793 configs.push_back(std::move(copy));
1794 watcher->onWorkDone(frameIndex);
1795 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001796 }
1797 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001798 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001799 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001800 Mutexed<Input>::Locked input(mInput);
1801 input->buffers->flush();
1802 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001803 }
1804 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001805 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001806 if (output->buffers) {
1807 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001808 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001809 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001810 }
1811}
1812
1813void CCodecBufferChannel::onWorkDone(
1814 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001815 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001816 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001817 feedInputBufferIfAvailable();
1818 }
1819}
1820
1821void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001822 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001823 if (mInputSurface) {
1824 return;
1825 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001826 std::shared_ptr<C2Buffer> buffer =
1827 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001828 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001829 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001830 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001831 if (input->lastFlushIndex >= frameIndex) {
1832 ALOGD("[%s] Ignoring stale input buffer done callback: "
1833 "last flush index = %lld, frameIndex = %lld",
1834 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1835 } else {
1836 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1837 if (!newInputSlotAvailable) {
1838 (void)input->extraBuffers.expireComponentBuffer(buffer);
1839 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001840 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001841 }
1842 if (newInputSlotAvailable) {
1843 feedInputBufferIfAvailable();
1844 }
1845}
1846
1847bool CCodecBufferChannel::handleWork(
1848 std::unique_ptr<C2Work> work,
1849 const sp<AMessage> &outputFormat,
1850 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001851 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001852 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001853 if (!output->buffers) {
1854 return false;
1855 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001856 }
1857
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001858 // Whether the output buffer should be reported to the client or not.
1859 bool notifyClient = false;
1860
1861 if (work->result == C2_OK){
1862 notifyClient = true;
1863 } else if (work->result == C2_NOT_FOUND) {
1864 ALOGD("[%s] flushed work; ignored.", mName);
1865 } else {
1866 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1867 // the config update.
1868 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1869 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1870 return false;
1871 }
1872
1873 if ((work->input.ordinal.frameIndex -
1874 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001875 // Discard frames from previous generation.
1876 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001877 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001878 }
1879
Wonsik Kim524b0582019-03-12 11:28:57 -07001880 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001881 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001882 || !(work->worklets.front()->output.flags &
1883 C2FrameData::FLAG_INCOMPLETE))) {
1884 mPipelineWatcher.lock()->onWorkDone(
1885 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001886 }
1887
1888 // NOTE: MediaCodec usage supposedly have only one worklet
1889 if (work->worklets.size() != 1u) {
1890 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1891 mName, work->worklets.size());
1892 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1893 return false;
1894 }
1895
1896 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1897
1898 std::shared_ptr<C2Buffer> buffer;
1899 // NOTE: MediaCodec usage supposedly have only one output stream.
1900 if (worklet->output.buffers.size() > 1u) {
1901 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1902 mName, worklet->output.buffers.size());
1903 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1904 return false;
1905 } else if (worklet->output.buffers.size() == 1u) {
1906 buffer = worklet->output.buffers[0];
1907 if (!buffer) {
1908 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1909 }
1910 }
1911
Wonsik Kim3dedf682021-05-03 10:57:09 -07001912 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1913 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001914 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001915 while (!worklet->output.configUpdate.empty()) {
1916 std::unique_ptr<C2Param> param;
1917 worklet->output.configUpdate.back().swap(param);
1918 worklet->output.configUpdate.pop_back();
1919 switch (param->coreIndex().coreIndex()) {
1920 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1921 C2PortReorderBufferDepthTuning::output reorderDepth;
1922 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001923 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1924 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001925 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001926 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001927 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001928 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1929 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001930 }
1931 break;
1932 }
1933 case C2PortReorderKeySetting::CORE_INDEX: {
1934 C2PortReorderKeySetting::output reorderKey;
1935 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001936 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001937 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1938 mName, reorderKey.value);
1939 } else {
1940 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1941 }
1942 break;
1943 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001944 case C2PortActualDelayTuning::CORE_INDEX: {
1945 if (param->isGlobal()) {
1946 C2ActualPipelineDelayTuning pipelineDelay;
1947 if (pipelineDelay.updateFrom(*param)) {
1948 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1949 mName, pipelineDelay.value);
1950 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001951 (void)mPipelineWatcher.lock()->pipelineDelay(
1952 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001953 }
1954 }
1955 if (param->forInput()) {
1956 C2PortActualDelayTuning::input inputDelay;
1957 if (inputDelay.updateFrom(*param)) {
1958 ALOGV("[%s] onWorkDone: updating input delay %u",
1959 mName, inputDelay.value);
1960 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001961 (void)mPipelineWatcher.lock()->inputDelay(
1962 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001963 }
1964 }
1965 if (param->forOutput()) {
1966 C2PortActualDelayTuning::output outputDelay;
1967 if (outputDelay.updateFrom(*param)) {
1968 ALOGV("[%s] onWorkDone: updating output delay %u",
1969 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001970 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001971 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001972 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001973
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001974 }
1975 }
1976 break;
1977 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001978 case C2PortTunnelSystemTime::CORE_INDEX: {
1979 C2PortTunnelSystemTime::output frameRenderTime;
1980 if (frameRenderTime.updateFrom(*param)) {
1981 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1982 mName, (long long)frameRenderTime.value,
1983 (long long)worklet->output.ordinal.timestamp.peekll());
1984 mCCodecCallback->onOutputFramesRendered(
1985 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1986 }
1987 break;
1988 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001989 case C2StreamTunnelHoldRender::CORE_INDEX: {
1990 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1991 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1992 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1993 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1994 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1995 mCCodecCallback->onFirstTunnelFrameReady();
1996 break;
1997 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001998 default:
1999 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2000 mName, param->index());
2001 break;
2002 }
2003 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002004 if (newInputDelay || newPipelineDelay) {
2005 Mutexed<Input>::Locked input(mInput);
2006 size_t newNumSlots =
2007 newInputDelay.value_or(input->inputDelay) +
2008 newPipelineDelay.value_or(input->pipelineDelay) +
2009 kSmoothnessFactor;
2010 if (input->buffers->isArrayMode()) {
2011 if (input->numSlots >= newNumSlots) {
2012 input->numExtraSlots = 0;
2013 } else {
2014 input->numExtraSlots = newNumSlots - input->numSlots;
2015 }
2016 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2017 mName, input->numExtraSlots);
2018 } else {
2019 input->numSlots = newNumSlots;
2020 }
2021 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002022 size_t numOutputSlots = 0;
2023 uint32_t reorderDepth = 0;
2024 bool outputBuffersChanged = false;
2025 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2026 Mutexed<Output>::Locked output(mOutput);
2027 if (!output->buffers) {
2028 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002029 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002030 numOutputSlots = output->numSlots;
2031 if (newReorderKey) {
2032 output->buffers->setReorderKey(newReorderKey.value());
2033 }
2034 if (newReorderDepth) {
2035 output->buffers->setReorderDepth(newReorderDepth.value());
2036 }
2037 reorderDepth = output->buffers->getReorderDepth();
2038 if (newOutputDelay) {
2039 output->outputDelay = newOutputDelay.value();
2040 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2041 if (output->numSlots < numOutputSlots) {
2042 output->numSlots = numOutputSlots;
2043 if (output->buffers->isArrayMode()) {
2044 OutputBuffersArray *array =
2045 (OutputBuffersArray *)output->buffers.get();
2046 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2047 mName, numOutputSlots);
2048 array->grow(numOutputSlots);
2049 outputBuffersChanged = true;
2050 }
2051 }
2052 }
2053 numOutputSlots = output->numSlots;
2054 }
2055 if (outputBuffersChanged) {
2056 mCCodecCallback->onOutputBuffersChanged();
2057 }
2058 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002059 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002060 {
2061 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2062 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002063 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002064 if (output->surface) {
2065 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2066 }
2067 }
2068 if (maxDequeueCount > 0) {
2069 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002070 }
2071 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002072
Pawin Vongmasa36653902018-11-15 00:10:25 -08002073 int32_t flags = 0;
2074 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002075 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002076 ALOGV("[%s] onWorkDone: output EOS", mName);
2077 }
2078
Pawin Vongmasa36653902018-11-15 00:10:25 -08002079 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2080 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2081 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2082 // shall correspond to the client input timesamp (in customOrdinal). By using the
2083 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2084 // produces multiple output.
2085 c2_cntr64_t timestamp =
2086 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2087 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07002088 if (mInputSurface != nullptr) {
2089 // When using input surface we need to restore the original input timestamp.
2090 timestamp = work->input.ordinal.customOrdinal;
2091 }
My Name6bd9a7d2022-03-25 12:37:58 -07002092 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2093 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002094 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2095 mName,
2096 work->input.ordinal.customOrdinal.peekll(),
2097 work->input.ordinal.timestamp.peekll(),
2098 worklet->output.ordinal.timestamp.peekll(),
2099 timestamp.peekll());
2100
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002101 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002102 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002103 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002104 if (!output->buffers) {
2105 return false;
2106 }
2107 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002108 output->buffers->updateSkipCutBuffer(outputFormat);
2109 output->buffers->setFormat(outputFormat);
2110 }
2111 if (!notifyClient) {
2112 return false;
2113 }
2114 size_t index;
2115 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002116 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002117 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002118 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002119 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2120
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002121 // TRICKY: we want popped buffers reported in order, so sending
2122 // the callback while holding the lock here. This assumes that
2123 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2124 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002125 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002126 } else {
2127 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002128 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002129 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002130 return false;
2131 }
2132 }
2133
Wonsik Kimec585c32021-10-01 01:11:00 -07002134 bool drop = false;
2135 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2136 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2137 drop = true;
2138 }
2139
Marc Kassisec910342022-11-25 11:43:05 +01002140 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2141 // HAL, the flag is then removed in the corresponding output buffer.
2142 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2143 flags |= BUFFER_FLAG_DECODE_ONLY;
2144 }
2145
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002146 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002147 if (mTunneled && drop && outputFormat) {
2148 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2149 mName, work->input.ordinal.frameIndex.peekull());
2150 } else {
2151 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2152 mName, work->input.ordinal.frameIndex.peekull());
2153 notifyClient = false;
2154 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002155 }
2156
2157 if (buffer) {
2158 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2159 // TODO: properly translate these to metadata
2160 switch (info->coreIndex().coreIndex()) {
2161 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002162 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002163 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002164 }
2165 break;
2166 default:
2167 break;
2168 }
2169 }
2170 }
2171
2172 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002173 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002174 if (!output->buffers) {
2175 return false;
2176 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002177 output->buffers->pushToStash(
2178 buffer,
2179 notifyClient,
2180 timestamp.peek(),
2181 flags,
2182 outputFormat,
2183 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002184 }
2185 sendOutputBuffers();
2186 return true;
2187}
2188
2189void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002190 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002191 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002192 sp<MediaCodecBuffer> outBuffer;
2193 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002194
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002195 constexpr int kMaxReallocTry = 5;
2196 int reallocTryNum = 0;
2197
Pawin Vongmasa36653902018-11-15 00:10:25 -08002198 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002199 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002200 if (!output->buffers) {
2201 return;
2202 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002203 action = output->buffers->popFromStashAndRegister(
2204 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002205 if (action != OutputBuffers::REALLOCATE) {
2206 reallocTryNum = 0;
2207 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002208 switch (action) {
2209 case OutputBuffers::SKIP:
2210 return;
2211 case OutputBuffers::DISCARD:
2212 break;
2213 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002214 // TRICKY: we want popped buffers reported in order, so sending
2215 // the callback while holding the lock here. This assumes that
2216 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2217 // callbacks are always sent with the Output lock held.
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002218 mCallback->onOutputBufferAvailable(index, outBuffer);
2219 break;
2220 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002221 if (++reallocTryNum > kMaxReallocTry) {
2222 output.unlock();
2223 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2224 mName, kMaxReallocTry);
2225 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2226 return;
2227 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002228 if (!output->buffers->isArrayMode()) {
2229 output->buffers =
2230 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002231 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002232 static_cast<OutputBuffersArray*>(output->buffers.get())->
2233 realloc(c2Buffer);
2234 output.unlock();
2235 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002236 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002237 case OutputBuffers::RETRY:
2238 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2239 mName);
2240 return;
2241 default:
2242 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2243 "corrupted BufferAction value (%d) "
2244 "returned from popFromStashAndRegister.",
2245 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002246 return;
2247 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002248 }
2249}
2250
Sungtak Lee99144332023-01-26 11:03:14 +00002251status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002252 static std::atomic_uint32_t surfaceGeneration{0};
2253 uint32_t generation = (getpid() << 10) |
2254 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2255 & ((1 << 10) - 1));
2256
2257 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002258 int maxDequeueCount;
2259 sp<Surface> oldSurface;
2260 {
2261 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2262 maxDequeueCount = outputSurface->maxDequeueBuffers;
2263 oldSurface = outputSurface->surface;
2264 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002265 if (newSurface) {
2266 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002267 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002268 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002269 producer = newSurface->getIGraphicBufferProducer();
2270 producer->setGenerationNumber(generation);
2271 } else {
2272 ALOGE("[%s] setting output surface to null", mName);
2273 return INVALID_OPERATION;
2274 }
2275
2276 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2277 C2BlockPool::local_id_t outputPoolId;
2278 {
2279 Mutexed<BlockPools>::Locked pools(mBlockPools);
2280 outputPoolId = pools->outputPoolId;
2281 outputPoolIntf = pools->outputPoolIntf;
2282 }
2283
2284 if (outputPoolIntf) {
2285 if (mComponent->setOutputSurface(
2286 outputPoolId,
2287 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002288 generation,
2289 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002290 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2291 return INVALID_OPERATION;
2292 }
2293 }
2294
2295 {
2296 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2297 output->surface = newSurface;
2298 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002299 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002300 }
2301
Sungtak Lee99144332023-01-26 11:03:14 +00002302 if (oldSurface && pushBlankBuffer) {
2303 // When ReleaseSurface was set from MediaCodec,
2304 // pushing a blank buffer at the end might be necessary.
2305 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2306 if (anw) {
2307 pushBlankBuffersToNativeWindow(anw.get());
2308 }
2309 }
2310
Pawin Vongmasa36653902018-11-15 00:10:25 -08002311 return OK;
2312}
2313
Wonsik Kimab34ed62019-01-31 15:28:46 -08002314PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002315 // Otherwise, component may have stalled work due to input starvation up to
2316 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002317 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2318 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002319 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002320 size_t outputDelay = mOutput.lock()->outputDelay;
2321 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002322 Mutexed<Input>::Locked input(mInput);
2323 n = input->inputDelay + input->pipelineDelay + outputDelay;
2324 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002325 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002326}
2327
Pawin Vongmasa36653902018-11-15 00:10:25 -08002328void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2329 mMetaMode = mode;
2330}
2331
Wonsik Kim596187e2019-10-25 12:44:10 -07002332void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002333 if (mCrypto != nullptr) {
2334 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2335 mCrypto->unsetHeap(entry.second);
2336 }
2337 mHeapSeqNumMap.clear();
2338 if (mHeapSeqNum >= 0) {
2339 mCrypto->unsetHeap(mHeapSeqNum);
2340 mHeapSeqNum = -1;
2341 }
2342 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002343 mCrypto = crypto;
2344}
2345
2346void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2347 mDescrambler = descrambler;
2348}
2349
Pawin Vongmasa36653902018-11-15 00:10:25 -08002350status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2351 // C2_OK is always translated to OK.
2352 if (c2s == C2_OK) {
2353 return OK;
2354 }
2355
2356 // Operation-dependent translation
2357 // TODO: Add as necessary
2358 switch (c2op) {
2359 case C2_OPERATION_Component_start:
2360 switch (c2s) {
2361 case C2_NO_MEMORY:
2362 return NO_MEMORY;
2363 default:
2364 return UNKNOWN_ERROR;
2365 }
2366 default:
2367 break;
2368 }
2369
2370 // Backup operation-agnostic translation
2371 switch (c2s) {
2372 case C2_BAD_INDEX:
2373 return BAD_INDEX;
2374 case C2_BAD_VALUE:
2375 return BAD_VALUE;
2376 case C2_BLOCKING:
2377 return WOULD_BLOCK;
2378 case C2_DUPLICATE:
2379 return ALREADY_EXISTS;
2380 case C2_NO_INIT:
2381 return NO_INIT;
2382 case C2_NO_MEMORY:
2383 return NO_MEMORY;
2384 case C2_NOT_FOUND:
2385 return NAME_NOT_FOUND;
2386 case C2_TIMED_OUT:
2387 return TIMED_OUT;
2388 case C2_BAD_STATE:
2389 case C2_CANCELED:
2390 case C2_CANNOT_DO:
2391 case C2_CORRUPTED:
2392 case C2_OMITTED:
2393 case C2_REFUSED:
2394 return UNKNOWN_ERROR;
2395 default:
2396 return -static_cast<status_t>(c2s);
2397 }
2398}
2399
Pawin Vongmasa36653902018-11-15 00:10:25 -08002400} // namespace android