blob: e2b28dcf2bc149cb8f1ecc3ae8102deda46483e2 [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>
Arun Johnson326166e2023-07-28 19:11:52 +000028#include <thread>
29#include <chrono>
Pawin Vongmasa36653902018-11-15 00:10:25 -080030
Harish Mahendrakar38a99c22024-02-26 20:28:05 +053031#include <android_media_codec.h>
32
Pawin Vongmasa36653902018-11-15 00:10:25 -080033#include <C2AllocatorGralloc.h>
34#include <C2PlatformSupport.h>
35#include <C2BlockInternal.h>
36#include <C2Config.h>
37#include <C2Debug.h>
38
39#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070040#include <android/hardware/drm/1.0/types.h>
Wonsik Kimc556d802024-10-15 21:42:25 +000041#include <android/sysprop/MediaProperties.sysprop.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070042#include <android-base/parseint.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080043#include <android-base/properties.h>
Sungtak Leed1146682024-10-03 02:03:42 +000044#include <android-base/no_destructor.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080045#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080046#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080047#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070048#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080049#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070050#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080051#include <media/openmax/OMX_Core.h>
52#include <media/stagefright/foundation/ABuffer.h>
53#include <media/stagefright/foundation/ALookup.h>
54#include <media/stagefright/foundation/AMessage.h>
55#include <media/stagefright/foundation/AUtils.h>
56#include <media/stagefright/foundation/hexdump.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080057#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070058#include <media/stagefright/SkipCutBuffer.h>
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010059#include <media/stagefright/SurfaceUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080060#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070061#include <mediadrm/ICrypto.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070062#include <server_configurable_flags/get_flags.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080063#include <system/window.h>
64
65#include "CCodecBufferChannel.h"
66#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080067
68namespace android {
69
70using android::base::StringPrintf;
71using hardware::hidl_handle;
72using hardware::hidl_string;
73using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070074using hardware::fromHeap;
75using hardware::HidlMemory;
Brian Lindahld7967a92023-08-10 10:12:49 -060076using server_configurable_flags::GetServerConfigurableFlag;
Robert Shih895fba92019-07-16 16:29:44 -070077
Pawin Vongmasa36653902018-11-15 00:10:25 -080078using namespace hardware::cas::V1_0;
79using namespace hardware::cas::native::V1_0;
80
81using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070082using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080083
Pawin Vongmasa36653902018-11-15 00:10:25 -080084namespace {
85
Wonsik Kim469c8342019-04-11 16:46:09 -070086constexpr size_t kSmoothnessFactor = 4;
Pawin Vongmasa36653902018-11-15 00:10:25 -080087
Sungtak Leeab6f2f32019-02-15 14:43:51 -080088// This is for keeping IGBP's buffer dropping logic in legacy mode other
89// than making it non-blocking. Do not change this value.
90const static size_t kDequeueTimeoutNs = 0;
91
Brian Lindahld7967a92023-08-10 10:12:49 -060092static bool areRenderMetricsEnabled() {
93 std::string v = GetServerConfigurableFlag("media_native", "render_metrics_enabled", "false");
94 return v == "true";
95}
96
Arun Johnsonf4a81f72023-11-09 21:22:48 +000097// Flags can come with individual BufferInfos
98// when used with large frame audio
99constexpr static std::initializer_list<std::pair<uint32_t, uint32_t>> flagList = {
100 {BUFFER_FLAG_CODEC_CONFIG, C2FrameData::FLAG_CODEC_CONFIG},
101 {BUFFER_FLAG_END_OF_STREAM, C2FrameData::FLAG_END_OF_STREAM},
102 {BUFFER_FLAG_DECODE_ONLY, C2FrameData::FLAG_DROP_FRAME}
103};
104
105static uint32_t convertFlags(uint32_t flags, bool toC2) {
106 return std::transform_reduce(
107 flagList.begin(), flagList.end(),
108 0u,
109 std::bit_or{},
110 [flags, toC2](const std::pair<uint32_t, uint32_t> &entry) {
111 if (toC2) {
112 return (flags & entry.first) ? entry.second : 0;
113 } else {
114 return (flags & entry.second) ? entry.first : 0;
115 }
116 });
117}
118
Sungtak Leed1146682024-10-03 02:03:42 +0000119class SurfaceCallbackHandler {
120public:
121 enum callback_type_t {
122 ON_BUFFER_RELEASED = 0,
123 ON_BUFFER_ATTACHED
124 };
125
126 void post(callback_type_t callback,
127 std::shared_ptr<Codec2Client::Component> component,
128 uint32_t generation) {
129 if (!component) {
130 ALOGW("surface callback psoted for invalid component");
131 }
132 std::shared_ptr<SurfaceCallbackItem> item =
133 std::make_shared<SurfaceCallbackItem>(callback, component, generation);
134 std::unique_lock<std::mutex> lock(mMutex);
135 mItems.emplace_back(std::move(item));
136 mCv.notify_one();
137 }
138
139 ~SurfaceCallbackHandler() {
140 {
141 std::unique_lock<std::mutex> lock(mMutex);
142 mDone = true;
143 mCv.notify_all();
144 }
145 if (mThread.joinable()) {
146 mThread.join();
147 }
148 }
149
150 static SurfaceCallbackHandler& GetInstance() {
151 static base::NoDestructor<SurfaceCallbackHandler> sSurfaceCallbackHandler{};
152 return *sSurfaceCallbackHandler;
153 }
154
155private:
156 struct SurfaceCallbackItem {
157 callback_type_t mCallback;
158 std::weak_ptr<Codec2Client::Component> mComp;
159 uint32_t mGeneration;
160
161 SurfaceCallbackItem(
162 callback_type_t callback,
163 std::shared_ptr<Codec2Client::Component> comp,
164 uint32_t generation)
165 : mCallback(callback), mComp(comp), mGeneration(generation) {}
166 };
167
168 SurfaceCallbackHandler() { mThread = std::thread(&SurfaceCallbackHandler::run, this); }
169
170 void run() {
171 std::unique_lock<std::mutex> lock(mMutex);
172 while (!mDone) {
173 while (!mItems.empty()) {
174 std::deque<std::shared_ptr<SurfaceCallbackItem>> items = std::move(mItems);
175 mItems.clear();
176 lock.unlock();
177 handle(items);
178 lock.lock();
179 }
180 mCv.wait(lock);
181 }
182 }
183
184 void handle(std::deque<std::shared_ptr<SurfaceCallbackItem>> &items) {
185 while (!items.empty()) {
186 std::shared_ptr<SurfaceCallbackItem> item = items.front();
187 items.pop_front();
188 switch (item->mCallback) {
189 case ON_BUFFER_RELEASED: {
190 std::shared_ptr<Codec2Client::Component> comp = item->mComp.lock();;
191 if (comp) {
192 comp->onBufferReleasedFromOutputSurface(item->mGeneration);
193 }
194 break;
195 }
196 case ON_BUFFER_ATTACHED: {
197 std::shared_ptr<Codec2Client::Component> comp = item->mComp.lock();
198 if (comp) {
199 comp->onBufferAttachedToOutputSurface(item->mGeneration);
200 }
201 break;
202 }
203 default:
204 ALOGE("Non defined surface callback message");
205 break;
206 }
207 }
208 }
209
210 std::thread mThread;
211 bool mDone = false;
212 std::deque<std::shared_ptr<SurfaceCallbackItem>> mItems;
213 std::mutex mMutex;
214 std::condition_variable mCv;
215
216
217 friend class base::NoDestructor<SurfaceCallbackHandler>;
218
219 DISALLOW_EVIL_CONSTRUCTORS(SurfaceCallbackHandler);
220};
221
Pawin Vongmasa36653902018-11-15 00:10:25 -0800222} // namespace
223
224CCodecBufferChannel::QueueGuard::QueueGuard(
225 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
226 Mutex::Autolock l(mSync.mGuardLock);
227 // At this point it's guaranteed that mSync is not under state transition,
228 // as we are holding its mutex.
229
230 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
231 if (count->value == -1) {
232 mRunning = false;
233 } else {
234 ++count->value;
235 mRunning = true;
236 }
237}
238
239CCodecBufferChannel::QueueGuard::~QueueGuard() {
240 if (mRunning) {
241 // We are not holding mGuardLock at this point so that QueueSync::stop() can
242 // keep holding the lock until mCount reaches zero.
243 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
244 --count->value;
245 count->cond.broadcast();
246 }
247}
248
249void CCodecBufferChannel::QueueSync::start() {
250 Mutex::Autolock l(mGuardLock);
251 // If stopped, it goes to running state; otherwise no-op.
252 Mutexed<Counter>::Locked count(mCount);
253 if (count->value == -1) {
254 count->value = 0;
255 }
256}
257
258void CCodecBufferChannel::QueueSync::stop() {
259 Mutex::Autolock l(mGuardLock);
260 Mutexed<Counter>::Locked count(mCount);
261 if (count->value == -1) {
262 // no-op
263 return;
264 }
265 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
266 // mCount can only decrement. In other words, threads that acquired the lock
267 // are allowed to finish execution but additional threads trying to acquire
268 // the lock at this point will block, and then get QueueGuard at STOPPED
269 // state.
270 while (count->value != 0) {
271 count.waitForCondition(count->cond);
272 }
273 count->value = -1;
274}
275
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700276// Input
277
278CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
279
Pawin Vongmasa36653902018-11-15 00:10:25 -0800280// CCodecBufferChannel
281
282CCodecBufferChannel::CCodecBufferChannel(
283 const std::shared_ptr<CCodecCallback> &callback)
284 : mHeapSeqNum(-1),
285 mCCodecCallback(callback),
286 mFrameIndex(0u),
287 mFirstValidFrameIndex(0u),
Brian Lindahld7967a92023-08-10 10:12:49 -0600288 mAreRenderMetricsEnabled(areRenderMetricsEnabled()),
Brian Lindahl2048d492023-04-05 08:49:23 -0600289 mIsSurfaceToDisplay(false),
290 mHasPresentFenceTimes(false),
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700291 mRenderingDepth(3u),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800292 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700293 mInputMetEos(false),
294 mSendEncryptedInfoBuffer(false) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700295 {
296 Mutexed<Input>::Locked input(mInput);
297 input->buffers.reset(new DummyInputBuffers(""));
298 input->extraBuffers.flush();
299 input->inputDelay = 0u;
300 input->pipelineDelay = 0u;
301 input->numSlots = kSmoothnessFactor;
302 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700303 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700304 }
305 {
306 Mutexed<Output>::Locked output(mOutput);
307 output->outputDelay = 0u;
308 output->numSlots = kSmoothnessFactor;
Wonsik Kim3722abc2023-05-17 13:26:31 -0700309 output->bounded = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700310 }
David Stevensc3fbb282021-01-18 18:11:20 +0900311 {
312 Mutexed<BlockPools>::Locked pools(mBlockPools);
313 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
314 }
Wonsik Kimc556d802024-10-15 21:42:25 +0000315 if (android::media::codec::provider_->rendering_depth_removal()) {
316 constexpr int kAndroidApi202404 = 202404;
317 int vendorVersion = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
318 using ::android::sysprop::MediaProperties::codec2_remove_rendering_depth;
319 if (vendorVersion > kAndroidApi202404 || codec2_remove_rendering_depth().value_or(false)) {
320 mRenderingDepth = 0;
321 }
322 } else {
323 std::string value = GetServerConfigurableFlag(
324 "media_native", "ccodec_rendering_depth", "3");
325 android::base::ParseInt(value, &mRenderingDepth);
326 }
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700327 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800328}
329
330CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800331 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800332 mCrypto->unsetHeap(mHeapSeqNum);
333 }
334}
335
336void CCodecBufferChannel::setComponent(
337 const std::shared_ptr<Codec2Client::Component> &component) {
Sungtak Lee368452b2024-10-17 01:16:29 +0000338 std::atomic_store(&mComponent, component);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800339 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
340 mName = mComponentName.c_str();
341}
342
343status_t CCodecBufferChannel::setInputSurface(
344 const std::shared_ptr<InputSurfaceWrapper> &surface) {
345 ALOGV("[%s] setInputSurface", mName);
Wonsik Kimfca97a22024-08-30 20:20:42 +0000346 if (!surface) {
347 ALOGE("[%s] setInputSurface: surface must not be null", mName);
348 return BAD_VALUE;
349 }
350 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
351 inputSurface->numProcessingBuffersBalance = 0;
352 inputSurface->surface = surface;
353 mHasInputSurface = true;
Sungtak Lee368452b2024-10-17 01:16:29 +0000354 return inputSurface->surface->connect(std::atomic_load(&mComponent));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800355}
356
357status_t CCodecBufferChannel::signalEndOfInputStream() {
Wonsik Kimfca97a22024-08-30 20:20:42 +0000358 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
359 if (inputSurface->surface == nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800360 return INVALID_OPERATION;
361 }
Wonsik Kimfca97a22024-08-30 20:20:42 +0000362 return inputSurface->surface->signalEndOfInputStream();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800363}
364
Sungtak Lee04b30352020-07-27 13:57:25 -0700365status_t CCodecBufferChannel::queueInputBufferInternal(
366 sp<MediaCodecBuffer> buffer,
367 std::shared_ptr<C2LinearBlock> encryptedBlock,
368 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800369 int64_t timeUs;
370 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
371
372 if (mInputMetEos) {
373 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
374 return OK;
375 }
376
377 int32_t flags = 0;
378 int32_t tmp = 0;
379 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200380 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800381 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
382 eos = true;
383 mInputMetEos = true;
384 ALOGV("[%s] input EOS", mName);
385 }
386 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
387 flags |= C2FrameData::FLAG_CODEC_CONFIG;
388 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200389 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
390 tunnelFirstFrame = true;
391 }
Marc Kassis96343b42022-12-09 11:49:44 +0100392 if (buffer->meta()->findInt32("decode-only", &tmp) && tmp) {
393 flags |= C2FrameData::FLAG_DROP_FRAME;
394 }
Arun Johnsonf4a81f72023-11-09 21:22:48 +0000395 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu time: %lld",
396 mName, buffer->size(), (long long)timeUs);
Wonsik Kime1104ca2020-11-24 15:01:33 -0800397 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800398 std::unique_ptr<C2Work> work(new C2Work);
399 work->input.ordinal.timestamp = timeUs;
400 work->input.ordinal.frameIndex = mFrameIndex++;
401 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
402 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
403 // Keep client timestamp in customOrdinal
404 work->input.ordinal.customOrdinal = timeUs;
405 work->input.buffers.clear();
406
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700407 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800408 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800409
Pawin Vongmasa36653902018-11-15 00:10:25 -0800410 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700411 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800412 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700413 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800414 return -ENOENT;
415 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700416 // TODO: we want to delay copying buffers.
417 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
418 copy = input->buffers->cloneAndReleaseBuffer(buffer);
419 if (copy != nullptr) {
420 (void)input->extraBuffers.assignSlot(copy);
421 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
422 return UNKNOWN_ERROR;
423 }
424 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
425 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
426 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700427 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700428 } else {
429 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
430 "buffer starvation on component.", mName);
431 }
432 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800433 if (input->frameReassembler) {
434 usesFrameReassembler = true;
435 input->frameReassembler.process(buffer, &items);
436 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900437 int32_t cvo = 0;
438 if (buffer->meta()->findInt32("cvo", &cvo)) {
439 int32_t rotation = cvo % 360;
440 // change rotation to counter-clock wise.
441 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
442
443 Mutexed<OutputSurface>::Locked output(mOutputSurface);
444 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
445 output->rotation[frameIndex] = rotation;
446 }
Arun Johnsonf4a81f72023-11-09 21:22:48 +0000447 sp<RefBase> obj;
448 if (buffer->meta()->findObject("accessUnitInfo", &obj)) {
449 ALOGV("Filling C2Info from multiple access units");
450 sp<WrapperObject<std::vector<AccessUnitInfo>>> infos{
451 (decltype(infos.get()))obj.get()};
452 std::vector<AccessUnitInfo> &accessUnitInfoVec = infos->value;
453 std::vector<C2AccessUnitInfosStruct> multipleAccessUnitInfos;
454 uint32_t outFlags = 0;
455 for (int i = 0; i < accessUnitInfoVec.size(); i++) {
456 outFlags = 0;
457 outFlags = convertFlags(accessUnitInfoVec[i].mFlags, true);
458 if (eos && (outFlags & C2FrameData::FLAG_END_OF_STREAM)) {
459 outFlags &= (~C2FrameData::FLAG_END_OF_STREAM);
460 }
461 multipleAccessUnitInfos.emplace_back(
462 outFlags,
463 accessUnitInfoVec[i].mSize,
464 accessUnitInfoVec[i].mTimestamp);
465 ALOGV("%d) flags: %d, size: %d, time: %llu",
466 i, outFlags, accessUnitInfoVec[i].mSize,
467 (long long)accessUnitInfoVec[i].mTimestamp);
468
469 }
470 const std::shared_ptr<C2AccessUnitInfos::input> c2AccessUnitInfos =
471 C2AccessUnitInfos::input::AllocShared(
472 multipleAccessUnitInfos.size(), 0u, multipleAccessUnitInfos);
473 c2buffer->setInfo(c2AccessUnitInfos);
474 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800475 work->input.buffers.push_back(c2buffer);
476 if (encryptedBlock) {
477 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
478 kParamIndexEncryptedBuffer,
479 encryptedBlock->share(0, blockSize, C2Fence())));
480 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700481 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800482 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700483 Mutexed<Input>::Locked input(mInput);
484 if (input->frameReassembler) {
485 usesFrameReassembler = true;
486 // drain any pending items with eos
487 input->frameReassembler.process(buffer, &items);
488 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800489 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800490 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800491 if (usesFrameReassembler) {
492 if (!items.empty()) {
493 items.front()->input.configUpdate = std::move(mParamsToBeSet);
494 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
495 }
496 } else {
497 work->input.flags = (C2FrameData::flags_t)flags;
Harish Mahendrakar38a99c22024-02-26 20:28:05 +0530498
Wonsik Kime1104ca2020-11-24 15:01:33 -0800499 // TODO: fill info's
Harish Mahendrakar38a99c22024-02-26 20:28:05 +0530500 if (android::media::codec::provider_->region_of_interest()
501 && android::media::codec::provider_->region_of_interest_support()) {
502 if (mInfoBuffers.size()) {
503 for (auto infoBuffer : mInfoBuffers) {
504 work->input.infoBuffers.emplace_back(*infoBuffer);
505 }
506 mInfoBuffers.clear();
507 }
508 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800509
Wonsik Kime1104ca2020-11-24 15:01:33 -0800510 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200511 if (tunnelFirstFrame) {
512 C2StreamTunnelHoldRender::input tunnelHoldRender{
513 0u /* stream */,
514 C2_TRUE /* value */
515 };
516 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
517 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800518 work->worklets.clear();
519 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800520
Wonsik Kime1104ca2020-11-24 15:01:33 -0800521 items.push_back(std::move(work));
522
523 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800524 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800525 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800526 work.reset(new C2Work);
527 work->input.ordinal.timestamp = timeUs;
528 work->input.ordinal.frameIndex = mFrameIndex++;
529 // WORKAROUND: keep client timestamp in customOrdinal
530 work->input.ordinal.customOrdinal = timeUs;
531 work->input.buffers.clear();
532 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800533 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800534 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800535 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800536 c2_status_t err = C2_OK;
537 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700538 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
539 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800540 {
541 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
542 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
543 for (const std::unique_ptr<C2Work> &work : items) {
544 watcher->onWorkQueued(
545 work->input.ordinal.frameIndex.peeku(),
546 std::vector(work->input.buffers),
547 now);
548 }
549 }
Sungtak Lee368452b2024-10-17 01:16:29 +0000550 err = std::atomic_load(&mComponent)->queue(&items);
Wonsik Kime1104ca2020-11-24 15:01:33 -0800551 }
552 if (err != C2_OK) {
553 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
554 for (const std::unique_ptr<C2Work> &work : items) {
555 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
556 }
557 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700558 Mutexed<Input>::Locked input(mInput);
559 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700560 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700561 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700562 } else if (buffer) {
563 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700564 }
565 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
566 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800567 }
568
569 feedInputBufferIfAvailableInternal();
570 return err;
571}
572
573status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
574 QueueGuard guard(mSync);
575 if (!guard.isRunning()) {
576 ALOGD("[%s] setParameters is only supported in the running state.", mName);
577 return -ENOSYS;
578 }
579 mParamsToBeSet.insert(mParamsToBeSet.end(),
580 std::make_move_iterator(params.begin()),
581 std::make_move_iterator(params.end()));
582 params.clear();
583 return OK;
584}
585
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800586status_t CCodecBufferChannel::attachBuffer(
587 const std::shared_ptr<C2Buffer> &c2Buffer,
588 const sp<MediaCodecBuffer> &buffer) {
589 if (!buffer->copy(c2Buffer)) {
590 return -ENOSYS;
591 }
592 return OK;
593}
594
595void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
596 if (!mDecryptDestination || mDecryptDestination->size() < size) {
597 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
598 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
599 mCrypto->unsetHeap(mHeapSeqNum);
600 }
601 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
602 if (mCrypto) {
603 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
604 }
605 }
606}
607
608int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
609 CHECK(mCrypto);
610 auto it = mHeapSeqNumMap.find(memory);
611 int32_t heapSeqNum = -1;
612 if (it == mHeapSeqNumMap.end()) {
613 heapSeqNum = mCrypto->setHeap(memory);
614 mHeapSeqNumMap.emplace(memory, heapSeqNum);
615 } else {
616 heapSeqNum = it->second;
617 }
618 return heapSeqNum;
619}
620
Arun Johnson564f3a92024-02-01 19:09:45 +0000621typedef WrapperObject<std::vector<AccessUnitInfo>> BufferInfosWrapper;
622typedef WrapperObject<std::vector<std::unique_ptr<CodecCryptoInfo>>> CryptoInfosWrapper;
623status_t CCodecBufferChannel::attachEncryptedBuffers(
624 const sp<hardware::HidlMemory> &memory,
625 size_t offset,
626 const sp<MediaCodecBuffer> &buffer,
627 bool secure,
628 AString* errorDetailMsg) {
629 static const C2MemoryUsage kDefaultReadWriteUsage{
630 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
631 if (!hasCryptoOrDescrambler()) {
632 ALOGE("attachEncryptedBuffers requires Crypto/descrambler object");
633 return -ENOSYS;
634 }
635 size_t size = 0;
636 CHECK(buffer->meta()->findSize("ssize", &size));
637 if (size == 0) {
638 buffer->setRange(0, 0);
639 return OK;
640 }
641 sp<RefBase> obj;
642 CHECK(buffer->meta()->findObject("cryptoInfos", &obj));
643 sp<CryptoInfosWrapper> cryptoInfos{(CryptoInfosWrapper *)obj.get()};
644 CHECK(buffer->meta()->findObject("accessUnitInfo", &obj));
645 sp<BufferInfosWrapper> bufferInfos{(BufferInfosWrapper *)obj.get()};
646 if (secure || (mCrypto == nullptr)) {
647 if (cryptoInfos->value.size() != 1) {
648 ALOGE("Cannot decrypt multiple access units");
649 return -ENOSYS;
650 }
651 // we are dealing with just one cryptoInfo or descrambler.
652 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[0]);
653 if (info == nullptr) {
654 ALOGE("Cannot decrypt, CryptoInfos are null.");
655 return -ENOSYS;
656 }
657 return attachEncryptedBuffer(
658 memory,
659 secure,
660 info->mKey,
661 info->mIv,
662 info->mMode,
663 info->mPattern,
664 offset,
665 info->mSubSamples,
666 info->mNumSubSamples,
667 buffer,
668 errorDetailMsg);
669 }
670 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
671 std::shared_ptr<C2LinearBlock> block;
672 c2_status_t err = pool->fetchLinearBlock(
673 size,
674 kDefaultReadWriteUsage,
675 &block);
676 if (err != C2_OK) {
677 ALOGI("[%s] attachEncryptedBuffers: fetchLinearBlock failed: size = %zu (%s) err = %d",
678 mName, size, secure ? "secure" : "non-secure", err);
679 return NO_MEMORY;
680 }
681 ensureDecryptDestination(size);
682 C2WriteView wView = block->map().get();
683 if (wView.error() != C2_OK) {
684 ALOGI("[%s] attachEncryptedBuffers: block map error: %d (non-secure)",
685 mName, wView.error());
686 return UNKNOWN_ERROR;
687 }
688
689 ssize_t result = -1;
Arun Johnson82174a12024-02-27 04:53:59 +0000690 size_t srcOffset = offset;
Arun Johnson564f3a92024-02-01 19:09:45 +0000691 size_t outBufferSize = 0;
692 uint32_t cryptoInfoIdx = 0;
693 int32_t heapSeqNum = getHeapSeqNum(memory);
694 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
695 hardware::drm::V1_0::DestinationBuffer dst;
696 dst.type = DrmBufferType::SHARED_MEMORY;
697 IMemoryToSharedBuffer(
698 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
699 for (int i = 0; i < bufferInfos->value.size(); i++) {
700 if (bufferInfos->value[i].mSize > 0) {
701 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[cryptoInfoIdx++]);
Arun Johnson82174a12024-02-27 04:53:59 +0000702 src.offset = srcOffset;
703 src.size = bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +0000704 result = mCrypto->decrypt(
705 (uint8_t*)info->mKey,
706 (uint8_t*)info->mIv,
707 info->mMode,
708 info->mPattern,
709 src,
Arun Johnson82174a12024-02-27 04:53:59 +0000710 0,
Arun Johnson564f3a92024-02-01 19:09:45 +0000711 info->mSubSamples,
712 info->mNumSubSamples,
713 dst,
714 errorDetailMsg);
Arun Johnson82174a12024-02-27 04:53:59 +0000715 srcOffset += bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +0000716 if (result < 0) {
717 ALOGI("[%s] attachEncryptedBuffers: decrypt failed: result = %zd",
718 mName, result);
719 return result;
720 }
721 if (wView.error() == C2_OK) {
722 if (wView.size() < result) {
723 ALOGI("[%s] attachEncryptedBuffers: block size too small:"
724 "size=%u result=%zd (non-secure)", mName, wView.size(), result);
725 return UNKNOWN_ERROR;
726 }
727 memcpy(wView.data(), mDecryptDestination->unsecurePointer(), result);
728 bufferInfos->value[i].mSize = result;
729 wView.setOffset(wView.offset() + result);
730 }
731 outBufferSize += result;
732 }
733 }
734 if (wView.error() == C2_OK) {
735 wView.setOffset(0);
736 }
737 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
Arun Johnson82174a12024-02-27 04:53:59 +0000738 block->share(0, outBufferSize, C2Fence{}))};
Arun Johnson564f3a92024-02-01 19:09:45 +0000739 if (!buffer->copy(c2Buffer)) {
740 ALOGI("[%s] attachEncryptedBuffers: buffer copy failed", mName);
741 return -ENOSYS;
742 }
743 return OK;
744}
745
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800746status_t CCodecBufferChannel::attachEncryptedBuffer(
747 const sp<hardware::HidlMemory> &memory,
748 bool secure,
749 const uint8_t *key,
750 const uint8_t *iv,
751 CryptoPlugin::Mode mode,
752 CryptoPlugin::Pattern pattern,
753 size_t offset,
754 const CryptoPlugin::SubSample *subSamples,
755 size_t numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000756 const sp<MediaCodecBuffer> &buffer,
757 AString* errorDetailMsg) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800758 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
759 static const C2MemoryUsage kDefaultReadWriteUsage{
760 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
761
762 size_t size = 0;
763 for (size_t i = 0; i < numSubSamples; ++i) {
764 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
765 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700766 if (size == 0) {
767 buffer->setRange(0, 0);
768 return OK;
769 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800770 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
771 std::shared_ptr<C2LinearBlock> block;
772 c2_status_t err = pool->fetchLinearBlock(
773 size,
774 secure ? kSecureUsage : kDefaultReadWriteUsage,
775 &block);
776 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700777 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
778 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800779 return NO_MEMORY;
780 }
781 if (!secure) {
782 ensureDecryptDestination(size);
783 }
784 ssize_t result = -1;
785 ssize_t codecDataOffset = 0;
786 if (mCrypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800787 int32_t heapSeqNum = getHeapSeqNum(memory);
788 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
789 hardware::drm::V1_0::DestinationBuffer dst;
790 if (secure) {
791 dst.type = DrmBufferType::NATIVE_HANDLE;
792 dst.secureMemory = hardware::hidl_handle(block->handle());
793 } else {
794 dst.type = DrmBufferType::SHARED_MEMORY;
795 IMemoryToSharedBuffer(
796 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
797 }
798 result = mCrypto->decrypt(
799 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000800 dst, errorDetailMsg);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800801 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700802 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800803 return result;
804 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800805 } else {
806 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
807 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
808 hidl_vec<SubSample> hidlSubSamples;
809 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
810
811 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
812 hardware::cas::native::V1_0::DestinationBuffer dst;
813 if (secure) {
814 dst.type = BufferType::NATIVE_HANDLE;
815 dst.secureMemory = hardware::hidl_handle(block->handle());
816 } else {
817 dst.type = BufferType::SHARED_MEMORY;
818 dst.nonsecureMemory = src;
819 }
820
821 CasStatus status = CasStatus::OK;
822 hidl_string detailedError;
823 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
824
825 if (key != nullptr) {
826 sctrl = (ScramblingControl)key[0];
827 // Adjust for the PES offset
828 codecDataOffset = key[2] | (key[3] << 8);
829 }
830
831 auto returnVoid = mDescrambler->descramble(
832 sctrl,
833 hidlSubSamples,
834 src,
835 0,
836 dst,
837 0,
838 [&status, &result, &detailedError] (
839 CasStatus _status, uint32_t _bytesWritten,
840 const hidl_string& _detailedError) {
841 status = _status;
842 result = (ssize_t)_bytesWritten;
843 detailedError = _detailedError;
844 });
Arun Johnson634d0802023-02-14 22:07:51 +0000845 if (errorDetailMsg) {
846 errorDetailMsg->setTo(detailedError.c_str(), detailedError.size());
847 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800848 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
849 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
850 mName, returnVoid.description().c_str(), status, result);
851 return UNKNOWN_ERROR;
852 }
853
854 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700855 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
856 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800857 return BAD_VALUE;
858 }
859 }
860 if (!secure) {
861 C2WriteView view = block->map().get();
862 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700863 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
864 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800865 return UNKNOWN_ERROR;
866 }
867 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700868 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
869 "(non-secure)",
870 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800871 return UNKNOWN_ERROR;
872 }
873 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
874 }
875 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
876 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
877 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700878 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800879 return -ENOSYS;
880 }
881 return OK;
882}
883
Pawin Vongmasa36653902018-11-15 00:10:25 -0800884status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
885 QueueGuard guard(mSync);
886 if (!guard.isRunning()) {
887 ALOGD("[%s] No more buffers should be queued at current state.", mName);
888 return -ENOSYS;
889 }
890 return queueInputBufferInternal(buffer);
891}
892
893status_t CCodecBufferChannel::queueSecureInputBuffer(
894 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
895 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
896 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
897 AString *errorDetailMsg) {
898 QueueGuard guard(mSync);
899 if (!guard.isRunning()) {
900 ALOGD("[%s] No more buffers should be queued at current state.", mName);
901 return -ENOSYS;
902 }
903
904 if (!hasCryptoOrDescrambler()) {
905 return -ENOSYS;
906 }
907 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
908
Sungtak Lee04b30352020-07-27 13:57:25 -0700909 std::shared_ptr<C2LinearBlock> block;
910 size_t allocSize = buffer->size();
911 size_t bufferSize = 0;
912 c2_status_t blockRes = C2_OK;
913 bool copied = false;
Arun Johnson7ba67072023-11-06 22:23:04 +0000914 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
915 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
Sungtak Lee04b30352020-07-27 13:57:25 -0700916 if (mSendEncryptedInfoBuffer) {
917 static const C2MemoryUsage kDefaultReadWriteUsage{
918 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
919 constexpr int kAllocGranule0 = 1024 * 64;
920 constexpr int kAllocGranule1 = 1024 * 1024;
921 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
922 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
923 if (allocSize <= kAllocGranule1) {
924 bufferSize = align(allocSize, kAllocGranule0);
925 } else {
926 bufferSize = align(allocSize, kAllocGranule1);
927 }
928 blockRes = pool->fetchLinearBlock(
929 bufferSize, kDefaultReadWriteUsage, &block);
930
931 if (blockRes == C2_OK) {
932 C2WriteView view = block->map().get();
933 if (view.error() == C2_OK && view.size() == bufferSize) {
934 copied = true;
935 // TODO: only copy clear sections
936 memcpy(view.data(), buffer->data(), allocSize);
937 }
938 }
939 }
940
941 if (!copied) {
942 block.reset();
943 }
944
Pawin Vongmasa36653902018-11-15 00:10:25 -0800945 ssize_t result = -1;
946 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700947 if (numSubSamples == 1
948 && subSamples[0].mNumBytesOfClearData == 0
949 && subSamples[0].mNumBytesOfEncryptedData == 0) {
950 // We don't need to go through crypto or descrambler if the input is empty.
951 result = 0;
952 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700953 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800954 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700955 destination.type = DrmBufferType::NATIVE_HANDLE;
956 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800957 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700958 destination.type = DrmBufferType::SHARED_MEMORY;
959 IMemoryToSharedBuffer(
960 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800961 }
Robert Shih895fba92019-07-16 16:29:44 -0700962 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800963 encryptedBuffer->fillSourceBuffer(&source);
964 result = mCrypto->decrypt(
965 key, iv, mode, pattern, source, buffer->offset(),
966 subSamples, numSubSamples, destination, errorDetailMsg);
967 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700968 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800969 return result;
970 }
Robert Shih895fba92019-07-16 16:29:44 -0700971 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800972 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
973 }
974 } else {
975 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
976 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
977 hidl_vec<SubSample> hidlSubSamples;
978 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
979
980 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
981 encryptedBuffer->fillSourceBuffer(&srcBuffer);
982
983 DestinationBuffer dstBuffer;
984 if (secure) {
985 dstBuffer.type = BufferType::NATIVE_HANDLE;
986 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
987 } else {
988 dstBuffer.type = BufferType::SHARED_MEMORY;
989 dstBuffer.nonsecureMemory = srcBuffer;
990 }
991
992 CasStatus status = CasStatus::OK;
993 hidl_string detailedError;
994 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
995
996 if (key != nullptr) {
997 sctrl = (ScramblingControl)key[0];
998 // Adjust for the PES offset
999 codecDataOffset = key[2] | (key[3] << 8);
1000 }
1001
1002 auto returnVoid = mDescrambler->descramble(
1003 sctrl,
1004 hidlSubSamples,
1005 srcBuffer,
1006 0,
1007 dstBuffer,
1008 0,
1009 [&status, &result, &detailedError] (
1010 CasStatus _status, uint32_t _bytesWritten,
1011 const hidl_string& _detailedError) {
1012 status = _status;
1013 result = (ssize_t)_bytesWritten;
1014 detailedError = _detailedError;
1015 });
1016
1017 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
1018 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
1019 mName, returnVoid.description().c_str(), status, result);
1020 return UNKNOWN_ERROR;
1021 }
1022
1023 if (result < codecDataOffset) {
1024 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
1025 return BAD_VALUE;
1026 }
1027
1028 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
1029
1030 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
1031 encryptedBuffer->copyDecryptedContentFromMemory(result);
1032 }
1033 }
1034
1035 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -07001036
1037 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001038}
1039
Arun Johnson564f3a92024-02-01 19:09:45 +00001040status_t CCodecBufferChannel::queueSecureInputBuffers(
1041 const sp<MediaCodecBuffer> &buffer,
1042 bool secure,
1043 AString *errorDetailMsg) {
1044 QueueGuard guard(mSync);
1045 if (!guard.isRunning()) {
1046 ALOGD("[%s] No more buffers should be queued at current state.", mName);
1047 return -ENOSYS;
1048 }
1049
1050 if (!hasCryptoOrDescrambler()) {
1051 ALOGE("queueSecureInputBuffers requires a Crypto/descrambler Object");
1052 return -ENOSYS;
1053 }
1054 sp<RefBase> obj;
1055 CHECK(buffer->meta()->findObject("cryptoInfos", &obj));
1056 sp<CryptoInfosWrapper> cryptoInfos{(CryptoInfosWrapper *)obj.get()};
1057 CHECK(buffer->meta()->findObject("accessUnitInfo", &obj));
1058 sp<BufferInfosWrapper> bufferInfos{(BufferInfosWrapper *)obj.get()};
1059 if (secure || mCrypto == nullptr) {
1060 if (cryptoInfos->value.size() != 1) {
1061 ALOGE("Cannot decrypt multiple access units on native handles");
1062 return -ENOSYS;
1063 }
1064 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[0]);
1065 if (info == nullptr) {
1066 ALOGE("Cannot decrypt, CryptoInfos are null");
1067 return -ENOSYS;
1068 }
1069 return queueSecureInputBuffer(
1070 buffer,
1071 secure,
1072 info->mKey,
1073 info->mIv,
1074 info->mMode,
1075 info->mPattern,
1076 info->mSubSamples,
1077 info->mNumSubSamples,
1078 errorDetailMsg);
1079 }
1080 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
1081
1082 std::shared_ptr<C2LinearBlock> block;
1083 size_t allocSize = buffer->size();
1084 size_t bufferSize = 0;
1085 c2_status_t blockRes = C2_OK;
1086 bool copied = false;
1087 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
1088 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
1089 if (mSendEncryptedInfoBuffer) {
1090 static const C2MemoryUsage kDefaultReadWriteUsage{
1091 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
1092 constexpr int kAllocGranule0 = 1024 * 64;
1093 constexpr int kAllocGranule1 = 1024 * 1024;
1094 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
1095 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
1096 if (allocSize <= kAllocGranule1) {
1097 bufferSize = align(allocSize, kAllocGranule0);
1098 } else {
1099 bufferSize = align(allocSize, kAllocGranule1);
1100 }
1101 blockRes = pool->fetchLinearBlock(
1102 bufferSize, kDefaultReadWriteUsage, &block);
1103
1104 if (blockRes == C2_OK) {
1105 C2WriteView view = block->map().get();
1106 if (view.error() == C2_OK && view.size() == bufferSize) {
1107 copied = true;
1108 // TODO: only copy clear sections
1109 memcpy(view.data(), buffer->data(), allocSize);
1110 }
1111 }
1112 }
1113
1114 if (!copied) {
1115 block.reset();
1116 }
1117 // size of cryptoInfo and accessUnitInfo should be the same?
1118 ssize_t result = -1;
Arun Johnson82174a12024-02-27 04:53:59 +00001119 size_t srcOffset = 0;
Arun Johnson564f3a92024-02-01 19:09:45 +00001120 size_t outBufferSize = 0;
1121 uint32_t cryptoInfoIdx = 0;
1122 {
1123 // scoped this block to enable destruction of mappedBlock
1124 std::unique_ptr<EncryptedLinearBlockBuffer::MappedBlock> mappedBlock = nullptr;
1125 hardware::drm::V1_0::DestinationBuffer destination;
1126 destination.type = DrmBufferType::SHARED_MEMORY;
1127 IMemoryToSharedBuffer(
1128 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
1129 encryptedBuffer->getMappedBlock(&mappedBlock);
1130 hardware::drm::V1_0::SharedBuffer source;
1131 encryptedBuffer->fillSourceBuffer(&source);
Arun Johnson82174a12024-02-27 04:53:59 +00001132 srcOffset = source.offset;
Arun Johnson564f3a92024-02-01 19:09:45 +00001133 for (int i = 0 ; i < bufferInfos->value.size(); i++) {
1134 if (bufferInfos->value[i].mSize > 0) {
1135 std::unique_ptr<CodecCryptoInfo> info =
1136 std::move(cryptoInfos->value[cryptoInfoIdx++]);
1137 if (info->mNumSubSamples == 1
1138 && info->mSubSamples[0].mNumBytesOfClearData == 0
1139 && info->mSubSamples[0].mNumBytesOfEncryptedData == 0) {
1140 // no data so we only populate the bufferInfo
1141 result = 0;
1142 } else {
Arun Johnson82174a12024-02-27 04:53:59 +00001143 source.offset = srcOffset;
1144 source.size = bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +00001145 result = mCrypto->decrypt(
1146 (uint8_t*)info->mKey,
1147 (uint8_t*)info->mIv,
1148 info->mMode,
1149 info->mPattern,
1150 source,
Arun Johnson82174a12024-02-27 04:53:59 +00001151 buffer->offset(),
Arun Johnson564f3a92024-02-01 19:09:45 +00001152 info->mSubSamples,
1153 info->mNumSubSamples,
1154 destination,
1155 errorDetailMsg);
Arun Johnson82174a12024-02-27 04:53:59 +00001156 srcOffset += bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +00001157 if (result < 0) {
1158 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
1159 return result;
1160 }
1161 if (destination.type == DrmBufferType::SHARED_MEMORY && mappedBlock) {
1162 mappedBlock->copyDecryptedContent(mDecryptDestination, result);
1163 }
1164 bufferInfos->value[i].mSize = result;
1165 outBufferSize += result;
1166 }
1167 }
1168 }
Arun Johnson82174a12024-02-27 04:53:59 +00001169 buffer->setRange(0, outBufferSize);
Arun Johnson564f3a92024-02-01 19:09:45 +00001170 }
1171 return queueInputBufferInternal(buffer, block, bufferSize);
1172}
1173
Pawin Vongmasa36653902018-11-15 00:10:25 -08001174void CCodecBufferChannel::feedInputBufferIfAvailable() {
1175 QueueGuard guard(mSync);
1176 if (!guard.isRunning()) {
1177 ALOGV("[%s] We're not running --- no input buffer reported", mName);
1178 return;
1179 }
1180 feedInputBufferIfAvailableInternal();
1181}
1182
1183void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +09001184 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001185 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -07001186 }
Wonsik Kimfca97a22024-08-30 20:20:42 +00001187 int64_t numOutputSlots = 0;
1188 bool outputFull = [this, &numOutputSlots]() {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001189 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimfca97a22024-08-30 20:20:42 +00001190 if (!output->buffers) {
1191 ALOGV("[%s] feedInputBufferIfAvailableInternal: "
1192 "return because output buffers are null", mName);
1193 return true;
1194 }
1195 numOutputSlots = int64_t(output->numSlots);
1196 if (output->buffers->hasPending() ||
Wonsik Kim3722abc2023-05-17 13:26:31 -07001197 (!output->bounded && output->buffers->numActiveSlots() >= output->numSlots)) {
Wonsik Kimfca97a22024-08-30 20:20:42 +00001198 ALOGV("[%s] feedInputBufferIfAvailableInternal: "
1199 "return because there are no room for more output buffers", mName);
1200 return true;
1201 }
1202 return false;
1203 }();
1204 if (android::media::codec::provider_->input_surface_throttle()) {
1205 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
1206 if (inputSurface->surface) {
1207 if (inputSurface->numProcessingBuffersBalance <= numOutputSlots) {
1208 ++inputSurface->numProcessingBuffersBalance;
1209 ALOGV("[%s] feedInputBufferIfAvailableInternal: numProcessingBuffersBalance = %lld",
1210 mName, static_cast<long long>(inputSurface->numProcessingBuffersBalance));
1211 inputSurface->surface->onInputBufferEmptied();
1212 }
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001213 }
1214 }
Wonsik Kimfca97a22024-08-30 20:20:42 +00001215 if (outputFull) {
1216 return;
Wonsik Kim1951d932024-05-23 22:59:00 +00001217 }
Wonsik Kim0487b782020-10-28 11:45:50 -07001218 size_t numActiveSlots = 0;
1219 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001220 sp<MediaCodecBuffer> inBuffer;
1221 size_t index;
1222 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001223 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -07001224 numActiveSlots = input->buffers->numActiveSlots();
1225 if (numActiveSlots >= input->numSlots) {
1226 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001227 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001228 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001229 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001230 break;
1231 }
1232 }
1233 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
1234 mCallback->onInputBufferAvailable(index, inBuffer);
1235 }
Wonsik Kim0487b782020-10-28 11:45:50 -07001236 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001237}
1238
1239status_t CCodecBufferChannel::renderOutputBuffer(
1240 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001241 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001242 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001243 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001244 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001245 Mutexed<Output>::Locked output(mOutput);
1246 if (output->buffers) {
1247 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001248 }
1249 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001250 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
1251 // set to true.
1252 sendOutputBuffers();
1253 // input buffer feeding may have been gated by pending output buffers
1254 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001255 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001256 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -07001257 std::call_once(mRenderWarningFlag, [this] {
1258 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
1259 "timestamp or render=true with non-video buffers. Apps should "
1260 "call releaseOutputBuffer() with render=false for those.",
1261 mName);
1262 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001263 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001264 return INVALID_OPERATION;
1265 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001266
1267#if 0
1268 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
1269 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
1270 for (const std::shared_ptr<const C2Info> &info : infoParams) {
1271 AString res;
1272 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
1273 if (ix) res.append(", ");
1274 res.append(*((int32_t*)info.get() + (ix / 4)));
1275 }
1276 ALOGV(" [%s]", res.c_str());
1277 }
1278#endif
1279 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
1280 std::static_pointer_cast<const C2StreamRotationInfo::output>(
1281 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
1282 bool flip = rotation && (rotation->flip & 1);
1283 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +09001284
1285 {
1286 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1287 if (output->surface == nullptr) {
1288 ALOGI("[%s] cannot render buffer without surface", mName);
1289 return OK;
1290 }
1291 int64_t frameIndex;
1292 buffer->meta()->findInt64("frameIndex", &frameIndex);
1293 if (output->rotation.count(frameIndex) != 0) {
1294 auto it = output->rotation.find(frameIndex);
1295 quarters = (it->second / 90) & 3;
1296 output->rotation.erase(it);
1297 }
1298 }
1299
Pawin Vongmasa36653902018-11-15 00:10:25 -08001300 uint32_t transform = 0;
1301 switch (quarters) {
1302 case 0: // no rotation
1303 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
1304 break;
1305 case 1: // 90 degrees counter-clockwise
1306 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
1307 : HAL_TRANSFORM_ROT_270;
1308 break;
1309 case 2: // 180 degrees
1310 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
1311 break;
1312 case 3: // 90 degrees clockwise
1313 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
1314 : HAL_TRANSFORM_ROT_90;
1315 break;
1316 }
1317
1318 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
1319 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
1320 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
1321 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
1322 if (surfaceScaling) {
1323 videoScalingMode = surfaceScaling->value;
1324 }
1325
1326 // Use dataspace from format as it has the default aspects already applied
1327 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
1328 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
1329
1330 // HDR static info
1331 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
1332 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
1333 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
1334
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001335 // HDR10 plus info
1336 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
1337 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
1338 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +08001339 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
1340 hdr10PlusInfo.reset();
1341 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001342
Wonsik Kima79c5522022-01-18 16:29:24 -08001343 // HDR dynamic info
1344 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
1345 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
1346 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
1347 // TODO: make this sticky & enable unset
1348 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
1349 hdrDynamicInfo.reset();
1350 }
1351
1352 if (hdr10PlusInfo) {
1353 // C2StreamHdr10PlusInfo is deprecated; components should use
1354 // C2StreamHdrDynamicMetadataInfo
1355 // TODO: #metric
1356 if (hdrDynamicInfo) {
1357 // It is unexpected that C2StreamHdr10PlusInfo and
1358 // C2StreamHdrDynamicMetadataInfo is both present.
1359 // C2StreamHdrDynamicMetadataInfo takes priority.
1360 // TODO: #metric
1361 } else {
1362 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
1363 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
1364 hdr10PlusInfo->flexCount(),
1365 0u,
1366 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
1367 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
1368 hdrDynamicInfo = info;
1369 }
1370 }
1371
Pawin Vongmasa36653902018-11-15 00:10:25 -08001372 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
1373 if (blocks.size() != 1u) {
1374 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
1375 return UNKNOWN_ERROR;
1376 }
1377 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -07001378 C2Fence c2fence = block.fence();
1379 sp<Fence> fence = Fence::NO_FENCE;
1380 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
1381 // Once C2Fence::type() is added, check the exact C2Fence type
1382 if (c2fence.isHW()) {
1383 int fenceFd = c2fence.fd();
1384 fence = sp<Fence>::make(fenceFd);
1385 if (!fence) {
1386 ALOGE("[%s] Failed to allocate a fence", mName);
1387 close(fenceFd);
1388 return NO_MEMORY;
1389 }
1390 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001391
1392 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -07001393 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 timestampNs,
1395 false, // droppable
1396 dataSpace,
1397 Rect(blocks.front().crop().left,
1398 blocks.front().crop().top,
1399 blocks.front().crop().right(),
1400 blocks.front().crop().bottom()),
1401 videoScalingMode,
1402 transform,
Lubin Yin92427a52022-04-18 16:57:39 -07001403 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -08001404 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001405 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001406 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +08001407 // If mastering max and min luminance fields are 0, do not use them.
1408 // It indicates the value may not be present in the stream.
1409 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
1410 hdrStaticInfo->mastering.minLuminance > 0.0f) {
1411 struct android_smpte2086_metadata smpte2086_meta = {
1412 .displayPrimaryRed = {
1413 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
1414 },
1415 .displayPrimaryGreen = {
1416 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
1417 },
1418 .displayPrimaryBlue = {
1419 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
1420 },
1421 .whitePoint = {
1422 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
1423 },
1424 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
1425 .minLuminance = hdrStaticInfo->mastering.minLuminance,
1426 };
Yichi Chen54be23c2020-06-15 14:30:53 +08001427 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +08001428 hdr.smpte2086 = smpte2086_meta;
1429 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -07001430 // If the content light level fields are 0, do not use them, it
1431 // indicates the value may not be present in the stream.
1432 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
1433 struct android_cta861_3_metadata cta861_meta = {
1434 .maxContentLightLevel = hdrStaticInfo->maxCll,
1435 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
1436 };
1437 hdr.validTypes |= HdrMetadata::CTA861_3;
1438 hdr.cta8613 = cta861_meta;
1439 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +09001440
1441 // does not have valid info
1442 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
1443 hdrStaticInfo.reset();
1444 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001445 }
Wonsik Kima79c5522022-01-18 16:29:24 -08001446 if (hdrDynamicInfo
1447 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001448 hdr.validTypes |= HdrMetadata::HDR10PLUS;
1449 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -08001450 hdrDynamicInfo->m.data,
1451 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001452 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001453 qbi.setHdrMetadata(hdr);
1454 }
Hongguangfc1478a2022-07-20 22:56:06 -07001455 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
1456
Brian Lindahl932bf602023-03-09 11:59:48 -07001457 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
1458 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
1459 IGraphicBufferProducer::QueueBufferOutput qbo;
Sungtak Lee368452b2024-10-17 01:16:29 +00001460 status_t result = std::atomic_load(&mComponent)->queueToOutputSurface(block, qbi, &qbo);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001461 if (result != OK) {
1462 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -08001463 if (result == NO_INIT) {
1464 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1465 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001466 return result;
1467 }
Josh Hou8eddf4b2021-02-02 16:26:53 +08001468
1469 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
1470 ALOGD("[%s] queue buffer successful", mName);
1471 } else {
1472 ALOGV("[%s] queue buffer successful", mName);
1473 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001474
1475 int64_t mediaTimeUs = 0;
1476 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahld7967a92023-08-10 10:12:49 -06001477 if (mAreRenderMetricsEnabled && mIsSurfaceToDisplay) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001478 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
1479 processRenderedFrames(qbo.frameTimestamps);
1480 } else {
1481 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
1482 // when the frame is queued to the non-display surface
1483 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1484 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001485
1486 return OK;
1487}
1488
Brian Lindahl932bf602023-03-09 11:59:48 -07001489void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001490 mTrackedFrames.clear();
1491
1492 int isSurfaceToDisplay = 0;
1493 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1494 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1495 // No frame tracking is needed if we're not sending frames to the display
1496 if (!mIsSurfaceToDisplay) {
1497 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1498 return;
1499 }
1500
Brian Lindahl932bf602023-03-09 11:59:48 -07001501 int hasPresentFenceTimes = 0;
1502 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1503 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
Brian Lindahl119e0c22023-05-19 15:42:13 -06001504 if (!mHasPresentFenceTimes) {
Brian Lindahl932bf602023-03-09 11:59:48 -07001505 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1506 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001507}
1508
1509void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1510 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1511 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1512 // so track the frame as if the desired render time is now.
1513 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1514 if (desiredRenderTimeNs < nowNs) {
1515 desiredRenderTimeNs = nowNs;
1516 }
Brian Lindahlc8bd9272023-08-28 09:42:43 -06001517
1518 // If the render time is more than a second from now, then pretend the frame is supposed to be
1519 // rendered immediately, because that's what SurfaceFlinger heuristics will do. This is a tight
1520 // coupling, but is really the only way to optimize away unnecessary present fence checks in
1521 // processRenderedFrames.
1522 if (desiredRenderTimeNs > nowNs + 1*1000*1000*1000LL) {
1523 desiredRenderTimeNs = nowNs;
1524 }
1525
Brian Lindahl932bf602023-03-09 11:59:48 -07001526 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1527 // actually rendered.
1528 TrackedFrame frame;
1529 frame.number = qbo.nextFrameNumber - 1;
1530 frame.mediaTimeUs = mediaTimeUs;
1531 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1532 frame.latchTime = -1;
1533 frame.presentFence = nullptr;
1534 mTrackedFrames.push_back(frame);
1535}
1536
1537void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1538 // Grab the latch times and present fences from the frame event deltas
1539 for (const auto& delta : deltas) {
1540 for (auto& frame : mTrackedFrames) {
1541 if (delta.getFrameNumber() == frame.number) {
1542 delta.getLatchTime(&frame.latchTime);
1543 delta.getDisplayPresentFence(&frame.presentFence);
1544 }
1545 }
1546 }
1547
1548 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1549 // in fact, been rendered.
1550 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1551 while (!mTrackedFrames.empty()) {
1552 TrackedFrame & frame = mTrackedFrames.front();
1553 // Frames that should have been rendered at least 100ms in the past are checked
1554 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1555 break;
1556 }
1557
1558 // If we don't have a render time by now, then consider the frame as dropped
1559 int64_t renderTimeNs = getRenderTimeNs(frame);
1560 if (renderTimeNs != -1) {
1561 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1562 }
1563 mTrackedFrames.pop_front();
1564 }
1565}
1566
1567int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1568 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1569 if (!mHasPresentFenceTimes) {
1570 if (frame.latchTime == -1) {
1571 ALOGD("no latch time for frame %d", (int) frame.number);
1572 return -1;
1573 }
1574 return frame.latchTime;
1575 }
1576
1577 if (frame.presentFence == nullptr) {
1578 ALOGW("no present fence for frame %d", (int) frame.number);
1579 return -1;
1580 }
1581
1582 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1583
1584 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1585 ALOGW("invalid signal time for frame %d", (int) frame.number);
1586 return -1;
1587 }
1588
1589 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1590 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1591 return -1;
1592 }
1593
1594 return actualRenderTimeNs;
1595}
1596
1597void CCodecBufferChannel::pollForRenderedBuffers() {
1598 FrameEventHistoryDelta delta;
Sungtak Lee368452b2024-10-17 01:16:29 +00001599 std::atomic_load(&mComponent)->pollForRenderedFrames(&delta);
Brian Lindahl932bf602023-03-09 11:59:48 -07001600 processRenderedFrames(delta);
1601}
1602
Sungtak Lee214ce612023-11-01 10:01:13 +00001603void CCodecBufferChannel::onBufferReleasedFromOutputSurface(uint32_t generation) {
Sungtak Lee6700cc92023-11-22 18:04:05 +00001604 // Note: Since this is called asynchronously from IProducerListener not
1605 // knowing the internal state of CCodec/CCodecBufferChannel,
1606 // prevent mComponent from being destroyed by holding the shared reference
1607 // during this interface being executed.
Sungtak Lee368452b2024-10-17 01:16:29 +00001608 std::shared_ptr<Codec2Client::Component> comp = std::atomic_load(&mComponent);
Sungtak Lee6700cc92023-11-22 18:04:05 +00001609 if (comp) {
Sungtak Leed1146682024-10-03 02:03:42 +00001610 SurfaceCallbackHandler::GetInstance().post(
1611 SurfaceCallbackHandler::ON_BUFFER_RELEASED, comp, generation);
Sungtak Lee6700cc92023-11-22 18:04:05 +00001612 }
Sungtak Lee214ce612023-11-01 10:01:13 +00001613}
1614
Sungtak Lee1720e4c2024-07-31 21:15:26 +00001615void CCodecBufferChannel::onBufferAttachedToOutputSurface(uint32_t generation) {
1616 // Note: Since this is called asynchronously from IProducerListener not
1617 // knowing the internal state of CCodec/CCodecBufferChannel,
1618 // prevent mComponent from being destroyed by holding the shared reference
1619 // during this interface being executed.
Sungtak Lee368452b2024-10-17 01:16:29 +00001620 std::shared_ptr<Codec2Client::Component> comp = std::atomic_load(&mComponent);
Sungtak Lee1720e4c2024-07-31 21:15:26 +00001621 if (comp) {
Sungtak Leed1146682024-10-03 02:03:42 +00001622 SurfaceCallbackHandler::GetInstance().post(
1623 SurfaceCallbackHandler::ON_BUFFER_ATTACHED, comp, generation);
Sungtak Lee1720e4c2024-07-31 21:15:26 +00001624 }
1625}
1626
Pawin Vongmasa36653902018-11-15 00:10:25 -08001627status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1628 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1629 bool released = false;
1630 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001631 Mutexed<Input>::Locked input(mInput);
1632 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001633 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001634 }
1635 }
1636 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001637 Mutexed<Output>::Locked output(mOutput);
1638 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001639 released = true;
1640 }
1641 }
1642 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001643 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001644 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001645 } else {
1646 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1647 }
1648 return OK;
1649}
1650
1651void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1652 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001653 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001654
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001655 if (!input->buffers) {
1656 ALOGE("getInputBufferArray: No Input Buffers allocated");
1657 return;
1658 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001659 if (!input->buffers->isArrayMode()) {
1660 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001661 }
1662
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001663 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001664}
1665
1666void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1667 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001668 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001669 if (!output->buffers) {
1670 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1671 return;
1672 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001673 if (!output->buffers->isArrayMode()) {
1674 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001675 }
1676
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001677 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001678}
1679
1680status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001681 const sp<AMessage> &inputFormat,
1682 const sp<AMessage> &outputFormat,
1683 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001684 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1685 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001686 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001687 C2PortReorderBufferDepthTuning::output reorderDepth;
1688 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001689 C2PortActualDelayTuning::input inputDelay(0);
1690 C2PortActualDelayTuning::output outputDelay(0);
1691 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001692 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001693
Sungtak Lee368452b2024-10-17 01:16:29 +00001694 c2_status_t err = std::atomic_load(&mComponent)->query(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001695 {
1696 &iStreamFormat,
1697 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001698 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001699 &reorderDepth,
1700 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001701 &inputDelay,
1702 &pipelineDelay,
1703 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001704 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001705 },
1706 {},
1707 C2_DONT_BLOCK,
1708 nullptr);
1709 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001710 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001711 return UNKNOWN_ERROR;
1712 }
1713 } else if (err != C2_OK) {
1714 return UNKNOWN_ERROR;
1715 }
1716
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001717 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1718 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1719 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1720
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001721 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1722 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001723
Pawin Vongmasa36653902018-11-15 00:10:25 -08001724 // TODO: get this from input format
Sungtak Lee368452b2024-10-17 01:16:29 +00001725 bool secure = std::atomic_load(&mComponent)->getName().find(".secure") != std::string::npos;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001726
Sungtak Lee04b30352020-07-27 13:57:25 -07001727 // secure mode is a static parameter (shall not change in the executing state)
1728 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1729
Pawin Vongmasa36653902018-11-15 00:10:25 -08001730 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001731 int poolMask = GetCodec2PoolMask();
1732 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001733
1734 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001735 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001736 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001737 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1738 API_REFLECTION |
1739 API_VALUES |
1740 API_CURRENT_VALUES |
1741 API_DEPENDENCY |
1742 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001743 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1744 C2StreamSampleRateInfo::input sampleRate(0u);
1745 C2StreamChannelCountInfo::input channelCount(0u);
1746 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001747 std::shared_ptr<C2BlockPool> pool;
1748 {
1749 Mutexed<BlockPools>::Locked pools(mBlockPools);
1750
1751 // set default allocator ID.
1752 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001753 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001754
1755 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1756 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1757 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001758 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001759 std::vector<C2Param *> stackParams({&featuresSetting});
1760 if (audioEncoder) {
1761 stackParams.push_back(&encoderFrameSize);
1762 stackParams.push_back(&sampleRate);
1763 stackParams.push_back(&channelCount);
1764 stackParams.push_back(&pcmEncoding);
1765 } else {
1766 encoderFrameSize.invalidate();
1767 sampleRate.invalidate();
1768 channelCount.invalidate();
1769 pcmEncoding.invalidate();
1770 }
Sungtak Lee368452b2024-10-17 01:16:29 +00001771 err = std::atomic_load(&mComponent)->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001772 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1773 C2_DONT_BLOCK,
1774 &params);
1775 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1776 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1777 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001778 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001779 C2PortAllocatorsTuning::input *inputAllocators =
1780 C2PortAllocatorsTuning::input::From(params[0].get());
1781 if (inputAllocators && inputAllocators->flexCount() > 0) {
1782 std::shared_ptr<C2Allocator> allocator;
1783 // verify allocator IDs and resolve default allocator
1784 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1785 if (allocator) {
1786 pools->inputAllocatorId = allocator->getId();
1787 } else {
1788 ALOGD("[%s] component requested invalid input allocator ID %u",
1789 mName, inputAllocators->m.values[0]);
1790 }
1791 }
1792 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001793 if (featuresSetting) {
1794 apiFeatures = featuresSetting.value;
1795 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001796
1797 // TODO: use C2Component wrapper to associate this pool with ourselves
1798 if ((poolMask >> pools->inputAllocatorId) & 1) {
1799 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1800 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1801 mName, pools->inputAllocatorId,
1802 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1803 asString(err), err);
1804 } else {
1805 err = C2_NOT_FOUND;
1806 }
1807 if (err != C2_OK) {
1808 C2BlockPool::local_id_t inputPoolId =
1809 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1810 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1811 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1812 mName, (unsigned long long)inputPoolId,
1813 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1814 asString(err), err);
1815 if (err != C2_OK) {
1816 return NO_MEMORY;
1817 }
1818 }
1819 pools->inputPool = pool;
1820 }
1821
Wonsik Kim51051262018-11-28 13:59:05 -08001822 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001823 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001824 input->inputDelay = inputDelayValue;
1825 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001826 input->numSlots = numInputSlots;
1827 input->extraBuffers.flush();
1828 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001829 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001830 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1831 input->frameReassembler.init(
1832 pool,
1833 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1834 encoderFrameSize.value,
1835 sampleRate.value,
1836 channelCount.value,
1837 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1838 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001839 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1840 // For encrypted content, framework decrypts source buffer (ashmem) into
1841 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001842 if (!buffersBoundToCodec
1843 && !input->frameReassembler
1844 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001845 input->buffers.reset(new SlotInputBuffers(mName));
1846 } else if (graphic) {
Wonsik Kimfca97a22024-08-30 20:20:42 +00001847 if (mHasInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001848 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001849 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001850 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001851 // This is to ensure buffers do not get released prematurely.
1852 // TODO: handle this without going into array mode
1853 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001854 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001855 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001856 }
1857 } else {
1858 if (hasCryptoOrDescrambler()) {
1859 int32_t capacity = kLinearBufferSize;
1860 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1861 if ((size_t)capacity > kMaxLinearBufferSize) {
1862 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1863 capacity = kMaxLinearBufferSize;
1864 }
1865 if (mDealer == nullptr) {
1866 mDealer = new MemoryDealer(
1867 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001868 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001869 "EncryptedLinearInputBuffers");
1870 mDecryptDestination = mDealer->allocate((size_t)capacity);
1871 }
1872 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001873 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1874 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001875 } else {
1876 mHeapSeqNum = -1;
1877 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001878 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001879 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001880 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001881 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001882 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001883 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001884 }
1885 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001886 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001887
1888 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001889 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001890 } else {
1891 // TODO: error
1892 }
Wonsik Kim51051262018-11-28 13:59:05 -08001893
1894 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001895 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001896 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001897 }
1898
1899 if (outputFormat != nullptr) {
1900 sp<IGraphicBufferProducer> outputSurface;
1901 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001902 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001903 {
1904 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001905 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001906 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001907 outputSurface = output->surface ?
1908 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001909 if (outputSurface) {
Sungtak Leed1146682024-10-03 02:03:42 +00001910 (void)SurfaceCallbackHandler::GetInstance();
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001911 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1912 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001913 outputGeneration = output->generation;
1914 }
1915
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001916 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001917 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001918 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001919
1920 {
1921 Mutexed<BlockPools>::Locked pools(mBlockPools);
1922
David Stevensc3fbb282021-01-18 18:11:20 +09001923 prevOutputPoolId = pools->outputPoolId;
1924
Pawin Vongmasa36653902018-11-15 00:10:25 -08001925 // set default allocator ID.
1926 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001927 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001928
1929 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1930 // unsuccessful.
1931 std::vector<std::unique_ptr<C2Param>> params;
Sungtak Lee368452b2024-10-17 01:16:29 +00001932 err = std::atomic_load(&mComponent)->query({ },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001933 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1934 C2_DONT_BLOCK,
1935 &params);
1936 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1937 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1938 mName, params.size(), asString(err), err);
1939 } else if (err == C2_OK && params.size() == 1) {
1940 C2PortAllocatorsTuning::output *outputAllocators =
1941 C2PortAllocatorsTuning::output::From(params[0].get());
1942 if (outputAllocators && outputAllocators->flexCount() > 0) {
1943 std::shared_ptr<C2Allocator> allocator;
1944 // verify allocator IDs and resolve default allocator
1945 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1946 if (allocator) {
1947 pools->outputAllocatorId = allocator->getId();
1948 } else {
1949 ALOGD("[%s] component requested invalid output allocator ID %u",
1950 mName, outputAllocators->m.values[0]);
1951 }
1952 }
1953 }
1954
1955 // use bufferqueue if outputting to a surface.
1956 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1957 // if unsuccessful.
1958 if (outputSurface) {
1959 params.clear();
Sungtak Lee368452b2024-10-17 01:16:29 +00001960 err = std::atomic_load(&mComponent)->query({ },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001961 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1962 C2_DONT_BLOCK,
1963 &params);
1964 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1965 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1966 mName, params.size(), asString(err), err);
1967 } else if (err == C2_OK && params.size() == 1) {
1968 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1969 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1970 if (surfaceAllocator) {
1971 std::shared_ptr<C2Allocator> allocator;
1972 // verify allocator IDs and resolve default allocator
1973 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1974 if (allocator) {
1975 pools->outputAllocatorId = allocator->getId();
1976 } else {
1977 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1978 mName, surfaceAllocator->value);
1979 err = C2_BAD_VALUE;
1980 }
1981 }
1982 }
1983 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1984 && err != C2_OK
1985 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1986 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1987 }
1988 }
1989
1990 if ((poolMask >> pools->outputAllocatorId) & 1) {
Sungtak Lee368452b2024-10-17 01:16:29 +00001991 err = std::atomic_load(&mComponent)->createBlockPool(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001992 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1993 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1994 mName, pools->outputAllocatorId,
1995 (unsigned long long)pools->outputPoolId,
1996 asString(err));
1997 } else {
1998 err = C2_NOT_FOUND;
1999 }
2000 if (err != C2_OK) {
2001 // use basic pool instead
2002 pools->outputPoolId =
2003 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
2004 }
2005
2006 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
2007 // component.
2008 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
2009 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
2010
2011 std::vector<std::unique_ptr<C2SettingResult>> failures;
Sungtak Lee368452b2024-10-17 01:16:29 +00002012 err = std::atomic_load(&mComponent)->config(
2013 { poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002014 ALOGD("[%s] Configured output block pool ids %llu => %s",
2015 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
2016 outputPoolId_ = pools->outputPoolId;
2017 }
2018
David Stevensc3fbb282021-01-18 18:11:20 +09002019 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
2020 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
Sungtak Lee368452b2024-10-17 01:16:29 +00002021 c2_status_t err = std::atomic_load(&mComponent)->destroyBlockPool(prevOutputPoolId);
David Stevensc3fbb282021-01-18 18:11:20 +09002022 if (err != C2_OK) {
2023 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
2024 (unsigned long long) prevOutputPoolId, asString(err), err);
2025 }
2026 }
2027
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002028 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07002029 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002030 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07002031 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002032 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002033 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002034 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002035 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07002036 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002037 }
2038 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002039 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002040 }
Wonsik Kime4716c02020-02-28 10:42:21 -08002041 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002042
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002043 output->buffers->clearStash();
2044 if (reorderDepth) {
2045 output->buffers->setReorderDepth(reorderDepth.value);
2046 }
2047 if (reorderKey) {
2048 output->buffers->setReorderKey(reorderKey.value);
2049 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002050
2051 // Try to set output surface to created block pool if given.
2052 if (outputSurface) {
Sungtak Lee368452b2024-10-17 01:16:29 +00002053 std::atomic_load(&mComponent)->setOutputSurface(
Pawin Vongmasa36653902018-11-15 00:10:25 -08002054 outputPoolId_,
2055 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002056 outputGeneration,
2057 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08002058 } else {
2059 // configure CPU read consumer usage
2060 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
2061 std::vector<std::unique_ptr<C2SettingResult>> failures;
Sungtak Lee368452b2024-10-17 01:16:29 +00002062 err = std::atomic_load(&mComponent)->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08002063 // do not print error message for now as most components may not yet
2064 // support this setting
2065 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
2066 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002067 }
2068
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07002069 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08002070 if (buffersBoundToCodec) {
2071 // WORKAROUND: if we're using early CSD workaround we convert to
2072 // array mode, to appease apps assuming the output
2073 // buffers to be of the same size.
2074 output->buffers = output->buffers->toArrayMode(numOutputSlots);
2075 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002076
2077 int32_t channelCount;
2078 int32_t sampleRate;
2079 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
2080 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
2081 int32_t delay = 0;
2082 int32_t padding = 0;;
2083 if (!outputFormat->findInt32("encoder-delay", &delay)) {
2084 delay = 0;
2085 }
2086 if (!outputFormat->findInt32("encoder-padding", &padding)) {
2087 padding = 0;
2088 }
2089 if (delay || padding) {
Arun Johnson52d323e2024-01-05 21:16:56 +00002090 // We need write access to the buffers, so turn them into array mode.
2091 // TODO: b/321930152 - define SkipCutOutputBuffers that takes output from
2092 // component, runs it through SkipCutBuffer and allocate local buffer to be
2093 // used by fwk. Make initSkipCutBuffer() return OutputBuffers similar to
2094 // toArrayMode().
2095 if (!output->buffers->isArrayMode()) {
2096 output->buffers = output->buffers->toArrayMode(numOutputSlots);
2097 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002098 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002099 }
2100 }
2101 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002102
2103 int32_t tunneled = 0;
2104 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
2105 tunneled = 0;
2106 }
2107 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002108 }
2109
2110 // Set up pipeline control. This has to be done after mInputBuffers and
2111 // mOutputBuffers are initialized to make sure that lingering callbacks
2112 // about buffers from the previous generation do not interfere with the
2113 // newly initialized pipeline capacity.
2114
Wonsik Kim62545252021-01-20 11:25:41 -08002115 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002116 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002117 watcher->inputDelay(inputDelayValue)
2118 .pipelineDelay(pipelineDelayValue)
2119 .outputDelay(outputDelayValue)
Houxiang Dai0b573282023-03-11 18:31:56 +08002120 .smoothnessFactor(kSmoothnessFactor)
2121 .tunneled(mTunneled);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002122 watcher->flush();
2123 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002124
2125 mInputMetEos = false;
2126 mSync.start();
2127 return OK;
2128}
2129
Wonsik Kim34b28b42022-05-20 15:49:32 -07002130status_t CCodecBufferChannel::prepareInitialInputBuffers(
Arun Johnson326166e2023-07-28 19:11:52 +00002131 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers, bool retry) {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002132 if (mHasInputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002133 return OK;
2134 }
2135
Wonsik Kim34b28b42022-05-20 15:49:32 -07002136 size_t numInputSlots = mInput.lock()->numSlots;
Arun Johnson326166e2023-07-28 19:11:52 +00002137 int retryCount = 1;
2138 for (; clientInputBuffers->empty() && retryCount >= 0; retryCount--) {
2139 {
2140 Mutexed<Input>::Locked input(mInput);
2141 while (clientInputBuffers->size() < numInputSlots) {
2142 size_t index;
2143 sp<MediaCodecBuffer> buffer;
2144 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
2145 break;
2146 }
2147 clientInputBuffers->emplace(index, buffer);
Wonsik Kim34b28b42022-05-20 15:49:32 -07002148 }
Arun Johnson326166e2023-07-28 19:11:52 +00002149 }
2150 if (!retry || (retryCount <= 0)) {
2151 break;
2152 }
2153 if (clientInputBuffers->empty()) {
2154 // wait: buffer may be in transit from component.
2155 std::this_thread::sleep_for(std::chrono::milliseconds(4));
Wonsik Kim34b28b42022-05-20 15:49:32 -07002156 }
2157 }
2158 if (clientInputBuffers->empty()) {
2159 ALOGW("[%s] start: cannot allocate memory at all", mName);
2160 return NO_MEMORY;
2161 } else if (clientInputBuffers->size() < numInputSlots) {
2162 ALOGD("[%s] start: cannot allocate memory for all slots, "
2163 "only %zu buffers allocated",
2164 mName, clientInputBuffers->size());
2165 } else {
2166 ALOGV("[%s] %zu initial input buffers available",
2167 mName, clientInputBuffers->size());
2168 }
2169 return OK;
2170}
2171
2172status_t CCodecBufferChannel::requestInitialInputBuffers(
2173 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Wonsik Kim8f67e732024-10-19 04:13:05 +00002174 std::optional<QueueGuard> guard;
2175 if (android::media::codec::provider_->codec_buffer_state_cleanup()) {
2176 guard.emplace(mSync);
2177 if (!guard->isRunning()) {
2178 ALOGD("[%s] skip requestInitialInputBuffers when not running", mName);
2179 return OK;
2180 }
2181 }
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002182 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07002183 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Sungtak Lee368452b2024-10-17 01:16:29 +00002184 c2_status_t err = std::atomic_load(&mComponent)->query(
2185 { &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07002186 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002187 return UNKNOWN_ERROR;
2188 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002189
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002190 std::list<std::unique_ptr<C2Work>> flushedConfigs;
2191 mFlushedConfigs.lock()->swap(flushedConfigs);
2192 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07002193 {
2194 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2195 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
2196 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
2197 watcher->onWorkQueued(
2198 work->input.ordinal.frameIndex.peeku(),
2199 std::vector(work->input.buffers),
2200 now);
2201 }
2202 }
Sungtak Lee368452b2024-10-17 01:16:29 +00002203 err = std::atomic_load(&mComponent)->queue(&flushedConfigs);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002204 if (err != C2_OK) {
2205 ALOGW("[%s] Error while queueing a flushed config", mName);
2206 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002207 }
2208 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002209 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07002210 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
2211 !clientInputBuffers.empty()) {
2212 size_t minIndex = clientInputBuffers.begin()->first;
2213 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
2214 for (const auto &[index, buffer] : clientInputBuffers) {
2215 if (minBuffer->capacity() > buffer->capacity()) {
2216 minIndex = index;
2217 minBuffer = buffer;
2218 }
2219 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002220 // WORKAROUND: Some apps expect CSD available without queueing
2221 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07002222 minBuffer->setRange(0, 0);
2223 minBuffer->meta()->clear();
2224 minBuffer->meta()->setInt64("timeUs", 0);
2225 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002226 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
2227 mName);
2228 return UNKNOWN_ERROR;
2229 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07002230 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002231 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002232
Wonsik Kim34b28b42022-05-20 15:49:32 -07002233 for (const auto &[index, buffer] : clientInputBuffers) {
2234 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002235 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002236
Pawin Vongmasa36653902018-11-15 00:10:25 -08002237 return OK;
2238}
2239
2240void CCodecBufferChannel::stop() {
2241 mSync.stop();
2242 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302243 mInfoBuffers.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002244}
2245
Sungtak Lee99144332023-01-26 11:03:14 +00002246void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
2247 sp<Surface> surface = mOutputSurface.lock()->surface;
2248 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00002249 C2BlockPool::local_id_t outputPoolId;
2250 {
2251 Mutexed<BlockPools>::Locked pools(mBlockPools);
2252 outputPoolId = pools->outputPoolId;
2253 }
Sungtak Lee368452b2024-10-17 01:16:29 +00002254 std::shared_ptr<Codec2Client::Component> comp = std::atomic_load(&mComponent);
2255 if (comp) comp->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00002256
2257 if (pushBlankBuffer) {
2258 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
2259 if (anw) {
2260 pushBlankBuffersToNativeWindow(anw.get());
2261 }
2262 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00002263 }
2264}
2265
Wonsik Kim936a89c2020-05-08 16:07:50 -07002266void CCodecBufferChannel::reset() {
2267 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08002268 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002269 {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002270 mHasInputSurface = false;
2271 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
2272 inputSurface->surface.reset();
2273 }
2274 {
Wonsik Kim936a89c2020-05-08 16:07:50 -07002275 Mutexed<Input>::Locked input(mInput);
2276 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002277 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002278 }
2279 {
2280 Mutexed<Output>::Locked output(mOutput);
2281 output->buffers.reset();
2282 }
Brian Lindahl932bf602023-03-09 11:59:48 -07002283 // reset the frames that are being tracked for onFrameRendered callbacks
2284 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002285}
2286
2287void CCodecBufferChannel::release() {
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302288 mInfoBuffers.clear();
Sungtak Lee368452b2024-10-17 01:16:29 +00002289 std::shared_ptr<Codec2Client::Component> nullComp;
2290 std::atomic_store(&mComponent, nullComp);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002291 mInputAllocator.reset();
2292 mOutputSurface.lock()->surface.clear();
2293 {
2294 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
2295 blockPools->inputPool.reset();
2296 blockPools->outputPoolIntf.reset();
2297 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002298 setCrypto(nullptr);
2299 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002300}
2301
Pawin Vongmasa36653902018-11-15 00:10:25 -08002302void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
2303 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002304 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002305 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07002306 {
2307 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2308 for (const std::unique_ptr<C2Work> &work : flushedWork) {
2309 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
2310 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
2311 watcher->onWorkDone(frameIndex);
2312 continue;
2313 }
2314 if (work->input.buffers.empty()
2315 || work->input.buffers.front() == nullptr
2316 || work->input.buffers.front()->data().linearBlocks().empty()) {
2317 ALOGD("[%s] no linear codec config data found", mName);
2318 watcher->onWorkDone(frameIndex);
2319 continue;
2320 }
2321 std::unique_ptr<C2Work> copy(new C2Work);
2322 copy->input.flags = C2FrameData::flags_t(
2323 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
2324 copy->input.ordinal = work->input.ordinal;
2325 copy->input.ordinal.frameIndex = mFrameIndex++;
2326 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
2327 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
2328 }
2329 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
2330 copy->input.configUpdate.push_back(C2Param::Copy(*param));
2331 }
2332 copy->input.infoBuffers.insert(
2333 copy->input.infoBuffers.begin(),
2334 work->input.infoBuffers.begin(),
2335 work->input.infoBuffers.end());
2336 copy->worklets.emplace_back(new C2Worklet);
2337 configs.push_back(std::move(copy));
2338 watcher->onWorkDone(frameIndex);
2339 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002340 }
2341 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002342 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002343 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002344 Mutexed<Input>::Locked input(mInput);
2345 input->buffers->flush();
2346 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002347 }
2348 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002349 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002350 if (output->buffers) {
2351 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002352 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002353 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002354 }
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302355 mInfoBuffers.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002356}
2357
2358void CCodecBufferChannel::onWorkDone(
2359 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002360 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002361 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002362 feedInputBufferIfAvailable();
2363 }
2364}
2365
2366void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08002367 uint64_t frameIndex, size_t arrayIndex) {
2368 std::shared_ptr<C2Buffer> buffer =
2369 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002370 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002371 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002372 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002373 if (input->lastFlushIndex >= frameIndex) {
2374 ALOGD("[%s] Ignoring stale input buffer done callback: "
2375 "last flush index = %lld, frameIndex = %lld",
2376 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
2377 } else {
2378 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
2379 if (!newInputSlotAvailable) {
2380 (void)input->extraBuffers.expireComponentBuffer(buffer);
2381 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002382 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002383 }
2384 if (newInputSlotAvailable) {
2385 feedInputBufferIfAvailable();
2386 }
2387}
2388
2389bool CCodecBufferChannel::handleWork(
2390 std::unique_ptr<C2Work> work,
2391 const sp<AMessage> &outputFormat,
2392 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07002393 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00002394 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002395 if (!output->buffers) {
2396 return false;
2397 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08002398 }
2399
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002400 // Whether the output buffer should be reported to the client or not.
2401 bool notifyClient = false;
2402
2403 if (work->result == C2_OK){
2404 notifyClient = true;
2405 } else if (work->result == C2_NOT_FOUND) {
2406 ALOGD("[%s] flushed work; ignored.", mName);
2407 } else {
2408 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
2409 // the config update.
2410 ALOGD("[%s] work failed to complete: %d", mName, work->result);
2411 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
2412 return false;
2413 }
2414
2415 if ((work->input.ordinal.frameIndex -
2416 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002417 // Discard frames from previous generation.
2418 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002419 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002420 }
2421
Wonsik Kimfca97a22024-08-30 20:20:42 +00002422 if (!mHasInputSurface && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08002423 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002424 || !(work->worklets.front()->output.flags &
2425 C2FrameData::FLAG_INCOMPLETE))) {
2426 mPipelineWatcher.lock()->onWorkDone(
2427 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002428 }
2429
2430 // NOTE: MediaCodec usage supposedly have only one worklet
2431 if (work->worklets.size() != 1u) {
2432 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
2433 mName, work->worklets.size());
2434 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2435 return false;
2436 }
2437
2438 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
2439
2440 std::shared_ptr<C2Buffer> buffer;
2441 // NOTE: MediaCodec usage supposedly have only one output stream.
2442 if (worklet->output.buffers.size() > 1u) {
2443 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
2444 mName, worklet->output.buffers.size());
2445 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2446 return false;
2447 } else if (worklet->output.buffers.size() == 1u) {
2448 buffer = worklet->output.buffers[0];
2449 if (!buffer) {
2450 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
2451 }
2452 }
2453
Wonsik Kim3dedf682021-05-03 10:57:09 -07002454 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
2455 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002456 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002457 while (!worklet->output.configUpdate.empty()) {
2458 std::unique_ptr<C2Param> param;
2459 worklet->output.configUpdate.back().swap(param);
2460 worklet->output.configUpdate.pop_back();
2461 switch (param->coreIndex().coreIndex()) {
2462 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
2463 C2PortReorderBufferDepthTuning::output reorderDepth;
2464 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002465 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
2466 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002467 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002468 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002469 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002470 ALOGD("[%s] onWorkDone: failed to read reorder depth",
2471 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002472 }
2473 break;
2474 }
2475 case C2PortReorderKeySetting::CORE_INDEX: {
2476 C2PortReorderKeySetting::output reorderKey;
2477 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07002478 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002479 ALOGV("[%s] onWorkDone: updated reorder key to %u",
2480 mName, reorderKey.value);
2481 } else {
2482 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
2483 }
2484 break;
2485 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002486 case C2PortActualDelayTuning::CORE_INDEX: {
2487 if (param->isGlobal()) {
2488 C2ActualPipelineDelayTuning pipelineDelay;
2489 if (pipelineDelay.updateFrom(*param)) {
2490 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
2491 mName, pipelineDelay.value);
2492 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002493 (void)mPipelineWatcher.lock()->pipelineDelay(
2494 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002495 }
2496 }
2497 if (param->forInput()) {
2498 C2PortActualDelayTuning::input inputDelay;
2499 if (inputDelay.updateFrom(*param)) {
2500 ALOGV("[%s] onWorkDone: updating input delay %u",
2501 mName, inputDelay.value);
2502 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002503 (void)mPipelineWatcher.lock()->inputDelay(
2504 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002505 }
2506 }
2507 if (param->forOutput()) {
2508 C2PortActualDelayTuning::output outputDelay;
2509 if (outputDelay.updateFrom(*param)) {
2510 ALOGV("[%s] onWorkDone: updating output delay %u",
2511 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002512 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002513 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002514 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002515
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002516 }
2517 }
2518 break;
2519 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08002520 case C2PortTunnelSystemTime::CORE_INDEX: {
2521 C2PortTunnelSystemTime::output frameRenderTime;
2522 if (frameRenderTime.updateFrom(*param)) {
2523 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
2524 mName, (long long)frameRenderTime.value,
2525 (long long)worklet->output.ordinal.timestamp.peekll());
2526 mCCodecCallback->onOutputFramesRendered(
2527 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
2528 }
2529 break;
2530 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02002531 case C2StreamTunnelHoldRender::CORE_INDEX: {
2532 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
2533 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
2534 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
2535 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
2536 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
2537 mCCodecCallback->onFirstTunnelFrameReady();
2538 break;
2539 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002540 default:
2541 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2542 mName, param->index());
2543 break;
2544 }
2545 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002546 if (newInputDelay || newPipelineDelay) {
2547 Mutexed<Input>::Locked input(mInput);
2548 size_t newNumSlots =
2549 newInputDelay.value_or(input->inputDelay) +
2550 newPipelineDelay.value_or(input->pipelineDelay) +
2551 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08002552 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002553 if (input->buffers->isArrayMode()) {
2554 if (input->numSlots >= newNumSlots) {
2555 input->numExtraSlots = 0;
2556 } else {
2557 input->numExtraSlots = newNumSlots - input->numSlots;
2558 }
2559 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2560 mName, input->numExtraSlots);
2561 } else {
2562 input->numSlots = newNumSlots;
2563 }
2564 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002565 size_t numOutputSlots = 0;
2566 uint32_t reorderDepth = 0;
2567 bool outputBuffersChanged = false;
2568 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2569 Mutexed<Output>::Locked output(mOutput);
2570 if (!output->buffers) {
2571 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002572 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002573 numOutputSlots = output->numSlots;
2574 if (newReorderKey) {
2575 output->buffers->setReorderKey(newReorderKey.value());
2576 }
2577 if (newReorderDepth) {
2578 output->buffers->setReorderDepth(newReorderDepth.value());
2579 }
2580 reorderDepth = output->buffers->getReorderDepth();
2581 if (newOutputDelay) {
2582 output->outputDelay = newOutputDelay.value();
2583 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2584 if (output->numSlots < numOutputSlots) {
2585 output->numSlots = numOutputSlots;
2586 if (output->buffers->isArrayMode()) {
2587 OutputBuffersArray *array =
2588 (OutputBuffersArray *)output->buffers.get();
2589 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2590 mName, numOutputSlots);
2591 array->grow(numOutputSlots);
2592 outputBuffersChanged = true;
2593 }
2594 }
2595 }
2596 numOutputSlots = output->numSlots;
2597 }
2598 if (outputBuffersChanged) {
2599 mCCodecCallback->onOutputBuffersChanged();
2600 }
2601 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002602 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002603 {
2604 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2605 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002606 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002607 if (output->surface) {
2608 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2609 }
2610 }
2611 if (maxDequeueCount > 0) {
Sungtak Lee368452b2024-10-17 01:16:29 +00002612 std::atomic_load(&mComponent)->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002613 }
2614 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002615
Pawin Vongmasa36653902018-11-15 00:10:25 -08002616 int32_t flags = 0;
2617 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002618 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002619 ALOGV("[%s] onWorkDone: output EOS", mName);
2620 }
2621
Pawin Vongmasa36653902018-11-15 00:10:25 -08002622 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2623 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2624 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2625 // shall correspond to the client input timesamp (in customOrdinal). By using the
2626 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2627 // produces multiple output.
2628 c2_cntr64_t timestamp =
2629 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2630 - work->input.ordinal.timestamp;
Wonsik Kimfca97a22024-08-30 20:20:42 +00002631 if (mHasInputSurface) {
Wonsik Kim95ba0162019-03-19 15:51:54 -07002632 // When using input surface we need to restore the original input timestamp.
2633 timestamp = work->input.ordinal.customOrdinal;
2634 }
My Name6bd9a7d2022-03-25 12:37:58 -07002635 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2636 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002637 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2638 mName,
2639 work->input.ordinal.customOrdinal.peekll(),
2640 work->input.ordinal.timestamp.peekll(),
2641 worklet->output.ordinal.timestamp.peekll(),
2642 timestamp.peekll());
2643
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002644 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002645 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002646 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002647 if (!output->buffers) {
2648 return false;
2649 }
2650 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002651 output->buffers->updateSkipCutBuffer(outputFormat);
2652 output->buffers->setFormat(outputFormat);
2653 }
2654 if (!notifyClient) {
2655 return false;
2656 }
2657 size_t index;
2658 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002659 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002660 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002661 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002662 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2663
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002664 // TRICKY: we want popped buffers reported in order, so sending
2665 // the callback while holding the lock here. This assumes that
2666 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2667 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002668 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002669 } else {
2670 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002671 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002672 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002673 return false;
2674 }
2675 }
2676
Wonsik Kimec585c32021-10-01 01:11:00 -07002677 bool drop = false;
2678 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2679 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2680 drop = true;
2681 }
2682
Marc Kassisec910342022-11-25 11:43:05 +01002683 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2684 // HAL, the flag is then removed in the corresponding output buffer.
2685 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2686 flags |= BUFFER_FLAG_DECODE_ONLY;
2687 }
2688
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002689 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002690 if (mTunneled && drop && outputFormat) {
Houxiang Daie74e5062022-05-19 15:32:54 +08002691 if (mOutputFormat != outputFormat) {
2692 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2693 mName, work->input.ordinal.frameIndex.peekull());
2694 mOutputFormat = outputFormat;
2695 } else {
2696 ALOGV("[%s] onWorkDone: Not reporting output buffer without format change (%lld)",
2697 mName, work->input.ordinal.frameIndex.peekull());
2698 notifyClient = false;
2699 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002700 } else {
2701 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2702 mName, work->input.ordinal.frameIndex.peekull());
2703 notifyClient = false;
2704 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002705 }
2706
2707 if (buffer) {
2708 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2709 // TODO: properly translate these to metadata
2710 switch (info->coreIndex().coreIndex()) {
2711 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002712 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002713 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002714 }
2715 break;
2716 default:
2717 break;
2718 }
2719 }
2720 }
2721
2722 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002723 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002724 if (!output->buffers) {
2725 return false;
2726 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002727 output->buffers->pushToStash(
2728 buffer,
2729 notifyClient,
2730 timestamp.peek(),
2731 flags,
2732 outputFormat,
2733 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002734 }
2735 sendOutputBuffers();
2736 return true;
2737}
2738
2739void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002740 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002741 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002742 sp<MediaCodecBuffer> outBuffer;
2743 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002744
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002745 constexpr int kMaxReallocTry = 5;
2746 int reallocTryNum = 0;
2747
Pawin Vongmasa36653902018-11-15 00:10:25 -08002748 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002749 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002750 if (!output->buffers) {
2751 return;
2752 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002753 action = output->buffers->popFromStashAndRegister(
2754 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002755 if (action != OutputBuffers::REALLOCATE) {
2756 reallocTryNum = 0;
2757 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002758 switch (action) {
2759 case OutputBuffers::SKIP:
2760 return;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002761 case OutputBuffers::NOTIFY_CLIENT:
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002762 {
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002763 // TRICKY: we want popped buffers reported in order, so sending
2764 // the callback while holding the lock here. This assumes that
2765 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2766 // callbacks are always sent with the Output lock held.
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002767 if (c2Buffer) {
2768 std::shared_ptr<const C2AccessUnitInfos::output> bufferMetadata =
2769 std::static_pointer_cast<const C2AccessUnitInfos::output>(
2770 c2Buffer->getInfo(C2AccessUnitInfos::output::PARAM_TYPE));
2771 if (bufferMetadata && bufferMetadata->flexCount() > 0) {
2772 uint32_t flag = 0;
2773 std::vector<AccessUnitInfo> accessUnitInfos;
2774 for (int nMeta = 0; nMeta < bufferMetadata->flexCount(); nMeta++) {
2775 const C2AccessUnitInfosStruct &bufferMetadataStruct =
2776 bufferMetadata->m.values[nMeta];
2777 flag = convertFlags(bufferMetadataStruct.flags, false);
2778 accessUnitInfos.emplace_back(flag,
Arun Johnson9c6e91e2024-09-10 18:46:02 +00002779 bufferMetadataStruct.size,
2780 bufferMetadataStruct.timestamp);
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002781 }
2782 sp<WrapperObject<std::vector<AccessUnitInfo>>> obj{
2783 new WrapperObject<std::vector<AccessUnitInfo>>{accessUnitInfos}};
2784 outBuffer->meta()->setObject("accessUnitInfo", obj);
2785 }
2786 }
Wonsik Kim9dbb4162024-09-24 19:25:14 +00002787 mCallback->onOutputBufferAvailable(index, outBuffer);
2788 [[fallthrough]];
2789 }
2790 case OutputBuffers::DISCARD: {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002791 if (mHasInputSurface && android::media::codec::provider_->input_surface_throttle()) {
2792 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
2793 --inputSurface->numProcessingBuffersBalance;
Wonsik Kim9dbb4162024-09-24 19:25:14 +00002794 ALOGV("[%s] onWorkDone: numProcessingBuffersBalance = %lld",
2795 mName, static_cast<long long>(inputSurface->numProcessingBuffersBalance));
Wonsik Kimfca97a22024-08-30 20:20:42 +00002796 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002797 break;
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002798 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002799 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002800 if (++reallocTryNum > kMaxReallocTry) {
2801 output.unlock();
2802 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2803 mName, kMaxReallocTry);
2804 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2805 return;
2806 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002807 if (!output->buffers->isArrayMode()) {
2808 output->buffers =
2809 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002810 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002811 static_cast<OutputBuffersArray*>(output->buffers.get())->
2812 realloc(c2Buffer);
2813 output.unlock();
2814 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002815 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002816 case OutputBuffers::RETRY:
2817 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2818 mName);
2819 return;
2820 default:
2821 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2822 "corrupted BufferAction value (%d) "
2823 "returned from popFromStashAndRegister.",
2824 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002825 return;
2826 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002827 }
2828}
2829
Sungtak Lee214ce612023-11-01 10:01:13 +00002830status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface,
2831 uint32_t generation, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002832 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002833 int maxDequeueCount;
2834 sp<Surface> oldSurface;
2835 {
2836 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2837 maxDequeueCount = outputSurface->maxDequeueBuffers;
2838 oldSurface = outputSurface->surface;
2839 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002840 if (newSurface) {
Sungtak Leed1146682024-10-03 02:03:42 +00002841 (void)SurfaceCallbackHandler::GetInstance();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002842 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002843 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002844 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002845 producer = newSurface->getIGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002846 } else {
2847 ALOGE("[%s] setting output surface to null", mName);
2848 return INVALID_OPERATION;
2849 }
2850
2851 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2852 C2BlockPool::local_id_t outputPoolId;
2853 {
2854 Mutexed<BlockPools>::Locked pools(mBlockPools);
2855 outputPoolId = pools->outputPoolId;
2856 outputPoolIntf = pools->outputPoolIntf;
2857 }
2858
2859 if (outputPoolIntf) {
Sungtak Lee368452b2024-10-17 01:16:29 +00002860 if (std::atomic_load(&mComponent)->setOutputSurface(
Pawin Vongmasa36653902018-11-15 00:10:25 -08002861 outputPoolId,
2862 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002863 generation,
2864 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002865 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2866 return INVALID_OPERATION;
2867 }
2868 }
2869
2870 {
2871 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2872 output->surface = newSurface;
2873 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002874 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002875 }
2876
Sungtak Lee99144332023-01-26 11:03:14 +00002877 if (oldSurface && pushBlankBuffer) {
2878 // When ReleaseSurface was set from MediaCodec,
2879 // pushing a blank buffer at the end might be necessary.
2880 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2881 if (anw) {
2882 pushBlankBuffersToNativeWindow(anw.get());
2883 }
2884 }
2885
Pawin Vongmasa36653902018-11-15 00:10:25 -08002886 return OK;
2887}
2888
Wonsik Kimab34ed62019-01-31 15:28:46 -08002889PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002890 // Otherwise, component may have stalled work due to input starvation up to
2891 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002892 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2893 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002894 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002895 size_t outputDelay = mOutput.lock()->outputDelay;
2896 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002897 Mutexed<Input>::Locked input(mInput);
2898 n = input->inputDelay + input->pipelineDelay + outputDelay;
2899 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002900 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002901}
2902
Pawin Vongmasa36653902018-11-15 00:10:25 -08002903void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2904 mMetaMode = mode;
2905}
2906
Wonsik Kim596187e2019-10-25 12:44:10 -07002907void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002908 if (mCrypto != nullptr) {
2909 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2910 mCrypto->unsetHeap(entry.second);
2911 }
2912 mHeapSeqNumMap.clear();
2913 if (mHeapSeqNum >= 0) {
2914 mCrypto->unsetHeap(mHeapSeqNum);
2915 mHeapSeqNum = -1;
2916 }
2917 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002918 mCrypto = crypto;
2919}
2920
2921void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2922 mDescrambler = descrambler;
2923}
2924
Songyue Han1e6769b2023-08-30 18:09:27 +00002925uint32_t CCodecBufferChannel::getBuffersPixelFormat(bool isEncoder) {
2926 if (isEncoder) {
2927 return getInputBuffersPixelFormat();
2928 } else {
2929 return getOutputBuffersPixelFormat();
2930 }
2931}
2932
2933uint32_t CCodecBufferChannel::getInputBuffersPixelFormat() {
2934 Mutexed<Input>::Locked input(mInput);
2935 if (input->buffers == nullptr) {
2936 return PIXEL_FORMAT_UNKNOWN;
2937 }
2938 return input->buffers->getPixelFormatIfApplicable();
2939}
2940
2941uint32_t CCodecBufferChannel::getOutputBuffersPixelFormat() {
2942 Mutexed<Output>::Locked output(mOutput);
2943 if (output->buffers == nullptr) {
2944 return PIXEL_FORMAT_UNKNOWN;
2945 }
2946 return output->buffers->getPixelFormatIfApplicable();
2947}
2948
2949void CCodecBufferChannel::resetBuffersPixelFormat(bool isEncoder) {
2950 if (isEncoder) {
2951 Mutexed<Input>::Locked input(mInput);
2952 if (input->buffers == nullptr) {
2953 return;
2954 }
2955 input->buffers->resetPixelFormatIfApplicable();
2956 } else {
2957 Mutexed<Output>::Locked output(mOutput);
2958 if (output->buffers == nullptr) {
2959 return;
2960 }
2961 output->buffers->resetPixelFormatIfApplicable();
2962 }
2963}
2964
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302965void CCodecBufferChannel::setInfoBuffer(const std::shared_ptr<C2InfoBuffer> &buffer) {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002966 if (!mHasInputSurface) {
Harish Mahendrakar2b095d92024-05-13 16:51:15 -07002967 mInfoBuffers.push_back(buffer);
2968 } else {
2969 std::list<std::unique_ptr<C2Work>> items;
2970 std::unique_ptr<C2Work> work(new C2Work);
2971 work->input.infoBuffers.emplace_back(*buffer);
2972 work->worklets.emplace_back(new C2Worklet);
2973 items.push_back(std::move(work));
Harish Mahendrakar2b095d92024-05-13 16:51:15 -07002974 }
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302975}
2976
Pawin Vongmasa36653902018-11-15 00:10:25 -08002977status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2978 // C2_OK is always translated to OK.
2979 if (c2s == C2_OK) {
2980 return OK;
2981 }
2982
2983 // Operation-dependent translation
2984 // TODO: Add as necessary
2985 switch (c2op) {
2986 case C2_OPERATION_Component_start:
2987 switch (c2s) {
2988 case C2_NO_MEMORY:
2989 return NO_MEMORY;
2990 default:
2991 return UNKNOWN_ERROR;
2992 }
2993 default:
2994 break;
2995 }
2996
2997 // Backup operation-agnostic translation
2998 switch (c2s) {
2999 case C2_BAD_INDEX:
3000 return BAD_INDEX;
3001 case C2_BAD_VALUE:
3002 return BAD_VALUE;
3003 case C2_BLOCKING:
3004 return WOULD_BLOCK;
3005 case C2_DUPLICATE:
3006 return ALREADY_EXISTS;
3007 case C2_NO_INIT:
3008 return NO_INIT;
3009 case C2_NO_MEMORY:
3010 return NO_MEMORY;
3011 case C2_NOT_FOUND:
3012 return NAME_NOT_FOUND;
3013 case C2_TIMED_OUT:
3014 return TIMED_OUT;
3015 case C2_BAD_STATE:
3016 case C2_CANCELED:
3017 case C2_CANNOT_DO:
3018 case C2_CORRUPTED:
3019 case C2_OMITTED:
3020 case C2_REFUSED:
3021 return UNKNOWN_ERROR;
3022 default:
3023 return -static_cast<status_t>(c2s);
3024 }
3025}
3026
Pawin Vongmasa36653902018-11-15 00:10:25 -08003027} // namespace android