blob: a66e81e92639a63e5c3b5f850ff7c40512493b6c [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
18#define LOG_TAG "CCodecBufferChannel"
My Name6bd9a7d2022-03-25 12:37:58 -070019#define ATRACE_TAG ATRACE_TAG_VIDEO
Pawin Vongmasa36653902018-11-15 00:10:25 -080020#include <utils/Log.h>
My Name6bd9a7d2022-03-25 12:37:58 -070021#include <utils/Trace.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080022
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070023#include <algorithm>
Wonsik Kim6b2c8be2021-09-28 05:11:04 -070024#include <atomic>
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070025#include <list>
Pawin Vongmasa36653902018-11-15 00:10:25 -080026#include <numeric>
27
28#include <C2AllocatorGralloc.h>
29#include <C2PlatformSupport.h>
30#include <C2BlockInternal.h>
31#include <C2Config.h>
32#include <C2Debug.h>
33
34#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070035#include <android/hardware/drm/1.0/types.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080036#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080037#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080038#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080039#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070040#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080041#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070042#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080043#include <media/openmax/OMX_Core.h>
44#include <media/stagefright/foundation/ABuffer.h>
45#include <media/stagefright/foundation/ALookup.h>
46#include <media/stagefright/foundation/AMessage.h>
47#include <media/stagefright/foundation/AUtils.h>
48#include <media/stagefright/foundation/hexdump.h>
49#include <media/stagefright/MediaCodec.h>
50#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070051#include <media/stagefright/SkipCutBuffer.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080052#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070053#include <mediadrm/ICrypto.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080054#include <system/window.h>
55
56#include "CCodecBufferChannel.h"
57#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080058
59namespace android {
60
61using android::base::StringPrintf;
62using hardware::hidl_handle;
63using hardware::hidl_string;
64using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070065using hardware::fromHeap;
66using hardware::HidlMemory;
67
Pawin Vongmasa36653902018-11-15 00:10:25 -080068using namespace hardware::cas::V1_0;
69using namespace hardware::cas::native::V1_0;
70
71using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070072using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080073
Pawin Vongmasa36653902018-11-15 00:10:25 -080074namespace {
75
Wonsik Kim469c8342019-04-11 16:46:09 -070076constexpr size_t kSmoothnessFactor = 4;
77constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080078
Sungtak Leeab6f2f32019-02-15 14:43:51 -080079// This is for keeping IGBP's buffer dropping logic in legacy mode other
80// than making it non-blocking. Do not change this value.
81const static size_t kDequeueTimeoutNs = 0;
82
Pawin Vongmasa36653902018-11-15 00:10:25 -080083} // namespace
84
85CCodecBufferChannel::QueueGuard::QueueGuard(
86 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
87 Mutex::Autolock l(mSync.mGuardLock);
88 // At this point it's guaranteed that mSync is not under state transition,
89 // as we are holding its mutex.
90
91 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
92 if (count->value == -1) {
93 mRunning = false;
94 } else {
95 ++count->value;
96 mRunning = true;
97 }
98}
99
100CCodecBufferChannel::QueueGuard::~QueueGuard() {
101 if (mRunning) {
102 // We are not holding mGuardLock at this point so that QueueSync::stop() can
103 // keep holding the lock until mCount reaches zero.
104 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
105 --count->value;
106 count->cond.broadcast();
107 }
108}
109
110void CCodecBufferChannel::QueueSync::start() {
111 Mutex::Autolock l(mGuardLock);
112 // If stopped, it goes to running state; otherwise no-op.
113 Mutexed<Counter>::Locked count(mCount);
114 if (count->value == -1) {
115 count->value = 0;
116 }
117}
118
119void CCodecBufferChannel::QueueSync::stop() {
120 Mutex::Autolock l(mGuardLock);
121 Mutexed<Counter>::Locked count(mCount);
122 if (count->value == -1) {
123 // no-op
124 return;
125 }
126 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
127 // mCount can only decrement. In other words, threads that acquired the lock
128 // are allowed to finish execution but additional threads trying to acquire
129 // the lock at this point will block, and then get QueueGuard at STOPPED
130 // state.
131 while (count->value != 0) {
132 count.waitForCondition(count->cond);
133 }
134 count->value = -1;
135}
136
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700137// Input
138
139CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
140
Pawin Vongmasa36653902018-11-15 00:10:25 -0800141// CCodecBufferChannel
142
143CCodecBufferChannel::CCodecBufferChannel(
144 const std::shared_ptr<CCodecCallback> &callback)
145 : mHeapSeqNum(-1),
146 mCCodecCallback(callback),
147 mFrameIndex(0u),
148 mFirstValidFrameIndex(0u),
149 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700150 mInputMetEos(false),
151 mSendEncryptedInfoBuffer(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700152 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700153 {
154 Mutexed<Input>::Locked input(mInput);
155 input->buffers.reset(new DummyInputBuffers(""));
156 input->extraBuffers.flush();
157 input->inputDelay = 0u;
158 input->pipelineDelay = 0u;
159 input->numSlots = kSmoothnessFactor;
160 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700161 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700162 }
163 {
164 Mutexed<Output>::Locked output(mOutput);
165 output->outputDelay = 0u;
166 output->numSlots = kSmoothnessFactor;
167 }
David Stevensc3fbb282021-01-18 18:11:20 +0900168 {
169 Mutexed<BlockPools>::Locked pools(mBlockPools);
170 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
171 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800172}
173
174CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800175 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800176 mCrypto->unsetHeap(mHeapSeqNum);
177 }
178}
179
180void CCodecBufferChannel::setComponent(
181 const std::shared_ptr<Codec2Client::Component> &component) {
182 mComponent = component;
183 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
184 mName = mComponentName.c_str();
185}
186
187status_t CCodecBufferChannel::setInputSurface(
188 const std::shared_ptr<InputSurfaceWrapper> &surface) {
189 ALOGV("[%s] setInputSurface", mName);
190 mInputSurface = surface;
191 return mInputSurface->connect(mComponent);
192}
193
194status_t CCodecBufferChannel::signalEndOfInputStream() {
195 if (mInputSurface == nullptr) {
196 return INVALID_OPERATION;
197 }
198 return mInputSurface->signalEndOfInputStream();
199}
200
Sungtak Lee04b30352020-07-27 13:57:25 -0700201status_t CCodecBufferChannel::queueInputBufferInternal(
202 sp<MediaCodecBuffer> buffer,
203 std::shared_ptr<C2LinearBlock> encryptedBlock,
204 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800205 int64_t timeUs;
206 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
207
208 if (mInputMetEos) {
209 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
210 return OK;
211 }
212
213 int32_t flags = 0;
214 int32_t tmp = 0;
215 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200216 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800217 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
218 eos = true;
219 mInputMetEos = true;
220 ALOGV("[%s] input EOS", mName);
221 }
222 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
223 flags |= C2FrameData::FLAG_CODEC_CONFIG;
224 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200225 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
226 tunnelFirstFrame = true;
227 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800228 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800229 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800230 std::unique_ptr<C2Work> work(new C2Work);
231 work->input.ordinal.timestamp = timeUs;
232 work->input.ordinal.frameIndex = mFrameIndex++;
233 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
234 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
235 // Keep client timestamp in customOrdinal
236 work->input.ordinal.customOrdinal = timeUs;
237 work->input.buffers.clear();
238
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700239 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800240 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800241
Pawin Vongmasa36653902018-11-15 00:10:25 -0800242 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700243 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800244 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700245 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800246 return -ENOENT;
247 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700248 // TODO: we want to delay copying buffers.
249 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
250 copy = input->buffers->cloneAndReleaseBuffer(buffer);
251 if (copy != nullptr) {
252 (void)input->extraBuffers.assignSlot(copy);
253 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
254 return UNKNOWN_ERROR;
255 }
256 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
257 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
258 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700259 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700260 } else {
261 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
262 "buffer starvation on component.", mName);
263 }
264 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800265 if (input->frameReassembler) {
266 usesFrameReassembler = true;
267 input->frameReassembler.process(buffer, &items);
268 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900269 int32_t cvo = 0;
270 if (buffer->meta()->findInt32("cvo", &cvo)) {
271 int32_t rotation = cvo % 360;
272 // change rotation to counter-clock wise.
273 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
274
275 Mutexed<OutputSurface>::Locked output(mOutputSurface);
276 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
277 output->rotation[frameIndex] = rotation;
278 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800279 work->input.buffers.push_back(c2buffer);
280 if (encryptedBlock) {
281 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
282 kParamIndexEncryptedBuffer,
283 encryptedBlock->share(0, blockSize, C2Fence())));
284 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700285 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800286 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700287 Mutexed<Input>::Locked input(mInput);
288 if (input->frameReassembler) {
289 usesFrameReassembler = true;
290 // drain any pending items with eos
291 input->frameReassembler.process(buffer, &items);
292 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800293 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800294 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800295 if (usesFrameReassembler) {
296 if (!items.empty()) {
297 items.front()->input.configUpdate = std::move(mParamsToBeSet);
298 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
299 }
300 } else {
301 work->input.flags = (C2FrameData::flags_t)flags;
302 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800303
Wonsik Kime1104ca2020-11-24 15:01:33 -0800304 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200305 if (tunnelFirstFrame) {
306 C2StreamTunnelHoldRender::input tunnelHoldRender{
307 0u /* stream */,
308 C2_TRUE /* value */
309 };
310 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
311 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800312 work->worklets.clear();
313 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800314
Wonsik Kime1104ca2020-11-24 15:01:33 -0800315 items.push_back(std::move(work));
316
317 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800318 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800319 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800320 work.reset(new C2Work);
321 work->input.ordinal.timestamp = timeUs;
322 work->input.ordinal.frameIndex = mFrameIndex++;
323 // WORKAROUND: keep client timestamp in customOrdinal
324 work->input.ordinal.customOrdinal = timeUs;
325 work->input.buffers.clear();
326 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800327 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800328 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800329 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800330 c2_status_t err = C2_OK;
331 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700332 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
333 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800334 {
335 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
336 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
337 for (const std::unique_ptr<C2Work> &work : items) {
338 watcher->onWorkQueued(
339 work->input.ordinal.frameIndex.peeku(),
340 std::vector(work->input.buffers),
341 now);
342 }
343 }
344 err = mComponent->queue(&items);
345 }
346 if (err != C2_OK) {
347 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
348 for (const std::unique_ptr<C2Work> &work : items) {
349 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
350 }
351 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700352 Mutexed<Input>::Locked input(mInput);
353 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700354 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700355 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700356 } else if (buffer) {
357 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700358 }
359 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
360 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800361 }
362
363 feedInputBufferIfAvailableInternal();
364 return err;
365}
366
367status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
368 QueueGuard guard(mSync);
369 if (!guard.isRunning()) {
370 ALOGD("[%s] setParameters is only supported in the running state.", mName);
371 return -ENOSYS;
372 }
373 mParamsToBeSet.insert(mParamsToBeSet.end(),
374 std::make_move_iterator(params.begin()),
375 std::make_move_iterator(params.end()));
376 params.clear();
377 return OK;
378}
379
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800380status_t CCodecBufferChannel::attachBuffer(
381 const std::shared_ptr<C2Buffer> &c2Buffer,
382 const sp<MediaCodecBuffer> &buffer) {
383 if (!buffer->copy(c2Buffer)) {
384 return -ENOSYS;
385 }
386 return OK;
387}
388
389void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
390 if (!mDecryptDestination || mDecryptDestination->size() < size) {
391 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
392 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
393 mCrypto->unsetHeap(mHeapSeqNum);
394 }
395 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
396 if (mCrypto) {
397 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
398 }
399 }
400}
401
402int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
403 CHECK(mCrypto);
404 auto it = mHeapSeqNumMap.find(memory);
405 int32_t heapSeqNum = -1;
406 if (it == mHeapSeqNumMap.end()) {
407 heapSeqNum = mCrypto->setHeap(memory);
408 mHeapSeqNumMap.emplace(memory, heapSeqNum);
409 } else {
410 heapSeqNum = it->second;
411 }
412 return heapSeqNum;
413}
414
415status_t CCodecBufferChannel::attachEncryptedBuffer(
416 const sp<hardware::HidlMemory> &memory,
417 bool secure,
418 const uint8_t *key,
419 const uint8_t *iv,
420 CryptoPlugin::Mode mode,
421 CryptoPlugin::Pattern pattern,
422 size_t offset,
423 const CryptoPlugin::SubSample *subSamples,
424 size_t numSubSamples,
425 const sp<MediaCodecBuffer> &buffer) {
426 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
427 static const C2MemoryUsage kDefaultReadWriteUsage{
428 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
429
430 size_t size = 0;
431 for (size_t i = 0; i < numSubSamples; ++i) {
432 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
433 }
434 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
435 std::shared_ptr<C2LinearBlock> block;
436 c2_status_t err = pool->fetchLinearBlock(
437 size,
438 secure ? kSecureUsage : kDefaultReadWriteUsage,
439 &block);
440 if (err != C2_OK) {
441 return NO_MEMORY;
442 }
443 if (!secure) {
444 ensureDecryptDestination(size);
445 }
446 ssize_t result = -1;
447 ssize_t codecDataOffset = 0;
448 if (mCrypto) {
449 AString errorDetailMsg;
450 int32_t heapSeqNum = getHeapSeqNum(memory);
451 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
452 hardware::drm::V1_0::DestinationBuffer dst;
453 if (secure) {
454 dst.type = DrmBufferType::NATIVE_HANDLE;
455 dst.secureMemory = hardware::hidl_handle(block->handle());
456 } else {
457 dst.type = DrmBufferType::SHARED_MEMORY;
458 IMemoryToSharedBuffer(
459 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
460 }
461 result = mCrypto->decrypt(
462 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
463 dst, &errorDetailMsg);
464 if (result < 0) {
465 return result;
466 }
467 if (dst.type == DrmBufferType::SHARED_MEMORY) {
468 C2WriteView view = block->map().get();
469 if (view.error() != C2_OK) {
470 return false;
471 }
472 if (view.size() < result) {
473 return false;
474 }
475 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
476 }
477 } else {
478 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
479 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
480 hidl_vec<SubSample> hidlSubSamples;
481 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
482
483 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
484 hardware::cas::native::V1_0::DestinationBuffer dst;
485 if (secure) {
486 dst.type = BufferType::NATIVE_HANDLE;
487 dst.secureMemory = hardware::hidl_handle(block->handle());
488 } else {
489 dst.type = BufferType::SHARED_MEMORY;
490 dst.nonsecureMemory = src;
491 }
492
493 CasStatus status = CasStatus::OK;
494 hidl_string detailedError;
495 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
496
497 if (key != nullptr) {
498 sctrl = (ScramblingControl)key[0];
499 // Adjust for the PES offset
500 codecDataOffset = key[2] | (key[3] << 8);
501 }
502
503 auto returnVoid = mDescrambler->descramble(
504 sctrl,
505 hidlSubSamples,
506 src,
507 0,
508 dst,
509 0,
510 [&status, &result, &detailedError] (
511 CasStatus _status, uint32_t _bytesWritten,
512 const hidl_string& _detailedError) {
513 status = _status;
514 result = (ssize_t)_bytesWritten;
515 detailedError = _detailedError;
516 });
517
518 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
519 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
520 mName, returnVoid.description().c_str(), status, result);
521 return UNKNOWN_ERROR;
522 }
523
524 if (result < codecDataOffset) {
525 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
526 return BAD_VALUE;
527 }
528 }
529 if (!secure) {
530 C2WriteView view = block->map().get();
531 if (view.error() != C2_OK) {
532 return UNKNOWN_ERROR;
533 }
534 if (view.size() < result) {
535 return UNKNOWN_ERROR;
536 }
537 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
538 }
539 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
540 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
541 if (!buffer->copy(c2Buffer)) {
542 return -ENOSYS;
543 }
544 return OK;
545}
546
Pawin Vongmasa36653902018-11-15 00:10:25 -0800547status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
548 QueueGuard guard(mSync);
549 if (!guard.isRunning()) {
550 ALOGD("[%s] No more buffers should be queued at current state.", mName);
551 return -ENOSYS;
552 }
553 return queueInputBufferInternal(buffer);
554}
555
556status_t CCodecBufferChannel::queueSecureInputBuffer(
557 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
558 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
559 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
560 AString *errorDetailMsg) {
561 QueueGuard guard(mSync);
562 if (!guard.isRunning()) {
563 ALOGD("[%s] No more buffers should be queued at current state.", mName);
564 return -ENOSYS;
565 }
566
567 if (!hasCryptoOrDescrambler()) {
568 return -ENOSYS;
569 }
570 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
571
Sungtak Lee04b30352020-07-27 13:57:25 -0700572 std::shared_ptr<C2LinearBlock> block;
573 size_t allocSize = buffer->size();
574 size_t bufferSize = 0;
575 c2_status_t blockRes = C2_OK;
576 bool copied = false;
577 if (mSendEncryptedInfoBuffer) {
578 static const C2MemoryUsage kDefaultReadWriteUsage{
579 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
580 constexpr int kAllocGranule0 = 1024 * 64;
581 constexpr int kAllocGranule1 = 1024 * 1024;
582 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
583 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
584 if (allocSize <= kAllocGranule1) {
585 bufferSize = align(allocSize, kAllocGranule0);
586 } else {
587 bufferSize = align(allocSize, kAllocGranule1);
588 }
589 blockRes = pool->fetchLinearBlock(
590 bufferSize, kDefaultReadWriteUsage, &block);
591
592 if (blockRes == C2_OK) {
593 C2WriteView view = block->map().get();
594 if (view.error() == C2_OK && view.size() == bufferSize) {
595 copied = true;
596 // TODO: only copy clear sections
597 memcpy(view.data(), buffer->data(), allocSize);
598 }
599 }
600 }
601
602 if (!copied) {
603 block.reset();
604 }
605
Pawin Vongmasa36653902018-11-15 00:10:25 -0800606 ssize_t result = -1;
607 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700608 if (numSubSamples == 1
609 && subSamples[0].mNumBytesOfClearData == 0
610 && subSamples[0].mNumBytesOfEncryptedData == 0) {
611 // We don't need to go through crypto or descrambler if the input is empty.
612 result = 0;
613 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700614 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800615 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700616 destination.type = DrmBufferType::NATIVE_HANDLE;
617 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800618 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700619 destination.type = DrmBufferType::SHARED_MEMORY;
620 IMemoryToSharedBuffer(
621 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800622 }
Robert Shih895fba92019-07-16 16:29:44 -0700623 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800624 encryptedBuffer->fillSourceBuffer(&source);
625 result = mCrypto->decrypt(
626 key, iv, mode, pattern, source, buffer->offset(),
627 subSamples, numSubSamples, destination, errorDetailMsg);
628 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700629 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800630 return result;
631 }
Robert Shih895fba92019-07-16 16:29:44 -0700632 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800633 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
634 }
635 } else {
636 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
637 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
638 hidl_vec<SubSample> hidlSubSamples;
639 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
640
641 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
642 encryptedBuffer->fillSourceBuffer(&srcBuffer);
643
644 DestinationBuffer dstBuffer;
645 if (secure) {
646 dstBuffer.type = BufferType::NATIVE_HANDLE;
647 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
648 } else {
649 dstBuffer.type = BufferType::SHARED_MEMORY;
650 dstBuffer.nonsecureMemory = srcBuffer;
651 }
652
653 CasStatus status = CasStatus::OK;
654 hidl_string detailedError;
655 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
656
657 if (key != nullptr) {
658 sctrl = (ScramblingControl)key[0];
659 // Adjust for the PES offset
660 codecDataOffset = key[2] | (key[3] << 8);
661 }
662
663 auto returnVoid = mDescrambler->descramble(
664 sctrl,
665 hidlSubSamples,
666 srcBuffer,
667 0,
668 dstBuffer,
669 0,
670 [&status, &result, &detailedError] (
671 CasStatus _status, uint32_t _bytesWritten,
672 const hidl_string& _detailedError) {
673 status = _status;
674 result = (ssize_t)_bytesWritten;
675 detailedError = _detailedError;
676 });
677
678 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
679 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
680 mName, returnVoid.description().c_str(), status, result);
681 return UNKNOWN_ERROR;
682 }
683
684 if (result < codecDataOffset) {
685 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
686 return BAD_VALUE;
687 }
688
689 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
690
691 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
692 encryptedBuffer->copyDecryptedContentFromMemory(result);
693 }
694 }
695
696 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700697
698 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800699}
700
701void CCodecBufferChannel::feedInputBufferIfAvailable() {
702 QueueGuard guard(mSync);
703 if (!guard.isRunning()) {
704 ALOGV("[%s] We're not running --- no input buffer reported", mName);
705 return;
706 }
707 feedInputBufferIfAvailableInternal();
708}
709
710void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900711 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800712 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700713 }
714 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700715 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700716 if (!output->buffers ||
717 output->buffers->hasPending() ||
Wonsik Kim0487b782020-10-28 11:45:50 -0700718 output->buffers->numActiveSlots() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800719 return;
720 }
721 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700722 size_t numActiveSlots = 0;
723 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800724 sp<MediaCodecBuffer> inBuffer;
725 size_t index;
726 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700727 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700728 numActiveSlots = input->buffers->numActiveSlots();
729 if (numActiveSlots >= input->numSlots) {
730 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800731 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700732 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800733 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800734 break;
735 }
736 }
737 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
738 mCallback->onInputBufferAvailable(index, inBuffer);
739 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700740 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800741}
742
743status_t CCodecBufferChannel::renderOutputBuffer(
744 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800745 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800746 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800747 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700749 Mutexed<Output>::Locked output(mOutput);
750 if (output->buffers) {
751 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800752 }
753 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800754 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
755 // set to true.
756 sendOutputBuffers();
757 // input buffer feeding may have been gated by pending output buffers
758 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800760 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700761 std::call_once(mRenderWarningFlag, [this] {
762 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
763 "timestamp or render=true with non-video buffers. Apps should "
764 "call releaseOutputBuffer() with render=false for those.",
765 mName);
766 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800767 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800768 return INVALID_OPERATION;
769 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800770
771#if 0
772 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
773 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
774 for (const std::shared_ptr<const C2Info> &info : infoParams) {
775 AString res;
776 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
777 if (ix) res.append(", ");
778 res.append(*((int32_t*)info.get() + (ix / 4)));
779 }
780 ALOGV(" [%s]", res.c_str());
781 }
782#endif
783 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
784 std::static_pointer_cast<const C2StreamRotationInfo::output>(
785 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
786 bool flip = rotation && (rotation->flip & 1);
787 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900788
789 {
790 Mutexed<OutputSurface>::Locked output(mOutputSurface);
791 if (output->surface == nullptr) {
792 ALOGI("[%s] cannot render buffer without surface", mName);
793 return OK;
794 }
795 int64_t frameIndex;
796 buffer->meta()->findInt64("frameIndex", &frameIndex);
797 if (output->rotation.count(frameIndex) != 0) {
798 auto it = output->rotation.find(frameIndex);
799 quarters = (it->second / 90) & 3;
800 output->rotation.erase(it);
801 }
802 }
803
Pawin Vongmasa36653902018-11-15 00:10:25 -0800804 uint32_t transform = 0;
805 switch (quarters) {
806 case 0: // no rotation
807 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
808 break;
809 case 1: // 90 degrees counter-clockwise
810 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
811 : HAL_TRANSFORM_ROT_270;
812 break;
813 case 2: // 180 degrees
814 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
815 break;
816 case 3: // 90 degrees clockwise
817 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
818 : HAL_TRANSFORM_ROT_90;
819 break;
820 }
821
822 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
823 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
824 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
825 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
826 if (surfaceScaling) {
827 videoScalingMode = surfaceScaling->value;
828 }
829
830 // Use dataspace from format as it has the default aspects already applied
831 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
832 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
833
834 // HDR static info
835 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
836 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
837 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
838
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800839 // HDR10 plus info
840 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
841 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
842 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800843 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
844 hdr10PlusInfo.reset();
845 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800846
Wonsik Kima79c5522022-01-18 16:29:24 -0800847 // HDR dynamic info
848 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
849 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
850 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
851 // TODO: make this sticky & enable unset
852 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
853 hdrDynamicInfo.reset();
854 }
855
856 if (hdr10PlusInfo) {
857 // C2StreamHdr10PlusInfo is deprecated; components should use
858 // C2StreamHdrDynamicMetadataInfo
859 // TODO: #metric
860 if (hdrDynamicInfo) {
861 // It is unexpected that C2StreamHdr10PlusInfo and
862 // C2StreamHdrDynamicMetadataInfo is both present.
863 // C2StreamHdrDynamicMetadataInfo takes priority.
864 // TODO: #metric
865 } else {
866 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
867 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
868 hdr10PlusInfo->flexCount(),
869 0u,
870 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
871 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
872 hdrDynamicInfo = info;
873 }
874 }
875
Pawin Vongmasa36653902018-11-15 00:10:25 -0800876 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
877 if (blocks.size() != 1u) {
878 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
879 return UNKNOWN_ERROR;
880 }
881 const C2ConstGraphicBlock &block = blocks.front();
882
883 // TODO: revisit this after C2Fence implementation.
884 android::IGraphicBufferProducer::QueueBufferInput qbi(
885 timestampNs,
886 false, // droppable
887 dataSpace,
888 Rect(blocks.front().crop().left,
889 blocks.front().crop().top,
890 blocks.front().crop().right(),
891 blocks.front().crop().bottom()),
892 videoScalingMode,
893 transform,
894 Fence::NO_FENCE, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800895 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800896 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800897 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800898 // If mastering max and min luminance fields are 0, do not use them.
899 // It indicates the value may not be present in the stream.
900 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
901 hdrStaticInfo->mastering.minLuminance > 0.0f) {
902 struct android_smpte2086_metadata smpte2086_meta = {
903 .displayPrimaryRed = {
904 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
905 },
906 .displayPrimaryGreen = {
907 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
908 },
909 .displayPrimaryBlue = {
910 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
911 },
912 .whitePoint = {
913 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
914 },
915 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
916 .minLuminance = hdrStaticInfo->mastering.minLuminance,
917 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800918 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800919 hdr.smpte2086 = smpte2086_meta;
920 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700921 // If the content light level fields are 0, do not use them, it
922 // indicates the value may not be present in the stream.
923 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
924 struct android_cta861_3_metadata cta861_meta = {
925 .maxContentLightLevel = hdrStaticInfo->maxCll,
926 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
927 };
928 hdr.validTypes |= HdrMetadata::CTA861_3;
929 hdr.cta8613 = cta861_meta;
930 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800931 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800932 if (hdrDynamicInfo
933 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800934 hdr.validTypes |= HdrMetadata::HDR10PLUS;
935 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800936 hdrDynamicInfo->m.data,
937 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800938 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800939 qbi.setHdrMetadata(hdr);
Wonsik Kima79c5522022-01-18 16:29:24 -0800940
941 SetHdrMetadataToGralloc4Handle(hdrStaticInfo, hdrDynamicInfo, block.handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800942 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800943 // we don't have dirty regions
944 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800945 android::IGraphicBufferProducer::QueueBufferOutput qbo;
946 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
947 if (result != OK) {
948 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800949 if (result == NO_INIT) {
950 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
951 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800952 return result;
953 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800954
955 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
956 ALOGD("[%s] queue buffer successful", mName);
957 } else {
958 ALOGV("[%s] queue buffer successful", mName);
959 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800960
961 int64_t mediaTimeUs = 0;
962 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
963 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
964
965 return OK;
966}
967
968status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
969 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
970 bool released = false;
971 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700972 Mutexed<Input>::Locked input(mInput);
973 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800974 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800975 }
976 }
977 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700978 Mutexed<Output>::Locked output(mOutput);
979 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800980 released = true;
981 }
982 }
983 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800984 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800985 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800986 } else {
987 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
988 }
989 return OK;
990}
991
992void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
993 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700994 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800995
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700996 if (!input->buffers->isArrayMode()) {
997 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800998 }
999
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001000 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001001}
1002
1003void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1004 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001005 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001006
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001007 if (!output->buffers->isArrayMode()) {
1008 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001009 }
1010
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001011 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001012}
1013
1014status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001015 const sp<AMessage> &inputFormat,
1016 const sp<AMessage> &outputFormat,
1017 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001018 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1019 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001020 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001021 C2PortReorderBufferDepthTuning::output reorderDepth;
1022 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001023 C2PortActualDelayTuning::input inputDelay(0);
1024 C2PortActualDelayTuning::output outputDelay(0);
1025 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001026 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001027
Pawin Vongmasa36653902018-11-15 00:10:25 -08001028 c2_status_t err = mComponent->query(
1029 {
1030 &iStreamFormat,
1031 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001032 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001033 &reorderDepth,
1034 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001035 &inputDelay,
1036 &pipelineDelay,
1037 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001038 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001039 },
1040 {},
1041 C2_DONT_BLOCK,
1042 nullptr);
1043 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001044 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001045 return UNKNOWN_ERROR;
1046 }
1047 } else if (err != C2_OK) {
1048 return UNKNOWN_ERROR;
1049 }
1050
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001051 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1052 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1053 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1054
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001055 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1056 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001057
Pawin Vongmasa36653902018-11-15 00:10:25 -08001058 // TODO: get this from input format
1059 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1060
Sungtak Lee04b30352020-07-27 13:57:25 -07001061 // secure mode is a static parameter (shall not change in the executing state)
1062 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1063
Pawin Vongmasa36653902018-11-15 00:10:25 -08001064 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001065 int poolMask = GetCodec2PoolMask();
1066 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001067
1068 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001069 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001070 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001071 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1072 API_REFLECTION |
1073 API_VALUES |
1074 API_CURRENT_VALUES |
1075 API_DEPENDENCY |
1076 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001077 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1078 C2StreamSampleRateInfo::input sampleRate(0u);
1079 C2StreamChannelCountInfo::input channelCount(0u);
1080 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001081 std::shared_ptr<C2BlockPool> pool;
1082 {
1083 Mutexed<BlockPools>::Locked pools(mBlockPools);
1084
1085 // set default allocator ID.
1086 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001087 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001088
1089 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1090 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1091 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001092 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001093 std::vector<C2Param *> stackParams({&featuresSetting});
1094 if (audioEncoder) {
1095 stackParams.push_back(&encoderFrameSize);
1096 stackParams.push_back(&sampleRate);
1097 stackParams.push_back(&channelCount);
1098 stackParams.push_back(&pcmEncoding);
1099 } else {
1100 encoderFrameSize.invalidate();
1101 sampleRate.invalidate();
1102 channelCount.invalidate();
1103 pcmEncoding.invalidate();
1104 }
1105 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001106 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1107 C2_DONT_BLOCK,
1108 &params);
1109 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1110 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1111 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001112 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001113 C2PortAllocatorsTuning::input *inputAllocators =
1114 C2PortAllocatorsTuning::input::From(params[0].get());
1115 if (inputAllocators && inputAllocators->flexCount() > 0) {
1116 std::shared_ptr<C2Allocator> allocator;
1117 // verify allocator IDs and resolve default allocator
1118 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1119 if (allocator) {
1120 pools->inputAllocatorId = allocator->getId();
1121 } else {
1122 ALOGD("[%s] component requested invalid input allocator ID %u",
1123 mName, inputAllocators->m.values[0]);
1124 }
1125 }
1126 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001127 if (featuresSetting) {
1128 apiFeatures = featuresSetting.value;
1129 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001130
1131 // TODO: use C2Component wrapper to associate this pool with ourselves
1132 if ((poolMask >> pools->inputAllocatorId) & 1) {
1133 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1134 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1135 mName, pools->inputAllocatorId,
1136 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1137 asString(err), err);
1138 } else {
1139 err = C2_NOT_FOUND;
1140 }
1141 if (err != C2_OK) {
1142 C2BlockPool::local_id_t inputPoolId =
1143 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1144 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1145 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1146 mName, (unsigned long long)inputPoolId,
1147 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1148 asString(err), err);
1149 if (err != C2_OK) {
1150 return NO_MEMORY;
1151 }
1152 }
1153 pools->inputPool = pool;
1154 }
1155
Wonsik Kim51051262018-11-28 13:59:05 -08001156 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001157 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001158 input->inputDelay = inputDelayValue;
1159 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001160 input->numSlots = numInputSlots;
1161 input->extraBuffers.flush();
1162 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001163 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001164 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1165 input->frameReassembler.init(
1166 pool,
1167 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1168 encoderFrameSize.value,
1169 sampleRate.value,
1170 channelCount.value,
1171 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1172 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001173 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1174 // For encrypted content, framework decrypts source buffer (ashmem) into
1175 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001176 if (!buffersBoundToCodec
1177 && !input->frameReassembler
1178 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001179 input->buffers.reset(new SlotInputBuffers(mName));
1180 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001181 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001182 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001183 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001184 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001185 // This is to ensure buffers do not get released prematurely.
1186 // TODO: handle this without going into array mode
1187 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001188 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001189 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001190 }
1191 } else {
1192 if (hasCryptoOrDescrambler()) {
1193 int32_t capacity = kLinearBufferSize;
1194 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1195 if ((size_t)capacity > kMaxLinearBufferSize) {
1196 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1197 capacity = kMaxLinearBufferSize;
1198 }
1199 if (mDealer == nullptr) {
1200 mDealer = new MemoryDealer(
1201 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001202 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001203 "EncryptedLinearInputBuffers");
1204 mDecryptDestination = mDealer->allocate((size_t)capacity);
1205 }
1206 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001207 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1208 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001209 } else {
1210 mHeapSeqNum = -1;
1211 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001212 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001213 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001214 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001215 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001216 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001217 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001218 }
1219 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001220 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001221
1222 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001223 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001224 } else {
1225 // TODO: error
1226 }
Wonsik Kim51051262018-11-28 13:59:05 -08001227
1228 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001229 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001230 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001231 }
1232
1233 if (outputFormat != nullptr) {
1234 sp<IGraphicBufferProducer> outputSurface;
1235 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001236 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001237 {
1238 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001239 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001240 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001241 outputSurface = output->surface ?
1242 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001243 if (outputSurface) {
1244 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1245 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001246 outputGeneration = output->generation;
1247 }
1248
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001249 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001250 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001251 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001252
1253 {
1254 Mutexed<BlockPools>::Locked pools(mBlockPools);
1255
David Stevensc3fbb282021-01-18 18:11:20 +09001256 prevOutputPoolId = pools->outputPoolId;
1257
Pawin Vongmasa36653902018-11-15 00:10:25 -08001258 // set default allocator ID.
1259 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001260 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001261
1262 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1263 // unsuccessful.
1264 std::vector<std::unique_ptr<C2Param>> params;
1265 err = mComponent->query({ },
1266 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1267 C2_DONT_BLOCK,
1268 &params);
1269 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1270 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1271 mName, params.size(), asString(err), err);
1272 } else if (err == C2_OK && params.size() == 1) {
1273 C2PortAllocatorsTuning::output *outputAllocators =
1274 C2PortAllocatorsTuning::output::From(params[0].get());
1275 if (outputAllocators && outputAllocators->flexCount() > 0) {
1276 std::shared_ptr<C2Allocator> allocator;
1277 // verify allocator IDs and resolve default allocator
1278 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1279 if (allocator) {
1280 pools->outputAllocatorId = allocator->getId();
1281 } else {
1282 ALOGD("[%s] component requested invalid output allocator ID %u",
1283 mName, outputAllocators->m.values[0]);
1284 }
1285 }
1286 }
1287
1288 // use bufferqueue if outputting to a surface.
1289 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1290 // if unsuccessful.
1291 if (outputSurface) {
1292 params.clear();
1293 err = mComponent->query({ },
1294 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1295 C2_DONT_BLOCK,
1296 &params);
1297 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1298 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1299 mName, params.size(), asString(err), err);
1300 } else if (err == C2_OK && params.size() == 1) {
1301 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1302 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1303 if (surfaceAllocator) {
1304 std::shared_ptr<C2Allocator> allocator;
1305 // verify allocator IDs and resolve default allocator
1306 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1307 if (allocator) {
1308 pools->outputAllocatorId = allocator->getId();
1309 } else {
1310 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1311 mName, surfaceAllocator->value);
1312 err = C2_BAD_VALUE;
1313 }
1314 }
1315 }
1316 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1317 && err != C2_OK
1318 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1319 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1320 }
1321 }
1322
1323 if ((poolMask >> pools->outputAllocatorId) & 1) {
1324 err = mComponent->createBlockPool(
1325 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1326 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1327 mName, pools->outputAllocatorId,
1328 (unsigned long long)pools->outputPoolId,
1329 asString(err));
1330 } else {
1331 err = C2_NOT_FOUND;
1332 }
1333 if (err != C2_OK) {
1334 // use basic pool instead
1335 pools->outputPoolId =
1336 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1337 }
1338
1339 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1340 // component.
1341 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1342 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1343
1344 std::vector<std::unique_ptr<C2SettingResult>> failures;
1345 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1346 ALOGD("[%s] Configured output block pool ids %llu => %s",
1347 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1348 outputPoolId_ = pools->outputPoolId;
1349 }
1350
David Stevensc3fbb282021-01-18 18:11:20 +09001351 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1352 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1353 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1354 if (err != C2_OK) {
1355 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1356 (unsigned long long) prevOutputPoolId, asString(err), err);
1357 }
1358 }
1359
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001360 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001361 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001362 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001363 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001364 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001365 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001366 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001367 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001368 }
1369 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001370 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001371 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001372 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001373
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001374 output->buffers->clearStash();
1375 if (reorderDepth) {
1376 output->buffers->setReorderDepth(reorderDepth.value);
1377 }
1378 if (reorderKey) {
1379 output->buffers->setReorderKey(reorderKey.value);
1380 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001381
1382 // Try to set output surface to created block pool if given.
1383 if (outputSurface) {
1384 mComponent->setOutputSurface(
1385 outputPoolId_,
1386 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001387 outputGeneration,
1388 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001389 } else {
1390 // configure CPU read consumer usage
1391 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1392 std::vector<std::unique_ptr<C2SettingResult>> failures;
1393 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1394 // do not print error message for now as most components may not yet
1395 // support this setting
1396 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1397 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001398 }
1399
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001400 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001401 if (buffersBoundToCodec) {
1402 // WORKAROUND: if we're using early CSD workaround we convert to
1403 // array mode, to appease apps assuming the output
1404 // buffers to be of the same size.
1405 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1406 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001407
1408 int32_t channelCount;
1409 int32_t sampleRate;
1410 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1411 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1412 int32_t delay = 0;
1413 int32_t padding = 0;;
1414 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1415 delay = 0;
1416 }
1417 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1418 padding = 0;
1419 }
1420 if (delay || padding) {
1421 // We need write access to the buffers, and we're already in
1422 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001423 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001424 }
1425 }
1426 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001427
1428 int32_t tunneled = 0;
1429 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1430 tunneled = 0;
1431 }
1432 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001433 }
1434
1435 // Set up pipeline control. This has to be done after mInputBuffers and
1436 // mOutputBuffers are initialized to make sure that lingering callbacks
1437 // about buffers from the previous generation do not interfere with the
1438 // newly initialized pipeline capacity.
1439
Wonsik Kim62545252021-01-20 11:25:41 -08001440 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001441 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001442 watcher->inputDelay(inputDelayValue)
1443 .pipelineDelay(pipelineDelayValue)
1444 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001445 .smoothnessFactor(kSmoothnessFactor);
1446 watcher->flush();
1447 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001448
1449 mInputMetEos = false;
1450 mSync.start();
1451 return OK;
1452}
1453
1454status_t CCodecBufferChannel::requestInitialInputBuffers() {
1455 if (mInputSurface) {
1456 return OK;
1457 }
1458
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001459 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001460 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1461 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1462 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001463 return UNKNOWN_ERROR;
1464 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001465 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001466
1467 struct ClientInputBuffer {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001468 size_t index;
1469 sp<MediaCodecBuffer> buffer;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001470 size_t capacity;
1471 };
1472 std::list<ClientInputBuffer> clientInputBuffers;
1473
1474 {
1475 Mutexed<Input>::Locked input(mInput);
1476 while (clientInputBuffers.size() < numInputSlots) {
1477 ClientInputBuffer clientInputBuffer;
1478 if (!input->buffers->requestNewBuffer(&clientInputBuffer.index,
1479 &clientInputBuffer.buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001480 break;
1481 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001482 clientInputBuffer.capacity = clientInputBuffer.buffer->capacity();
1483 clientInputBuffers.emplace_back(std::move(clientInputBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001484 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001485 }
1486 if (clientInputBuffers.empty()) {
1487 ALOGW("[%s] start: cannot allocate memory at all", mName);
1488 return NO_MEMORY;
1489 } else if (clientInputBuffers.size() < numInputSlots) {
1490 ALOGD("[%s] start: cannot allocate memory for all slots, "
1491 "only %zu buffers allocated",
1492 mName, clientInputBuffers.size());
1493 } else {
1494 ALOGV("[%s] %zu initial input buffers available",
1495 mName, clientInputBuffers.size());
1496 }
1497 // Sort input buffers by their capacities in increasing order.
1498 clientInputBuffers.sort(
1499 [](const ClientInputBuffer& a, const ClientInputBuffer& b) {
1500 return a.capacity < b.capacity;
1501 });
1502
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001503 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1504 mFlushedConfigs.lock()->swap(flushedConfigs);
1505 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001506 {
1507 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1508 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1509 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1510 watcher->onWorkQueued(
1511 work->input.ordinal.frameIndex.peeku(),
1512 std::vector(work->input.buffers),
1513 now);
1514 }
1515 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001516 err = mComponent->queue(&flushedConfigs);
1517 if (err != C2_OK) {
1518 ALOGW("[%s] Error while queueing a flushed config", mName);
1519 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001520 }
1521 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001522 if (oStreamFormat.value == C2BufferData::LINEAR &&
1523 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
1524 sp<MediaCodecBuffer> buffer = clientInputBuffers.front().buffer;
1525 // WORKAROUND: Some apps expect CSD available without queueing
1526 // any input. Queue an empty buffer to get the CSD.
1527 buffer->setRange(0, 0);
1528 buffer->meta()->clear();
1529 buffer->meta()->setInt64("timeUs", 0);
1530 if (queueInputBufferInternal(buffer) != OK) {
1531 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1532 mName);
1533 return UNKNOWN_ERROR;
1534 }
1535 clientInputBuffers.pop_front();
1536 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001537
1538 for (const ClientInputBuffer& clientInputBuffer: clientInputBuffers) {
1539 mCallback->onInputBufferAvailable(
1540 clientInputBuffer.index,
1541 clientInputBuffer.buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001542 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001543
Pawin Vongmasa36653902018-11-15 00:10:25 -08001544 return OK;
1545}
1546
1547void CCodecBufferChannel::stop() {
1548 mSync.stop();
1549 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001550}
1551
Wonsik Kim936a89c2020-05-08 16:07:50 -07001552void CCodecBufferChannel::reset() {
1553 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001554 if (mInputSurface != nullptr) {
1555 mInputSurface.reset();
1556 }
1557 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001558 {
1559 Mutexed<Input>::Locked input(mInput);
1560 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001561 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001562 }
1563 {
1564 Mutexed<Output>::Locked output(mOutput);
1565 output->buffers.reset();
1566 }
1567}
1568
1569void CCodecBufferChannel::release() {
1570 mComponent.reset();
1571 mInputAllocator.reset();
1572 mOutputSurface.lock()->surface.clear();
1573 {
1574 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1575 blockPools->inputPool.reset();
1576 blockPools->outputPoolIntf.reset();
1577 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001578 setCrypto(nullptr);
1579 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001580}
1581
Pawin Vongmasa36653902018-11-15 00:10:25 -08001582void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1583 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001584 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001585 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001586 {
1587 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1588 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1589 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1590 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1591 watcher->onWorkDone(frameIndex);
1592 continue;
1593 }
1594 if (work->input.buffers.empty()
1595 || work->input.buffers.front() == nullptr
1596 || work->input.buffers.front()->data().linearBlocks().empty()) {
1597 ALOGD("[%s] no linear codec config data found", mName);
1598 watcher->onWorkDone(frameIndex);
1599 continue;
1600 }
1601 std::unique_ptr<C2Work> copy(new C2Work);
1602 copy->input.flags = C2FrameData::flags_t(
1603 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1604 copy->input.ordinal = work->input.ordinal;
1605 copy->input.ordinal.frameIndex = mFrameIndex++;
1606 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1607 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1608 }
1609 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1610 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1611 }
1612 copy->input.infoBuffers.insert(
1613 copy->input.infoBuffers.begin(),
1614 work->input.infoBuffers.begin(),
1615 work->input.infoBuffers.end());
1616 copy->worklets.emplace_back(new C2Worklet);
1617 configs.push_back(std::move(copy));
1618 watcher->onWorkDone(frameIndex);
1619 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001620 }
1621 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001622 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001623 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001624 Mutexed<Input>::Locked input(mInput);
1625 input->buffers->flush();
1626 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001627 }
1628 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001629 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001630 if (output->buffers) {
1631 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001632 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001633 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001634 }
1635}
1636
1637void CCodecBufferChannel::onWorkDone(
1638 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001639 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001640 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001641 feedInputBufferIfAvailable();
1642 }
1643}
1644
1645void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001646 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001647 if (mInputSurface) {
1648 return;
1649 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001650 std::shared_ptr<C2Buffer> buffer =
1651 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001652 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001653 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001654 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001655 if (input->lastFlushIndex >= frameIndex) {
1656 ALOGD("[%s] Ignoring stale input buffer done callback: "
1657 "last flush index = %lld, frameIndex = %lld",
1658 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1659 } else {
1660 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1661 if (!newInputSlotAvailable) {
1662 (void)input->extraBuffers.expireComponentBuffer(buffer);
1663 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001664 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001665 }
1666 if (newInputSlotAvailable) {
1667 feedInputBufferIfAvailable();
1668 }
1669}
1670
1671bool CCodecBufferChannel::handleWork(
1672 std::unique_ptr<C2Work> work,
1673 const sp<AMessage> &outputFormat,
1674 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001675 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001676 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001677 if (!output->buffers) {
1678 return false;
1679 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001680 }
1681
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001682 // Whether the output buffer should be reported to the client or not.
1683 bool notifyClient = false;
1684
1685 if (work->result == C2_OK){
1686 notifyClient = true;
1687 } else if (work->result == C2_NOT_FOUND) {
1688 ALOGD("[%s] flushed work; ignored.", mName);
1689 } else {
1690 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1691 // the config update.
1692 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1693 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1694 return false;
1695 }
1696
1697 if ((work->input.ordinal.frameIndex -
1698 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001699 // Discard frames from previous generation.
1700 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001701 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001702 }
1703
Wonsik Kim524b0582019-03-12 11:28:57 -07001704 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001705 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001706 || !(work->worklets.front()->output.flags &
1707 C2FrameData::FLAG_INCOMPLETE))) {
1708 mPipelineWatcher.lock()->onWorkDone(
1709 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001710 }
1711
1712 // NOTE: MediaCodec usage supposedly have only one worklet
1713 if (work->worklets.size() != 1u) {
1714 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1715 mName, work->worklets.size());
1716 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1717 return false;
1718 }
1719
1720 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1721
1722 std::shared_ptr<C2Buffer> buffer;
1723 // NOTE: MediaCodec usage supposedly have only one output stream.
1724 if (worklet->output.buffers.size() > 1u) {
1725 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1726 mName, worklet->output.buffers.size());
1727 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1728 return false;
1729 } else if (worklet->output.buffers.size() == 1u) {
1730 buffer = worklet->output.buffers[0];
1731 if (!buffer) {
1732 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1733 }
1734 }
1735
Wonsik Kim3dedf682021-05-03 10:57:09 -07001736 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1737 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001738 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001739 while (!worklet->output.configUpdate.empty()) {
1740 std::unique_ptr<C2Param> param;
1741 worklet->output.configUpdate.back().swap(param);
1742 worklet->output.configUpdate.pop_back();
1743 switch (param->coreIndex().coreIndex()) {
1744 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1745 C2PortReorderBufferDepthTuning::output reorderDepth;
1746 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001747 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1748 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001749 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001750 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001751 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001752 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1753 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001754 }
1755 break;
1756 }
1757 case C2PortReorderKeySetting::CORE_INDEX: {
1758 C2PortReorderKeySetting::output reorderKey;
1759 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001760 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001761 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1762 mName, reorderKey.value);
1763 } else {
1764 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1765 }
1766 break;
1767 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001768 case C2PortActualDelayTuning::CORE_INDEX: {
1769 if (param->isGlobal()) {
1770 C2ActualPipelineDelayTuning pipelineDelay;
1771 if (pipelineDelay.updateFrom(*param)) {
1772 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1773 mName, pipelineDelay.value);
1774 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001775 (void)mPipelineWatcher.lock()->pipelineDelay(
1776 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001777 }
1778 }
1779 if (param->forInput()) {
1780 C2PortActualDelayTuning::input inputDelay;
1781 if (inputDelay.updateFrom(*param)) {
1782 ALOGV("[%s] onWorkDone: updating input delay %u",
1783 mName, inputDelay.value);
1784 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001785 (void)mPipelineWatcher.lock()->inputDelay(
1786 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001787 }
1788 }
1789 if (param->forOutput()) {
1790 C2PortActualDelayTuning::output outputDelay;
1791 if (outputDelay.updateFrom(*param)) {
1792 ALOGV("[%s] onWorkDone: updating output delay %u",
1793 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001794 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001795 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001796 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001797
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001798 }
1799 }
1800 break;
1801 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001802 case C2PortTunnelSystemTime::CORE_INDEX: {
1803 C2PortTunnelSystemTime::output frameRenderTime;
1804 if (frameRenderTime.updateFrom(*param)) {
1805 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1806 mName, (long long)frameRenderTime.value,
1807 (long long)worklet->output.ordinal.timestamp.peekll());
1808 mCCodecCallback->onOutputFramesRendered(
1809 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1810 }
1811 break;
1812 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001813 case C2StreamTunnelHoldRender::CORE_INDEX: {
1814 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1815 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1816 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1817 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1818 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1819 mCCodecCallback->onFirstTunnelFrameReady();
1820 break;
1821 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001822 default:
1823 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1824 mName, param->index());
1825 break;
1826 }
1827 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001828 if (newInputDelay || newPipelineDelay) {
1829 Mutexed<Input>::Locked input(mInput);
1830 size_t newNumSlots =
1831 newInputDelay.value_or(input->inputDelay) +
1832 newPipelineDelay.value_or(input->pipelineDelay) +
1833 kSmoothnessFactor;
1834 if (input->buffers->isArrayMode()) {
1835 if (input->numSlots >= newNumSlots) {
1836 input->numExtraSlots = 0;
1837 } else {
1838 input->numExtraSlots = newNumSlots - input->numSlots;
1839 }
1840 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1841 mName, input->numExtraSlots);
1842 } else {
1843 input->numSlots = newNumSlots;
1844 }
1845 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001846 size_t numOutputSlots = 0;
1847 uint32_t reorderDepth = 0;
1848 bool outputBuffersChanged = false;
1849 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
1850 Mutexed<Output>::Locked output(mOutput);
1851 if (!output->buffers) {
1852 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001853 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001854 numOutputSlots = output->numSlots;
1855 if (newReorderKey) {
1856 output->buffers->setReorderKey(newReorderKey.value());
1857 }
1858 if (newReorderDepth) {
1859 output->buffers->setReorderDepth(newReorderDepth.value());
1860 }
1861 reorderDepth = output->buffers->getReorderDepth();
1862 if (newOutputDelay) {
1863 output->outputDelay = newOutputDelay.value();
1864 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
1865 if (output->numSlots < numOutputSlots) {
1866 output->numSlots = numOutputSlots;
1867 if (output->buffers->isArrayMode()) {
1868 OutputBuffersArray *array =
1869 (OutputBuffersArray *)output->buffers.get();
1870 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1871 mName, numOutputSlots);
1872 array->grow(numOutputSlots);
1873 outputBuffersChanged = true;
1874 }
1875 }
1876 }
1877 numOutputSlots = output->numSlots;
1878 }
1879 if (outputBuffersChanged) {
1880 mCCodecCallback->onOutputBuffersChanged();
1881 }
1882 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07001883 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07001884 {
1885 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1886 maxDequeueCount = output->maxDequeueBuffers =
1887 numOutputSlots + reorderDepth + kRenderingDepth;
1888 if (output->surface) {
1889 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1890 }
1891 }
1892 if (maxDequeueCount > 0) {
1893 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001894 }
1895 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001896
Pawin Vongmasa36653902018-11-15 00:10:25 -08001897 int32_t flags = 0;
1898 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1899 flags |= MediaCodec::BUFFER_FLAG_EOS;
1900 ALOGV("[%s] onWorkDone: output EOS", mName);
1901 }
1902
Pawin Vongmasa36653902018-11-15 00:10:25 -08001903 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1904 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1905 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1906 // shall correspond to the client input timesamp (in customOrdinal). By using the
1907 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1908 // produces multiple output.
1909 c2_cntr64_t timestamp =
1910 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1911 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001912 if (mInputSurface != nullptr) {
1913 // When using input surface we need to restore the original input timestamp.
1914 timestamp = work->input.ordinal.customOrdinal;
1915 }
My Name6bd9a7d2022-03-25 12:37:58 -07001916 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
1917 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001918 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1919 mName,
1920 work->input.ordinal.customOrdinal.peekll(),
1921 work->input.ordinal.timestamp.peekll(),
1922 worklet->output.ordinal.timestamp.peekll(),
1923 timestamp.peekll());
1924
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001925 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001926 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001927 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001928 if (output->buffers && outputFormat) {
1929 output->buffers->updateSkipCutBuffer(outputFormat);
1930 output->buffers->setFormat(outputFormat);
1931 }
1932 if (!notifyClient) {
1933 return false;
1934 }
1935 size_t index;
1936 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07001937 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001938 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1939 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1940 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1941
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001942 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001943 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001944 } else {
1945 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001946 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001947 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001948 return false;
1949 }
1950 }
1951
Wonsik Kimec585c32021-10-01 01:11:00 -07001952 bool drop = false;
1953 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
1954 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
1955 drop = true;
1956 }
1957
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001958 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07001959 if (mTunneled && drop && outputFormat) {
1960 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
1961 mName, work->input.ordinal.frameIndex.peekull());
1962 } else {
1963 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1964 mName, work->input.ordinal.frameIndex.peekull());
1965 notifyClient = false;
1966 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001967 }
1968
1969 if (buffer) {
1970 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1971 // TODO: properly translate these to metadata
1972 switch (info->coreIndex().coreIndex()) {
1973 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001974 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001975 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1976 }
1977 break;
1978 default:
1979 break;
1980 }
1981 }
1982 }
1983
1984 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001985 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07001986 if (!output->buffers) {
1987 return false;
1988 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001989 output->buffers->pushToStash(
1990 buffer,
1991 notifyClient,
1992 timestamp.peek(),
1993 flags,
1994 outputFormat,
1995 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001996 }
1997 sendOutputBuffers();
1998 return true;
1999}
2000
2001void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002002 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002003 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002004 sp<MediaCodecBuffer> outBuffer;
2005 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002006
2007 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002008 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002009 if (!output->buffers) {
2010 return;
2011 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002012 action = output->buffers->popFromStashAndRegister(
2013 &c2Buffer, &index, &outBuffer);
2014 switch (action) {
2015 case OutputBuffers::SKIP:
2016 return;
2017 case OutputBuffers::DISCARD:
2018 break;
2019 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00002020 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002021 mCallback->onOutputBufferAvailable(index, outBuffer);
2022 break;
2023 case OutputBuffers::REALLOCATE:
2024 if (!output->buffers->isArrayMode()) {
2025 output->buffers =
2026 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002027 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002028 static_cast<OutputBuffersArray*>(output->buffers.get())->
2029 realloc(c2Buffer);
2030 output.unlock();
2031 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002032 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002033 case OutputBuffers::RETRY:
2034 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2035 mName);
2036 return;
2037 default:
2038 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2039 "corrupted BufferAction value (%d) "
2040 "returned from popFromStashAndRegister.",
2041 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002042 return;
2043 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002044 }
2045}
2046
2047status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
2048 static std::atomic_uint32_t surfaceGeneration{0};
2049 uint32_t generation = (getpid() << 10) |
2050 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2051 & ((1 << 10) - 1));
2052
2053 sp<IGraphicBufferProducer> producer;
Sungtak Leedb14cba2021-04-10 00:50:23 -07002054 int maxDequeueCount = mOutputSurface.lock()->maxDequeueBuffers;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002055 if (newSurface) {
2056 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002057 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002058 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002059 producer = newSurface->getIGraphicBufferProducer();
2060 producer->setGenerationNumber(generation);
2061 } else {
2062 ALOGE("[%s] setting output surface to null", mName);
2063 return INVALID_OPERATION;
2064 }
2065
2066 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2067 C2BlockPool::local_id_t outputPoolId;
2068 {
2069 Mutexed<BlockPools>::Locked pools(mBlockPools);
2070 outputPoolId = pools->outputPoolId;
2071 outputPoolIntf = pools->outputPoolIntf;
2072 }
2073
2074 if (outputPoolIntf) {
2075 if (mComponent->setOutputSurface(
2076 outputPoolId,
2077 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002078 generation,
2079 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002080 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2081 return INVALID_OPERATION;
2082 }
2083 }
2084
2085 {
2086 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2087 output->surface = newSurface;
2088 output->generation = generation;
2089 }
2090
2091 return OK;
2092}
2093
Wonsik Kimab34ed62019-01-31 15:28:46 -08002094PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002095 // When client pushed EOS, we want all the work to be done quickly.
2096 // Otherwise, component may have stalled work due to input starvation up to
2097 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002098 size_t n = 0;
2099 if (!mInputMetEos) {
2100 size_t outputDelay = mOutput.lock()->outputDelay;
2101 Mutexed<Input>::Locked input(mInput);
2102 n = input->inputDelay + input->pipelineDelay + outputDelay;
2103 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002104 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002105}
2106
Pawin Vongmasa36653902018-11-15 00:10:25 -08002107void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2108 mMetaMode = mode;
2109}
2110
Wonsik Kim596187e2019-10-25 12:44:10 -07002111void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002112 if (mCrypto != nullptr) {
2113 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2114 mCrypto->unsetHeap(entry.second);
2115 }
2116 mHeapSeqNumMap.clear();
2117 if (mHeapSeqNum >= 0) {
2118 mCrypto->unsetHeap(mHeapSeqNum);
2119 mHeapSeqNum = -1;
2120 }
2121 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002122 mCrypto = crypto;
2123}
2124
2125void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2126 mDescrambler = descrambler;
2127}
2128
Pawin Vongmasa36653902018-11-15 00:10:25 -08002129status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2130 // C2_OK is always translated to OK.
2131 if (c2s == C2_OK) {
2132 return OK;
2133 }
2134
2135 // Operation-dependent translation
2136 // TODO: Add as necessary
2137 switch (c2op) {
2138 case C2_OPERATION_Component_start:
2139 switch (c2s) {
2140 case C2_NO_MEMORY:
2141 return NO_MEMORY;
2142 default:
2143 return UNKNOWN_ERROR;
2144 }
2145 default:
2146 break;
2147 }
2148
2149 // Backup operation-agnostic translation
2150 switch (c2s) {
2151 case C2_BAD_INDEX:
2152 return BAD_INDEX;
2153 case C2_BAD_VALUE:
2154 return BAD_VALUE;
2155 case C2_BLOCKING:
2156 return WOULD_BLOCK;
2157 case C2_DUPLICATE:
2158 return ALREADY_EXISTS;
2159 case C2_NO_INIT:
2160 return NO_INIT;
2161 case C2_NO_MEMORY:
2162 return NO_MEMORY;
2163 case C2_NOT_FOUND:
2164 return NAME_NOT_FOUND;
2165 case C2_TIMED_OUT:
2166 return TIMED_OUT;
2167 case C2_BAD_STATE:
2168 case C2_CANCELED:
2169 case C2_CANNOT_DO:
2170 case C2_CORRUPTED:
2171 case C2_OMITTED:
2172 case C2_REFUSED:
2173 return UNKNOWN_ERROR;
2174 default:
2175 return -static_cast<status_t>(c2s);
2176 }
2177}
2178
2179} // namespace android