blob: 4353521fe9134d12197a3592fa9b19bb3f63cd29 [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) {
338 mComponent = component;
339 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;
354 return inputSurface->surface->connect(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 }
550 err = mComponent->queue(&items);
551 }
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;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001460 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
1461 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;
1599 mComponent->pollForRenderedFrames(&delta);
1600 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.
1608 std::shared_ptr<Codec2Client::Component> comp = mComponent;
1609 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.
1620 std::shared_ptr<Codec2Client::Component> comp = mComponent;
1621 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
Pawin Vongmasa36653902018-11-15 00:10:25 -08001694 c2_status_t err = mComponent->query(
1695 {
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
1725 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1726
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 }
1771 err = 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;
1932 err = mComponent->query({ },
1933 { 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();
1960 err = mComponent->query({ },
1961 { 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) {
1991 err = mComponent->createBlockPool(
1992 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;
2012 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
2013 ALOGD("[%s] Configured output block pool ids %llu => %s",
2014 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
2015 outputPoolId_ = pools->outputPoolId;
2016 }
2017
David Stevensc3fbb282021-01-18 18:11:20 +09002018 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
2019 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
2020 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
2021 if (err != C2_OK) {
2022 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
2023 (unsigned long long) prevOutputPoolId, asString(err), err);
2024 }
2025 }
2026
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002027 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07002028 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002029 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07002030 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002031 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002032 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002033 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002034 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07002035 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002036 }
2037 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002038 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002039 }
Wonsik Kime4716c02020-02-28 10:42:21 -08002040 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002041
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002042 output->buffers->clearStash();
2043 if (reorderDepth) {
2044 output->buffers->setReorderDepth(reorderDepth.value);
2045 }
2046 if (reorderKey) {
2047 output->buffers->setReorderKey(reorderKey.value);
2048 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002049
2050 // Try to set output surface to created block pool if given.
2051 if (outputSurface) {
2052 mComponent->setOutputSurface(
2053 outputPoolId_,
2054 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002055 outputGeneration,
2056 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08002057 } else {
2058 // configure CPU read consumer usage
2059 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
2060 std::vector<std::unique_ptr<C2SettingResult>> failures;
2061 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
2062 // do not print error message for now as most components may not yet
2063 // support this setting
2064 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
2065 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002066 }
2067
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07002068 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08002069 if (buffersBoundToCodec) {
2070 // WORKAROUND: if we're using early CSD workaround we convert to
2071 // array mode, to appease apps assuming the output
2072 // buffers to be of the same size.
2073 output->buffers = output->buffers->toArrayMode(numOutputSlots);
2074 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002075
2076 int32_t channelCount;
2077 int32_t sampleRate;
2078 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
2079 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
2080 int32_t delay = 0;
2081 int32_t padding = 0;;
2082 if (!outputFormat->findInt32("encoder-delay", &delay)) {
2083 delay = 0;
2084 }
2085 if (!outputFormat->findInt32("encoder-padding", &padding)) {
2086 padding = 0;
2087 }
2088 if (delay || padding) {
Arun Johnson52d323e2024-01-05 21:16:56 +00002089 // We need write access to the buffers, so turn them into array mode.
2090 // TODO: b/321930152 - define SkipCutOutputBuffers that takes output from
2091 // component, runs it through SkipCutBuffer and allocate local buffer to be
2092 // used by fwk. Make initSkipCutBuffer() return OutputBuffers similar to
2093 // toArrayMode().
2094 if (!output->buffers->isArrayMode()) {
2095 output->buffers = output->buffers->toArrayMode(numOutputSlots);
2096 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002097 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002098 }
2099 }
2100 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002101
2102 int32_t tunneled = 0;
2103 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
2104 tunneled = 0;
2105 }
2106 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002107 }
2108
2109 // Set up pipeline control. This has to be done after mInputBuffers and
2110 // mOutputBuffers are initialized to make sure that lingering callbacks
2111 // about buffers from the previous generation do not interfere with the
2112 // newly initialized pipeline capacity.
2113
Wonsik Kim62545252021-01-20 11:25:41 -08002114 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002115 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002116 watcher->inputDelay(inputDelayValue)
2117 .pipelineDelay(pipelineDelayValue)
2118 .outputDelay(outputDelayValue)
Houxiang Dai0b573282023-03-11 18:31:56 +08002119 .smoothnessFactor(kSmoothnessFactor)
2120 .tunneled(mTunneled);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002121 watcher->flush();
2122 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002123
2124 mInputMetEos = false;
2125 mSync.start();
2126 return OK;
2127}
2128
Wonsik Kim34b28b42022-05-20 15:49:32 -07002129status_t CCodecBufferChannel::prepareInitialInputBuffers(
Arun Johnson326166e2023-07-28 19:11:52 +00002130 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers, bool retry) {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002131 if (mHasInputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002132 return OK;
2133 }
2134
Wonsik Kim34b28b42022-05-20 15:49:32 -07002135 size_t numInputSlots = mInput.lock()->numSlots;
Arun Johnson326166e2023-07-28 19:11:52 +00002136 int retryCount = 1;
2137 for (; clientInputBuffers->empty() && retryCount >= 0; retryCount--) {
2138 {
2139 Mutexed<Input>::Locked input(mInput);
2140 while (clientInputBuffers->size() < numInputSlots) {
2141 size_t index;
2142 sp<MediaCodecBuffer> buffer;
2143 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
2144 break;
2145 }
2146 clientInputBuffers->emplace(index, buffer);
Wonsik Kim34b28b42022-05-20 15:49:32 -07002147 }
Arun Johnson326166e2023-07-28 19:11:52 +00002148 }
2149 if (!retry || (retryCount <= 0)) {
2150 break;
2151 }
2152 if (clientInputBuffers->empty()) {
2153 // wait: buffer may be in transit from component.
2154 std::this_thread::sleep_for(std::chrono::milliseconds(4));
Wonsik Kim34b28b42022-05-20 15:49:32 -07002155 }
2156 }
2157 if (clientInputBuffers->empty()) {
2158 ALOGW("[%s] start: cannot allocate memory at all", mName);
2159 return NO_MEMORY;
2160 } else if (clientInputBuffers->size() < numInputSlots) {
2161 ALOGD("[%s] start: cannot allocate memory for all slots, "
2162 "only %zu buffers allocated",
2163 mName, clientInputBuffers->size());
2164 } else {
2165 ALOGV("[%s] %zu initial input buffers available",
2166 mName, clientInputBuffers->size());
2167 }
2168 return OK;
2169}
2170
2171status_t CCodecBufferChannel::requestInitialInputBuffers(
2172 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Wonsik Kim8f67e732024-10-19 04:13:05 +00002173 std::optional<QueueGuard> guard;
2174 if (android::media::codec::provider_->codec_buffer_state_cleanup()) {
2175 guard.emplace(mSync);
2176 if (!guard->isRunning()) {
2177 ALOGD("[%s] skip requestInitialInputBuffers when not running", mName);
2178 return OK;
2179 }
2180 }
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002181 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07002182 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
2183 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
2184 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002185 return UNKNOWN_ERROR;
2186 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002187
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002188 std::list<std::unique_ptr<C2Work>> flushedConfigs;
2189 mFlushedConfigs.lock()->swap(flushedConfigs);
2190 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07002191 {
2192 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2193 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
2194 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
2195 watcher->onWorkQueued(
2196 work->input.ordinal.frameIndex.peeku(),
2197 std::vector(work->input.buffers),
2198 now);
2199 }
2200 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002201 err = mComponent->queue(&flushedConfigs);
2202 if (err != C2_OK) {
2203 ALOGW("[%s] Error while queueing a flushed config", mName);
2204 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002205 }
2206 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002207 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07002208 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
2209 !clientInputBuffers.empty()) {
2210 size_t minIndex = clientInputBuffers.begin()->first;
2211 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
2212 for (const auto &[index, buffer] : clientInputBuffers) {
2213 if (minBuffer->capacity() > buffer->capacity()) {
2214 minIndex = index;
2215 minBuffer = buffer;
2216 }
2217 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002218 // WORKAROUND: Some apps expect CSD available without queueing
2219 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07002220 minBuffer->setRange(0, 0);
2221 minBuffer->meta()->clear();
2222 minBuffer->meta()->setInt64("timeUs", 0);
2223 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002224 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
2225 mName);
2226 return UNKNOWN_ERROR;
2227 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07002228 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002229 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002230
Wonsik Kim34b28b42022-05-20 15:49:32 -07002231 for (const auto &[index, buffer] : clientInputBuffers) {
2232 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002233 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002234
Pawin Vongmasa36653902018-11-15 00:10:25 -08002235 return OK;
2236}
2237
2238void CCodecBufferChannel::stop() {
2239 mSync.stop();
2240 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302241 mInfoBuffers.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002242}
2243
Sungtak Lee99144332023-01-26 11:03:14 +00002244void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
2245 sp<Surface> surface = mOutputSurface.lock()->surface;
2246 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00002247 C2BlockPool::local_id_t outputPoolId;
2248 {
2249 Mutexed<BlockPools>::Locked pools(mBlockPools);
2250 outputPoolId = pools->outputPoolId;
2251 }
2252 if (mComponent) mComponent->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00002253
2254 if (pushBlankBuffer) {
2255 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
2256 if (anw) {
2257 pushBlankBuffersToNativeWindow(anw.get());
2258 }
2259 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00002260 }
2261}
2262
Wonsik Kim936a89c2020-05-08 16:07:50 -07002263void CCodecBufferChannel::reset() {
2264 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08002265 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002266 {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002267 mHasInputSurface = false;
2268 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
2269 inputSurface->surface.reset();
2270 }
2271 {
Wonsik Kim936a89c2020-05-08 16:07:50 -07002272 Mutexed<Input>::Locked input(mInput);
2273 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002274 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002275 }
2276 {
2277 Mutexed<Output>::Locked output(mOutput);
2278 output->buffers.reset();
2279 }
Brian Lindahl932bf602023-03-09 11:59:48 -07002280 // reset the frames that are being tracked for onFrameRendered callbacks
2281 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002282}
2283
2284void CCodecBufferChannel::release() {
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302285 mInfoBuffers.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002286 mComponent.reset();
2287 mInputAllocator.reset();
2288 mOutputSurface.lock()->surface.clear();
2289 {
2290 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
2291 blockPools->inputPool.reset();
2292 blockPools->outputPoolIntf.reset();
2293 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002294 setCrypto(nullptr);
2295 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002296}
2297
Pawin Vongmasa36653902018-11-15 00:10:25 -08002298void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
2299 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002300 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002301 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07002302 {
2303 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2304 for (const std::unique_ptr<C2Work> &work : flushedWork) {
2305 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
2306 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
2307 watcher->onWorkDone(frameIndex);
2308 continue;
2309 }
2310 if (work->input.buffers.empty()
2311 || work->input.buffers.front() == nullptr
2312 || work->input.buffers.front()->data().linearBlocks().empty()) {
2313 ALOGD("[%s] no linear codec config data found", mName);
2314 watcher->onWorkDone(frameIndex);
2315 continue;
2316 }
2317 std::unique_ptr<C2Work> copy(new C2Work);
2318 copy->input.flags = C2FrameData::flags_t(
2319 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
2320 copy->input.ordinal = work->input.ordinal;
2321 copy->input.ordinal.frameIndex = mFrameIndex++;
2322 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
2323 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
2324 }
2325 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
2326 copy->input.configUpdate.push_back(C2Param::Copy(*param));
2327 }
2328 copy->input.infoBuffers.insert(
2329 copy->input.infoBuffers.begin(),
2330 work->input.infoBuffers.begin(),
2331 work->input.infoBuffers.end());
2332 copy->worklets.emplace_back(new C2Worklet);
2333 configs.push_back(std::move(copy));
2334 watcher->onWorkDone(frameIndex);
2335 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002336 }
2337 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002338 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002339 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002340 Mutexed<Input>::Locked input(mInput);
2341 input->buffers->flush();
2342 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002343 }
2344 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002345 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002346 if (output->buffers) {
2347 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002348 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002349 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002350 }
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302351 mInfoBuffers.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002352}
2353
2354void CCodecBufferChannel::onWorkDone(
2355 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002356 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002357 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002358 feedInputBufferIfAvailable();
2359 }
2360}
2361
2362void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08002363 uint64_t frameIndex, size_t arrayIndex) {
2364 std::shared_ptr<C2Buffer> buffer =
2365 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002366 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002367 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002368 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002369 if (input->lastFlushIndex >= frameIndex) {
2370 ALOGD("[%s] Ignoring stale input buffer done callback: "
2371 "last flush index = %lld, frameIndex = %lld",
2372 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
2373 } else {
2374 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
2375 if (!newInputSlotAvailable) {
2376 (void)input->extraBuffers.expireComponentBuffer(buffer);
2377 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002378 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002379 }
2380 if (newInputSlotAvailable) {
2381 feedInputBufferIfAvailable();
2382 }
2383}
2384
2385bool CCodecBufferChannel::handleWork(
2386 std::unique_ptr<C2Work> work,
2387 const sp<AMessage> &outputFormat,
2388 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07002389 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00002390 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002391 if (!output->buffers) {
2392 return false;
2393 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08002394 }
2395
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002396 // Whether the output buffer should be reported to the client or not.
2397 bool notifyClient = false;
2398
2399 if (work->result == C2_OK){
2400 notifyClient = true;
2401 } else if (work->result == C2_NOT_FOUND) {
2402 ALOGD("[%s] flushed work; ignored.", mName);
2403 } else {
2404 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
2405 // the config update.
2406 ALOGD("[%s] work failed to complete: %d", mName, work->result);
2407 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
2408 return false;
2409 }
2410
2411 if ((work->input.ordinal.frameIndex -
2412 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002413 // Discard frames from previous generation.
2414 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002415 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002416 }
2417
Wonsik Kimfca97a22024-08-30 20:20:42 +00002418 if (!mHasInputSurface && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08002419 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002420 || !(work->worklets.front()->output.flags &
2421 C2FrameData::FLAG_INCOMPLETE))) {
2422 mPipelineWatcher.lock()->onWorkDone(
2423 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002424 }
2425
2426 // NOTE: MediaCodec usage supposedly have only one worklet
2427 if (work->worklets.size() != 1u) {
2428 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
2429 mName, work->worklets.size());
2430 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2431 return false;
2432 }
2433
2434 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
2435
2436 std::shared_ptr<C2Buffer> buffer;
2437 // NOTE: MediaCodec usage supposedly have only one output stream.
2438 if (worklet->output.buffers.size() > 1u) {
2439 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
2440 mName, worklet->output.buffers.size());
2441 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2442 return false;
2443 } else if (worklet->output.buffers.size() == 1u) {
2444 buffer = worklet->output.buffers[0];
2445 if (!buffer) {
2446 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
2447 }
2448 }
2449
Wonsik Kim3dedf682021-05-03 10:57:09 -07002450 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
2451 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002452 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002453 while (!worklet->output.configUpdate.empty()) {
2454 std::unique_ptr<C2Param> param;
2455 worklet->output.configUpdate.back().swap(param);
2456 worklet->output.configUpdate.pop_back();
2457 switch (param->coreIndex().coreIndex()) {
2458 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
2459 C2PortReorderBufferDepthTuning::output reorderDepth;
2460 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002461 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
2462 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002463 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002464 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002465 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002466 ALOGD("[%s] onWorkDone: failed to read reorder depth",
2467 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002468 }
2469 break;
2470 }
2471 case C2PortReorderKeySetting::CORE_INDEX: {
2472 C2PortReorderKeySetting::output reorderKey;
2473 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07002474 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002475 ALOGV("[%s] onWorkDone: updated reorder key to %u",
2476 mName, reorderKey.value);
2477 } else {
2478 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
2479 }
2480 break;
2481 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002482 case C2PortActualDelayTuning::CORE_INDEX: {
2483 if (param->isGlobal()) {
2484 C2ActualPipelineDelayTuning pipelineDelay;
2485 if (pipelineDelay.updateFrom(*param)) {
2486 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
2487 mName, pipelineDelay.value);
2488 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002489 (void)mPipelineWatcher.lock()->pipelineDelay(
2490 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002491 }
2492 }
2493 if (param->forInput()) {
2494 C2PortActualDelayTuning::input inputDelay;
2495 if (inputDelay.updateFrom(*param)) {
2496 ALOGV("[%s] onWorkDone: updating input delay %u",
2497 mName, inputDelay.value);
2498 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002499 (void)mPipelineWatcher.lock()->inputDelay(
2500 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002501 }
2502 }
2503 if (param->forOutput()) {
2504 C2PortActualDelayTuning::output outputDelay;
2505 if (outputDelay.updateFrom(*param)) {
2506 ALOGV("[%s] onWorkDone: updating output delay %u",
2507 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002508 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002509 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002510 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002511
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002512 }
2513 }
2514 break;
2515 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08002516 case C2PortTunnelSystemTime::CORE_INDEX: {
2517 C2PortTunnelSystemTime::output frameRenderTime;
2518 if (frameRenderTime.updateFrom(*param)) {
2519 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
2520 mName, (long long)frameRenderTime.value,
2521 (long long)worklet->output.ordinal.timestamp.peekll());
2522 mCCodecCallback->onOutputFramesRendered(
2523 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
2524 }
2525 break;
2526 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02002527 case C2StreamTunnelHoldRender::CORE_INDEX: {
2528 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
2529 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
2530 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
2531 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
2532 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
2533 mCCodecCallback->onFirstTunnelFrameReady();
2534 break;
2535 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002536 default:
2537 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2538 mName, param->index());
2539 break;
2540 }
2541 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002542 if (newInputDelay || newPipelineDelay) {
2543 Mutexed<Input>::Locked input(mInput);
2544 size_t newNumSlots =
2545 newInputDelay.value_or(input->inputDelay) +
2546 newPipelineDelay.value_or(input->pipelineDelay) +
2547 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08002548 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002549 if (input->buffers->isArrayMode()) {
2550 if (input->numSlots >= newNumSlots) {
2551 input->numExtraSlots = 0;
2552 } else {
2553 input->numExtraSlots = newNumSlots - input->numSlots;
2554 }
2555 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2556 mName, input->numExtraSlots);
2557 } else {
2558 input->numSlots = newNumSlots;
2559 }
2560 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002561 size_t numOutputSlots = 0;
2562 uint32_t reorderDepth = 0;
2563 bool outputBuffersChanged = false;
2564 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2565 Mutexed<Output>::Locked output(mOutput);
2566 if (!output->buffers) {
2567 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002568 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002569 numOutputSlots = output->numSlots;
2570 if (newReorderKey) {
2571 output->buffers->setReorderKey(newReorderKey.value());
2572 }
2573 if (newReorderDepth) {
2574 output->buffers->setReorderDepth(newReorderDepth.value());
2575 }
2576 reorderDepth = output->buffers->getReorderDepth();
2577 if (newOutputDelay) {
2578 output->outputDelay = newOutputDelay.value();
2579 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2580 if (output->numSlots < numOutputSlots) {
2581 output->numSlots = numOutputSlots;
2582 if (output->buffers->isArrayMode()) {
2583 OutputBuffersArray *array =
2584 (OutputBuffersArray *)output->buffers.get();
2585 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2586 mName, numOutputSlots);
2587 array->grow(numOutputSlots);
2588 outputBuffersChanged = true;
2589 }
2590 }
2591 }
2592 numOutputSlots = output->numSlots;
2593 }
2594 if (outputBuffersChanged) {
2595 mCCodecCallback->onOutputBuffersChanged();
2596 }
2597 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002598 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002599 {
2600 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2601 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002602 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002603 if (output->surface) {
2604 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2605 }
2606 }
2607 if (maxDequeueCount > 0) {
2608 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002609 }
2610 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002611
Pawin Vongmasa36653902018-11-15 00:10:25 -08002612 int32_t flags = 0;
2613 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002614 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002615 ALOGV("[%s] onWorkDone: output EOS", mName);
2616 }
2617
Pawin Vongmasa36653902018-11-15 00:10:25 -08002618 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2619 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2620 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2621 // shall correspond to the client input timesamp (in customOrdinal). By using the
2622 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2623 // produces multiple output.
2624 c2_cntr64_t timestamp =
2625 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2626 - work->input.ordinal.timestamp;
Wonsik Kimfca97a22024-08-30 20:20:42 +00002627 if (mHasInputSurface) {
Wonsik Kim95ba0162019-03-19 15:51:54 -07002628 // When using input surface we need to restore the original input timestamp.
2629 timestamp = work->input.ordinal.customOrdinal;
2630 }
My Name6bd9a7d2022-03-25 12:37:58 -07002631 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2632 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002633 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2634 mName,
2635 work->input.ordinal.customOrdinal.peekll(),
2636 work->input.ordinal.timestamp.peekll(),
2637 worklet->output.ordinal.timestamp.peekll(),
2638 timestamp.peekll());
2639
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002640 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002641 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002642 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002643 if (!output->buffers) {
2644 return false;
2645 }
2646 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002647 output->buffers->updateSkipCutBuffer(outputFormat);
2648 output->buffers->setFormat(outputFormat);
2649 }
2650 if (!notifyClient) {
2651 return false;
2652 }
2653 size_t index;
2654 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002655 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002656 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002657 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002658 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2659
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002660 // TRICKY: we want popped buffers reported in order, so sending
2661 // the callback while holding the lock here. This assumes that
2662 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2663 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002664 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002665 } else {
2666 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002667 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002668 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002669 return false;
2670 }
2671 }
2672
Wonsik Kimec585c32021-10-01 01:11:00 -07002673 bool drop = false;
2674 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2675 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2676 drop = true;
2677 }
2678
Marc Kassisec910342022-11-25 11:43:05 +01002679 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2680 // HAL, the flag is then removed in the corresponding output buffer.
2681 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2682 flags |= BUFFER_FLAG_DECODE_ONLY;
2683 }
2684
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002685 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002686 if (mTunneled && drop && outputFormat) {
Houxiang Daie74e5062022-05-19 15:32:54 +08002687 if (mOutputFormat != outputFormat) {
2688 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2689 mName, work->input.ordinal.frameIndex.peekull());
2690 mOutputFormat = outputFormat;
2691 } else {
2692 ALOGV("[%s] onWorkDone: Not reporting output buffer without format change (%lld)",
2693 mName, work->input.ordinal.frameIndex.peekull());
2694 notifyClient = false;
2695 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002696 } else {
2697 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2698 mName, work->input.ordinal.frameIndex.peekull());
2699 notifyClient = false;
2700 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002701 }
2702
2703 if (buffer) {
2704 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2705 // TODO: properly translate these to metadata
2706 switch (info->coreIndex().coreIndex()) {
2707 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002708 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002709 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002710 }
2711 break;
2712 default:
2713 break;
2714 }
2715 }
2716 }
2717
2718 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002719 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002720 if (!output->buffers) {
2721 return false;
2722 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002723 output->buffers->pushToStash(
2724 buffer,
2725 notifyClient,
2726 timestamp.peek(),
2727 flags,
2728 outputFormat,
2729 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002730 }
2731 sendOutputBuffers();
2732 return true;
2733}
2734
2735void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002736 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002737 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002738 sp<MediaCodecBuffer> outBuffer;
2739 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002740
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002741 constexpr int kMaxReallocTry = 5;
2742 int reallocTryNum = 0;
2743
Pawin Vongmasa36653902018-11-15 00:10:25 -08002744 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002745 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002746 if (!output->buffers) {
2747 return;
2748 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002749 action = output->buffers->popFromStashAndRegister(
2750 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002751 if (action != OutputBuffers::REALLOCATE) {
2752 reallocTryNum = 0;
2753 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002754 switch (action) {
2755 case OutputBuffers::SKIP:
2756 return;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002757 case OutputBuffers::NOTIFY_CLIENT:
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002758 {
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002759 // TRICKY: we want popped buffers reported in order, so sending
2760 // the callback while holding the lock here. This assumes that
2761 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2762 // callbacks are always sent with the Output lock held.
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002763 if (c2Buffer) {
2764 std::shared_ptr<const C2AccessUnitInfos::output> bufferMetadata =
2765 std::static_pointer_cast<const C2AccessUnitInfos::output>(
2766 c2Buffer->getInfo(C2AccessUnitInfos::output::PARAM_TYPE));
2767 if (bufferMetadata && bufferMetadata->flexCount() > 0) {
2768 uint32_t flag = 0;
2769 std::vector<AccessUnitInfo> accessUnitInfos;
2770 for (int nMeta = 0; nMeta < bufferMetadata->flexCount(); nMeta++) {
2771 const C2AccessUnitInfosStruct &bufferMetadataStruct =
2772 bufferMetadata->m.values[nMeta];
2773 flag = convertFlags(bufferMetadataStruct.flags, false);
2774 accessUnitInfos.emplace_back(flag,
Arun Johnson9c6e91e2024-09-10 18:46:02 +00002775 bufferMetadataStruct.size,
2776 bufferMetadataStruct.timestamp);
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002777 }
2778 sp<WrapperObject<std::vector<AccessUnitInfo>>> obj{
2779 new WrapperObject<std::vector<AccessUnitInfo>>{accessUnitInfos}};
2780 outBuffer->meta()->setObject("accessUnitInfo", obj);
2781 }
2782 }
Wonsik Kim9dbb4162024-09-24 19:25:14 +00002783 mCallback->onOutputBufferAvailable(index, outBuffer);
2784 [[fallthrough]];
2785 }
2786 case OutputBuffers::DISCARD: {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002787 if (mHasInputSurface && android::media::codec::provider_->input_surface_throttle()) {
2788 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
2789 --inputSurface->numProcessingBuffersBalance;
Wonsik Kim9dbb4162024-09-24 19:25:14 +00002790 ALOGV("[%s] onWorkDone: numProcessingBuffersBalance = %lld",
2791 mName, static_cast<long long>(inputSurface->numProcessingBuffersBalance));
Wonsik Kimfca97a22024-08-30 20:20:42 +00002792 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002793 break;
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002794 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002795 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002796 if (++reallocTryNum > kMaxReallocTry) {
2797 output.unlock();
2798 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2799 mName, kMaxReallocTry);
2800 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2801 return;
2802 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002803 if (!output->buffers->isArrayMode()) {
2804 output->buffers =
2805 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002806 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002807 static_cast<OutputBuffersArray*>(output->buffers.get())->
2808 realloc(c2Buffer);
2809 output.unlock();
2810 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002811 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002812 case OutputBuffers::RETRY:
2813 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2814 mName);
2815 return;
2816 default:
2817 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2818 "corrupted BufferAction value (%d) "
2819 "returned from popFromStashAndRegister.",
2820 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002821 return;
2822 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002823 }
2824}
2825
Sungtak Lee214ce612023-11-01 10:01:13 +00002826status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface,
2827 uint32_t generation, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002828 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002829 int maxDequeueCount;
2830 sp<Surface> oldSurface;
2831 {
2832 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2833 maxDequeueCount = outputSurface->maxDequeueBuffers;
2834 oldSurface = outputSurface->surface;
2835 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002836 if (newSurface) {
Sungtak Leed1146682024-10-03 02:03:42 +00002837 (void)SurfaceCallbackHandler::GetInstance();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002838 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002839 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002840 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002841 producer = newSurface->getIGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002842 } else {
2843 ALOGE("[%s] setting output surface to null", mName);
2844 return INVALID_OPERATION;
2845 }
2846
2847 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2848 C2BlockPool::local_id_t outputPoolId;
2849 {
2850 Mutexed<BlockPools>::Locked pools(mBlockPools);
2851 outputPoolId = pools->outputPoolId;
2852 outputPoolIntf = pools->outputPoolIntf;
2853 }
2854
2855 if (outputPoolIntf) {
2856 if (mComponent->setOutputSurface(
2857 outputPoolId,
2858 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002859 generation,
2860 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002861 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2862 return INVALID_OPERATION;
2863 }
2864 }
2865
2866 {
2867 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2868 output->surface = newSurface;
2869 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002870 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002871 }
2872
Sungtak Lee99144332023-01-26 11:03:14 +00002873 if (oldSurface && pushBlankBuffer) {
2874 // When ReleaseSurface was set from MediaCodec,
2875 // pushing a blank buffer at the end might be necessary.
2876 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2877 if (anw) {
2878 pushBlankBuffersToNativeWindow(anw.get());
2879 }
2880 }
2881
Pawin Vongmasa36653902018-11-15 00:10:25 -08002882 return OK;
2883}
2884
Wonsik Kimab34ed62019-01-31 15:28:46 -08002885PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002886 // Otherwise, component may have stalled work due to input starvation up to
2887 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002888 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2889 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002890 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002891 size_t outputDelay = mOutput.lock()->outputDelay;
2892 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002893 Mutexed<Input>::Locked input(mInput);
2894 n = input->inputDelay + input->pipelineDelay + outputDelay;
2895 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002896 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002897}
2898
Pawin Vongmasa36653902018-11-15 00:10:25 -08002899void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2900 mMetaMode = mode;
2901}
2902
Wonsik Kim596187e2019-10-25 12:44:10 -07002903void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002904 if (mCrypto != nullptr) {
2905 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2906 mCrypto->unsetHeap(entry.second);
2907 }
2908 mHeapSeqNumMap.clear();
2909 if (mHeapSeqNum >= 0) {
2910 mCrypto->unsetHeap(mHeapSeqNum);
2911 mHeapSeqNum = -1;
2912 }
2913 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002914 mCrypto = crypto;
2915}
2916
2917void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2918 mDescrambler = descrambler;
2919}
2920
Songyue Han1e6769b2023-08-30 18:09:27 +00002921uint32_t CCodecBufferChannel::getBuffersPixelFormat(bool isEncoder) {
2922 if (isEncoder) {
2923 return getInputBuffersPixelFormat();
2924 } else {
2925 return getOutputBuffersPixelFormat();
2926 }
2927}
2928
2929uint32_t CCodecBufferChannel::getInputBuffersPixelFormat() {
2930 Mutexed<Input>::Locked input(mInput);
2931 if (input->buffers == nullptr) {
2932 return PIXEL_FORMAT_UNKNOWN;
2933 }
2934 return input->buffers->getPixelFormatIfApplicable();
2935}
2936
2937uint32_t CCodecBufferChannel::getOutputBuffersPixelFormat() {
2938 Mutexed<Output>::Locked output(mOutput);
2939 if (output->buffers == nullptr) {
2940 return PIXEL_FORMAT_UNKNOWN;
2941 }
2942 return output->buffers->getPixelFormatIfApplicable();
2943}
2944
2945void CCodecBufferChannel::resetBuffersPixelFormat(bool isEncoder) {
2946 if (isEncoder) {
2947 Mutexed<Input>::Locked input(mInput);
2948 if (input->buffers == nullptr) {
2949 return;
2950 }
2951 input->buffers->resetPixelFormatIfApplicable();
2952 } else {
2953 Mutexed<Output>::Locked output(mOutput);
2954 if (output->buffers == nullptr) {
2955 return;
2956 }
2957 output->buffers->resetPixelFormatIfApplicable();
2958 }
2959}
2960
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302961void CCodecBufferChannel::setInfoBuffer(const std::shared_ptr<C2InfoBuffer> &buffer) {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002962 if (!mHasInputSurface) {
Harish Mahendrakar2b095d92024-05-13 16:51:15 -07002963 mInfoBuffers.push_back(buffer);
2964 } else {
2965 std::list<std::unique_ptr<C2Work>> items;
2966 std::unique_ptr<C2Work> work(new C2Work);
2967 work->input.infoBuffers.emplace_back(*buffer);
2968 work->worklets.emplace_back(new C2Worklet);
2969 items.push_back(std::move(work));
Harish Mahendrakar2b095d92024-05-13 16:51:15 -07002970 }
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302971}
2972
Pawin Vongmasa36653902018-11-15 00:10:25 -08002973status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2974 // C2_OK is always translated to OK.
2975 if (c2s == C2_OK) {
2976 return OK;
2977 }
2978
2979 // Operation-dependent translation
2980 // TODO: Add as necessary
2981 switch (c2op) {
2982 case C2_OPERATION_Component_start:
2983 switch (c2s) {
2984 case C2_NO_MEMORY:
2985 return NO_MEMORY;
2986 default:
2987 return UNKNOWN_ERROR;
2988 }
2989 default:
2990 break;
2991 }
2992
2993 // Backup operation-agnostic translation
2994 switch (c2s) {
2995 case C2_BAD_INDEX:
2996 return BAD_INDEX;
2997 case C2_BAD_VALUE:
2998 return BAD_VALUE;
2999 case C2_BLOCKING:
3000 return WOULD_BLOCK;
3001 case C2_DUPLICATE:
3002 return ALREADY_EXISTS;
3003 case C2_NO_INIT:
3004 return NO_INIT;
3005 case C2_NO_MEMORY:
3006 return NO_MEMORY;
3007 case C2_NOT_FOUND:
3008 return NAME_NOT_FOUND;
3009 case C2_TIMED_OUT:
3010 return TIMED_OUT;
3011 case C2_BAD_STATE:
3012 case C2_CANCELED:
3013 case C2_CANNOT_DO:
3014 case C2_CORRUPTED:
3015 case C2_OMITTED:
3016 case C2_REFUSED:
3017 return UNKNOWN_ERROR;
3018 default:
3019 return -static_cast<status_t>(c2s);
3020 }
3021}
3022
Pawin Vongmasa36653902018-11-15 00:10:25 -08003023} // namespace android