blob: cb2ffa08887420a03aa4f36851fcc5f6aaa2541e [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright 2017, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010018#include <utils/Errors.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080019#define LOG_TAG "CCodecBufferChannel"
My Name6bd9a7d2022-03-25 12:37:58 -070020#define ATRACE_TAG ATRACE_TAG_VIDEO
Pawin Vongmasa36653902018-11-15 00:10:25 -080021#include <utils/Log.h>
My Name6bd9a7d2022-03-25 12:37:58 -070022#include <utils/Trace.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080023
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070024#include <algorithm>
Wonsik Kim6b2c8be2021-09-28 05:11:04 -070025#include <atomic>
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070026#include <list>
Pawin Vongmasa36653902018-11-15 00:10:25 -080027#include <numeric>
28
29#include <C2AllocatorGralloc.h>
30#include <C2PlatformSupport.h>
31#include <C2BlockInternal.h>
32#include <C2Config.h>
33#include <C2Debug.h>
34
35#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070036#include <android/hardware/drm/1.0/types.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080037#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080038#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080039#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080040#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070041#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080042#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070043#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080044#include <media/openmax/OMX_Core.h>
45#include <media/stagefright/foundation/ABuffer.h>
46#include <media/stagefright/foundation/ALookup.h>
47#include <media/stagefright/foundation/AMessage.h>
48#include <media/stagefright/foundation/AUtils.h>
49#include <media/stagefright/foundation/hexdump.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080050#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070051#include <media/stagefright/SkipCutBuffer.h>
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010052#include <media/stagefright/SurfaceUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080053#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070054#include <mediadrm/ICrypto.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080055#include <system/window.h>
56
57#include "CCodecBufferChannel.h"
58#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080059
60namespace android {
61
62using android::base::StringPrintf;
63using hardware::hidl_handle;
64using hardware::hidl_string;
65using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070066using hardware::fromHeap;
67using hardware::HidlMemory;
68
Pawin Vongmasa36653902018-11-15 00:10:25 -080069using namespace hardware::cas::V1_0;
70using namespace hardware::cas::native::V1_0;
71
72using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070073using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080074
Pawin Vongmasa36653902018-11-15 00:10:25 -080075namespace {
76
Wonsik Kim469c8342019-04-11 16:46:09 -070077constexpr size_t kSmoothnessFactor = 4;
78constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080079
Sungtak Leeab6f2f32019-02-15 14:43:51 -080080// This is for keeping IGBP's buffer dropping logic in legacy mode other
81// than making it non-blocking. Do not change this value.
82const static size_t kDequeueTimeoutNs = 0;
83
Pawin Vongmasa36653902018-11-15 00:10:25 -080084} // namespace
85
86CCodecBufferChannel::QueueGuard::QueueGuard(
87 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
88 Mutex::Autolock l(mSync.mGuardLock);
89 // At this point it's guaranteed that mSync is not under state transition,
90 // as we are holding its mutex.
91
92 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
93 if (count->value == -1) {
94 mRunning = false;
95 } else {
96 ++count->value;
97 mRunning = true;
98 }
99}
100
101CCodecBufferChannel::QueueGuard::~QueueGuard() {
102 if (mRunning) {
103 // We are not holding mGuardLock at this point so that QueueSync::stop() can
104 // keep holding the lock until mCount reaches zero.
105 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
106 --count->value;
107 count->cond.broadcast();
108 }
109}
110
111void CCodecBufferChannel::QueueSync::start() {
112 Mutex::Autolock l(mGuardLock);
113 // If stopped, it goes to running state; otherwise no-op.
114 Mutexed<Counter>::Locked count(mCount);
115 if (count->value == -1) {
116 count->value = 0;
117 }
118}
119
120void CCodecBufferChannel::QueueSync::stop() {
121 Mutex::Autolock l(mGuardLock);
122 Mutexed<Counter>::Locked count(mCount);
123 if (count->value == -1) {
124 // no-op
125 return;
126 }
127 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
128 // mCount can only decrement. In other words, threads that acquired the lock
129 // are allowed to finish execution but additional threads trying to acquire
130 // the lock at this point will block, and then get QueueGuard at STOPPED
131 // state.
132 while (count->value != 0) {
133 count.waitForCondition(count->cond);
134 }
135 count->value = -1;
136}
137
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700138// Input
139
140CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
141
Pawin Vongmasa36653902018-11-15 00:10:25 -0800142// CCodecBufferChannel
143
144CCodecBufferChannel::CCodecBufferChannel(
145 const std::shared_ptr<CCodecCallback> &callback)
146 : mHeapSeqNum(-1),
147 mCCodecCallback(callback),
148 mFrameIndex(0u),
149 mFirstValidFrameIndex(0u),
150 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700151 mInputMetEos(false),
152 mSendEncryptedInfoBuffer(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700153 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700154 {
155 Mutexed<Input>::Locked input(mInput);
156 input->buffers.reset(new DummyInputBuffers(""));
157 input->extraBuffers.flush();
158 input->inputDelay = 0u;
159 input->pipelineDelay = 0u;
160 input->numSlots = kSmoothnessFactor;
161 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700162 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700163 }
164 {
165 Mutexed<Output>::Locked output(mOutput);
166 output->outputDelay = 0u;
167 output->numSlots = kSmoothnessFactor;
168 }
David Stevensc3fbb282021-01-18 18:11:20 +0900169 {
170 Mutexed<BlockPools>::Locked pools(mBlockPools);
171 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
172 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800173}
174
175CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800176 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800177 mCrypto->unsetHeap(mHeapSeqNum);
178 }
179}
180
181void CCodecBufferChannel::setComponent(
182 const std::shared_ptr<Codec2Client::Component> &component) {
183 mComponent = component;
184 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
185 mName = mComponentName.c_str();
186}
187
188status_t CCodecBufferChannel::setInputSurface(
189 const std::shared_ptr<InputSurfaceWrapper> &surface) {
190 ALOGV("[%s] setInputSurface", mName);
191 mInputSurface = surface;
192 return mInputSurface->connect(mComponent);
193}
194
195status_t CCodecBufferChannel::signalEndOfInputStream() {
196 if (mInputSurface == nullptr) {
197 return INVALID_OPERATION;
198 }
199 return mInputSurface->signalEndOfInputStream();
200}
201
Sungtak Lee04b30352020-07-27 13:57:25 -0700202status_t CCodecBufferChannel::queueInputBufferInternal(
203 sp<MediaCodecBuffer> buffer,
204 std::shared_ptr<C2LinearBlock> encryptedBlock,
205 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800206 int64_t timeUs;
207 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
208
209 if (mInputMetEos) {
210 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
211 return OK;
212 }
213
214 int32_t flags = 0;
215 int32_t tmp = 0;
216 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200217 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800218 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
219 eos = true;
220 mInputMetEos = true;
221 ALOGV("[%s] input EOS", mName);
222 }
223 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
224 flags |= C2FrameData::FLAG_CODEC_CONFIG;
225 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200226 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
227 tunnelFirstFrame = true;
228 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800229 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800230 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800231 std::unique_ptr<C2Work> work(new C2Work);
232 work->input.ordinal.timestamp = timeUs;
233 work->input.ordinal.frameIndex = mFrameIndex++;
234 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
235 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
236 // Keep client timestamp in customOrdinal
237 work->input.ordinal.customOrdinal = timeUs;
238 work->input.buffers.clear();
239
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700240 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800241 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800242
Pawin Vongmasa36653902018-11-15 00:10:25 -0800243 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700244 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800245 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700246 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800247 return -ENOENT;
248 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700249 // TODO: we want to delay copying buffers.
250 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
251 copy = input->buffers->cloneAndReleaseBuffer(buffer);
252 if (copy != nullptr) {
253 (void)input->extraBuffers.assignSlot(copy);
254 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
255 return UNKNOWN_ERROR;
256 }
257 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
258 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
259 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700260 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700261 } else {
262 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
263 "buffer starvation on component.", mName);
264 }
265 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800266 if (input->frameReassembler) {
267 usesFrameReassembler = true;
268 input->frameReassembler.process(buffer, &items);
269 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900270 int32_t cvo = 0;
271 if (buffer->meta()->findInt32("cvo", &cvo)) {
272 int32_t rotation = cvo % 360;
273 // change rotation to counter-clock wise.
274 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
275
276 Mutexed<OutputSurface>::Locked output(mOutputSurface);
277 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
278 output->rotation[frameIndex] = rotation;
279 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800280 work->input.buffers.push_back(c2buffer);
281 if (encryptedBlock) {
282 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
283 kParamIndexEncryptedBuffer,
284 encryptedBlock->share(0, blockSize, C2Fence())));
285 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700286 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800287 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700288 Mutexed<Input>::Locked input(mInput);
289 if (input->frameReassembler) {
290 usesFrameReassembler = true;
291 // drain any pending items with eos
292 input->frameReassembler.process(buffer, &items);
293 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800294 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800295 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800296 if (usesFrameReassembler) {
297 if (!items.empty()) {
298 items.front()->input.configUpdate = std::move(mParamsToBeSet);
299 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
300 }
301 } else {
302 work->input.flags = (C2FrameData::flags_t)flags;
303 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800304
Wonsik Kime1104ca2020-11-24 15:01:33 -0800305 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200306 if (tunnelFirstFrame) {
307 C2StreamTunnelHoldRender::input tunnelHoldRender{
308 0u /* stream */,
309 C2_TRUE /* value */
310 };
311 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
312 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800313 work->worklets.clear();
314 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800315
Wonsik Kime1104ca2020-11-24 15:01:33 -0800316 items.push_back(std::move(work));
317
318 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800319 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800320 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800321 work.reset(new C2Work);
322 work->input.ordinal.timestamp = timeUs;
323 work->input.ordinal.frameIndex = mFrameIndex++;
324 // WORKAROUND: keep client timestamp in customOrdinal
325 work->input.ordinal.customOrdinal = timeUs;
326 work->input.buffers.clear();
327 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800328 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800329 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800330 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800331 c2_status_t err = C2_OK;
332 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700333 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
334 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800335 {
336 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
337 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
338 for (const std::unique_ptr<C2Work> &work : items) {
339 watcher->onWorkQueued(
340 work->input.ordinal.frameIndex.peeku(),
341 std::vector(work->input.buffers),
342 now);
343 }
344 }
345 err = mComponent->queue(&items);
346 }
347 if (err != C2_OK) {
348 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
349 for (const std::unique_ptr<C2Work> &work : items) {
350 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
351 }
352 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700353 Mutexed<Input>::Locked input(mInput);
354 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700355 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700356 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700357 } else if (buffer) {
358 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700359 }
360 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
361 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800362 }
363
364 feedInputBufferIfAvailableInternal();
365 return err;
366}
367
368status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
369 QueueGuard guard(mSync);
370 if (!guard.isRunning()) {
371 ALOGD("[%s] setParameters is only supported in the running state.", mName);
372 return -ENOSYS;
373 }
374 mParamsToBeSet.insert(mParamsToBeSet.end(),
375 std::make_move_iterator(params.begin()),
376 std::make_move_iterator(params.end()));
377 params.clear();
378 return OK;
379}
380
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800381status_t CCodecBufferChannel::attachBuffer(
382 const std::shared_ptr<C2Buffer> &c2Buffer,
383 const sp<MediaCodecBuffer> &buffer) {
384 if (!buffer->copy(c2Buffer)) {
385 return -ENOSYS;
386 }
387 return OK;
388}
389
390void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
391 if (!mDecryptDestination || mDecryptDestination->size() < size) {
392 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
393 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
394 mCrypto->unsetHeap(mHeapSeqNum);
395 }
396 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
397 if (mCrypto) {
398 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
399 }
400 }
401}
402
403int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
404 CHECK(mCrypto);
405 auto it = mHeapSeqNumMap.find(memory);
406 int32_t heapSeqNum = -1;
407 if (it == mHeapSeqNumMap.end()) {
408 heapSeqNum = mCrypto->setHeap(memory);
409 mHeapSeqNumMap.emplace(memory, heapSeqNum);
410 } else {
411 heapSeqNum = it->second;
412 }
413 return heapSeqNum;
414}
415
416status_t CCodecBufferChannel::attachEncryptedBuffer(
417 const sp<hardware::HidlMemory> &memory,
418 bool secure,
419 const uint8_t *key,
420 const uint8_t *iv,
421 CryptoPlugin::Mode mode,
422 CryptoPlugin::Pattern pattern,
423 size_t offset,
424 const CryptoPlugin::SubSample *subSamples,
425 size_t numSubSamples,
426 const sp<MediaCodecBuffer> &buffer) {
427 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
428 static const C2MemoryUsage kDefaultReadWriteUsage{
429 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
430
431 size_t size = 0;
432 for (size_t i = 0; i < numSubSamples; ++i) {
433 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
434 }
435 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
436 std::shared_ptr<C2LinearBlock> block;
437 c2_status_t err = pool->fetchLinearBlock(
438 size,
439 secure ? kSecureUsage : kDefaultReadWriteUsage,
440 &block);
441 if (err != C2_OK) {
442 return NO_MEMORY;
443 }
444 if (!secure) {
445 ensureDecryptDestination(size);
446 }
447 ssize_t result = -1;
448 ssize_t codecDataOffset = 0;
449 if (mCrypto) {
450 AString errorDetailMsg;
451 int32_t heapSeqNum = getHeapSeqNum(memory);
452 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
453 hardware::drm::V1_0::DestinationBuffer dst;
454 if (secure) {
455 dst.type = DrmBufferType::NATIVE_HANDLE;
456 dst.secureMemory = hardware::hidl_handle(block->handle());
457 } else {
458 dst.type = DrmBufferType::SHARED_MEMORY;
459 IMemoryToSharedBuffer(
460 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
461 }
462 result = mCrypto->decrypt(
463 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
464 dst, &errorDetailMsg);
465 if (result < 0) {
466 return result;
467 }
468 if (dst.type == DrmBufferType::SHARED_MEMORY) {
469 C2WriteView view = block->map().get();
470 if (view.error() != C2_OK) {
471 return false;
472 }
473 if (view.size() < result) {
474 return false;
475 }
476 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
477 }
478 } else {
479 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
480 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
481 hidl_vec<SubSample> hidlSubSamples;
482 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
483
484 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
485 hardware::cas::native::V1_0::DestinationBuffer dst;
486 if (secure) {
487 dst.type = BufferType::NATIVE_HANDLE;
488 dst.secureMemory = hardware::hidl_handle(block->handle());
489 } else {
490 dst.type = BufferType::SHARED_MEMORY;
491 dst.nonsecureMemory = src;
492 }
493
494 CasStatus status = CasStatus::OK;
495 hidl_string detailedError;
496 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
497
498 if (key != nullptr) {
499 sctrl = (ScramblingControl)key[0];
500 // Adjust for the PES offset
501 codecDataOffset = key[2] | (key[3] << 8);
502 }
503
504 auto returnVoid = mDescrambler->descramble(
505 sctrl,
506 hidlSubSamples,
507 src,
508 0,
509 dst,
510 0,
511 [&status, &result, &detailedError] (
512 CasStatus _status, uint32_t _bytesWritten,
513 const hidl_string& _detailedError) {
514 status = _status;
515 result = (ssize_t)_bytesWritten;
516 detailedError = _detailedError;
517 });
518
519 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
520 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
521 mName, returnVoid.description().c_str(), status, result);
522 return UNKNOWN_ERROR;
523 }
524
525 if (result < codecDataOffset) {
526 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
527 return BAD_VALUE;
528 }
529 }
530 if (!secure) {
531 C2WriteView view = block->map().get();
532 if (view.error() != C2_OK) {
533 return UNKNOWN_ERROR;
534 }
535 if (view.size() < result) {
536 return UNKNOWN_ERROR;
537 }
538 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
539 }
540 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
541 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
542 if (!buffer->copy(c2Buffer)) {
543 return -ENOSYS;
544 }
545 return OK;
546}
547
Pawin Vongmasa36653902018-11-15 00:10:25 -0800548status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
549 QueueGuard guard(mSync);
550 if (!guard.isRunning()) {
551 ALOGD("[%s] No more buffers should be queued at current state.", mName);
552 return -ENOSYS;
553 }
554 return queueInputBufferInternal(buffer);
555}
556
557status_t CCodecBufferChannel::queueSecureInputBuffer(
558 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
559 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
560 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
561 AString *errorDetailMsg) {
562 QueueGuard guard(mSync);
563 if (!guard.isRunning()) {
564 ALOGD("[%s] No more buffers should be queued at current state.", mName);
565 return -ENOSYS;
566 }
567
568 if (!hasCryptoOrDescrambler()) {
569 return -ENOSYS;
570 }
571 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
572
Sungtak Lee04b30352020-07-27 13:57:25 -0700573 std::shared_ptr<C2LinearBlock> block;
574 size_t allocSize = buffer->size();
575 size_t bufferSize = 0;
576 c2_status_t blockRes = C2_OK;
577 bool copied = false;
578 if (mSendEncryptedInfoBuffer) {
579 static const C2MemoryUsage kDefaultReadWriteUsage{
580 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
581 constexpr int kAllocGranule0 = 1024 * 64;
582 constexpr int kAllocGranule1 = 1024 * 1024;
583 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
584 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
585 if (allocSize <= kAllocGranule1) {
586 bufferSize = align(allocSize, kAllocGranule0);
587 } else {
588 bufferSize = align(allocSize, kAllocGranule1);
589 }
590 blockRes = pool->fetchLinearBlock(
591 bufferSize, kDefaultReadWriteUsage, &block);
592
593 if (blockRes == C2_OK) {
594 C2WriteView view = block->map().get();
595 if (view.error() == C2_OK && view.size() == bufferSize) {
596 copied = true;
597 // TODO: only copy clear sections
598 memcpy(view.data(), buffer->data(), allocSize);
599 }
600 }
601 }
602
603 if (!copied) {
604 block.reset();
605 }
606
Pawin Vongmasa36653902018-11-15 00:10:25 -0800607 ssize_t result = -1;
608 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700609 if (numSubSamples == 1
610 && subSamples[0].mNumBytesOfClearData == 0
611 && subSamples[0].mNumBytesOfEncryptedData == 0) {
612 // We don't need to go through crypto or descrambler if the input is empty.
613 result = 0;
614 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700615 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800616 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700617 destination.type = DrmBufferType::NATIVE_HANDLE;
618 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800619 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700620 destination.type = DrmBufferType::SHARED_MEMORY;
621 IMemoryToSharedBuffer(
622 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800623 }
Robert Shih895fba92019-07-16 16:29:44 -0700624 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800625 encryptedBuffer->fillSourceBuffer(&source);
626 result = mCrypto->decrypt(
627 key, iv, mode, pattern, source, buffer->offset(),
628 subSamples, numSubSamples, destination, errorDetailMsg);
629 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700630 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800631 return result;
632 }
Robert Shih895fba92019-07-16 16:29:44 -0700633 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800634 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
635 }
636 } else {
637 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
638 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
639 hidl_vec<SubSample> hidlSubSamples;
640 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
641
642 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
643 encryptedBuffer->fillSourceBuffer(&srcBuffer);
644
645 DestinationBuffer dstBuffer;
646 if (secure) {
647 dstBuffer.type = BufferType::NATIVE_HANDLE;
648 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
649 } else {
650 dstBuffer.type = BufferType::SHARED_MEMORY;
651 dstBuffer.nonsecureMemory = srcBuffer;
652 }
653
654 CasStatus status = CasStatus::OK;
655 hidl_string detailedError;
656 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
657
658 if (key != nullptr) {
659 sctrl = (ScramblingControl)key[0];
660 // Adjust for the PES offset
661 codecDataOffset = key[2] | (key[3] << 8);
662 }
663
664 auto returnVoid = mDescrambler->descramble(
665 sctrl,
666 hidlSubSamples,
667 srcBuffer,
668 0,
669 dstBuffer,
670 0,
671 [&status, &result, &detailedError] (
672 CasStatus _status, uint32_t _bytesWritten,
673 const hidl_string& _detailedError) {
674 status = _status;
675 result = (ssize_t)_bytesWritten;
676 detailedError = _detailedError;
677 });
678
679 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
680 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
681 mName, returnVoid.description().c_str(), status, result);
682 return UNKNOWN_ERROR;
683 }
684
685 if (result < codecDataOffset) {
686 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
687 return BAD_VALUE;
688 }
689
690 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
691
692 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
693 encryptedBuffer->copyDecryptedContentFromMemory(result);
694 }
695 }
696
697 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700698
699 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800700}
701
702void CCodecBufferChannel::feedInputBufferIfAvailable() {
703 QueueGuard guard(mSync);
704 if (!guard.isRunning()) {
705 ALOGV("[%s] We're not running --- no input buffer reported", mName);
706 return;
707 }
708 feedInputBufferIfAvailableInternal();
709}
710
711void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900712 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800713 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700714 }
715 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700716 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700717 if (!output->buffers ||
718 output->buffers->hasPending() ||
Wonsik Kim0487b782020-10-28 11:45:50 -0700719 output->buffers->numActiveSlots() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800720 return;
721 }
722 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700723 size_t numActiveSlots = 0;
724 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800725 sp<MediaCodecBuffer> inBuffer;
726 size_t index;
727 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700728 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700729 numActiveSlots = input->buffers->numActiveSlots();
730 if (numActiveSlots >= input->numSlots) {
731 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800732 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700733 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800734 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800735 break;
736 }
737 }
738 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
739 mCallback->onInputBufferAvailable(index, inBuffer);
740 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700741 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800742}
743
744status_t CCodecBufferChannel::renderOutputBuffer(
745 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800746 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800747 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800748 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800749 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700750 Mutexed<Output>::Locked output(mOutput);
751 if (output->buffers) {
752 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800753 }
754 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800755 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
756 // set to true.
757 sendOutputBuffers();
758 // input buffer feeding may have been gated by pending output buffers
759 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800760 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800761 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700762 std::call_once(mRenderWarningFlag, [this] {
763 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
764 "timestamp or render=true with non-video buffers. Apps should "
765 "call releaseOutputBuffer() with render=false for those.",
766 mName);
767 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800768 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800769 return INVALID_OPERATION;
770 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800771
772#if 0
773 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
774 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
775 for (const std::shared_ptr<const C2Info> &info : infoParams) {
776 AString res;
777 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
778 if (ix) res.append(", ");
779 res.append(*((int32_t*)info.get() + (ix / 4)));
780 }
781 ALOGV(" [%s]", res.c_str());
782 }
783#endif
784 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
785 std::static_pointer_cast<const C2StreamRotationInfo::output>(
786 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
787 bool flip = rotation && (rotation->flip & 1);
788 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900789
790 {
791 Mutexed<OutputSurface>::Locked output(mOutputSurface);
792 if (output->surface == nullptr) {
793 ALOGI("[%s] cannot render buffer without surface", mName);
794 return OK;
795 }
796 int64_t frameIndex;
797 buffer->meta()->findInt64("frameIndex", &frameIndex);
798 if (output->rotation.count(frameIndex) != 0) {
799 auto it = output->rotation.find(frameIndex);
800 quarters = (it->second / 90) & 3;
801 output->rotation.erase(it);
802 }
803 }
804
Pawin Vongmasa36653902018-11-15 00:10:25 -0800805 uint32_t transform = 0;
806 switch (quarters) {
807 case 0: // no rotation
808 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
809 break;
810 case 1: // 90 degrees counter-clockwise
811 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
812 : HAL_TRANSFORM_ROT_270;
813 break;
814 case 2: // 180 degrees
815 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
816 break;
817 case 3: // 90 degrees clockwise
818 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
819 : HAL_TRANSFORM_ROT_90;
820 break;
821 }
822
823 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
824 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
825 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
826 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
827 if (surfaceScaling) {
828 videoScalingMode = surfaceScaling->value;
829 }
830
831 // Use dataspace from format as it has the default aspects already applied
832 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
833 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
834
835 // HDR static info
836 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
837 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
838 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
839
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800840 // HDR10 plus info
841 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
842 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
843 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800844 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
845 hdr10PlusInfo.reset();
846 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800847
Wonsik Kima79c5522022-01-18 16:29:24 -0800848 // HDR dynamic info
849 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
850 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
851 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
852 // TODO: make this sticky & enable unset
853 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
854 hdrDynamicInfo.reset();
855 }
856
857 if (hdr10PlusInfo) {
858 // C2StreamHdr10PlusInfo is deprecated; components should use
859 // C2StreamHdrDynamicMetadataInfo
860 // TODO: #metric
861 if (hdrDynamicInfo) {
862 // It is unexpected that C2StreamHdr10PlusInfo and
863 // C2StreamHdrDynamicMetadataInfo is both present.
864 // C2StreamHdrDynamicMetadataInfo takes priority.
865 // TODO: #metric
866 } else {
867 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
868 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
869 hdr10PlusInfo->flexCount(),
870 0u,
871 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
872 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
873 hdrDynamicInfo = info;
874 }
875 }
876
Pawin Vongmasa36653902018-11-15 00:10:25 -0800877 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
878 if (blocks.size() != 1u) {
879 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
880 return UNKNOWN_ERROR;
881 }
882 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700883 C2Fence c2fence = block.fence();
884 sp<Fence> fence = Fence::NO_FENCE;
885 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
886 // Once C2Fence::type() is added, check the exact C2Fence type
887 if (c2fence.isHW()) {
888 int fenceFd = c2fence.fd();
889 fence = sp<Fence>::make(fenceFd);
890 if (!fence) {
891 ALOGE("[%s] Failed to allocate a fence", mName);
892 close(fenceFd);
893 return NO_MEMORY;
894 }
895 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800896
897 // TODO: revisit this after C2Fence implementation.
898 android::IGraphicBufferProducer::QueueBufferInput qbi(
899 timestampNs,
900 false, // droppable
901 dataSpace,
902 Rect(blocks.front().crop().left,
903 blocks.front().crop().top,
904 blocks.front().crop().right(),
905 blocks.front().crop().bottom()),
906 videoScalingMode,
907 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700908 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800909 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800910 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800911 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800912 // If mastering max and min luminance fields are 0, do not use them.
913 // It indicates the value may not be present in the stream.
914 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
915 hdrStaticInfo->mastering.minLuminance > 0.0f) {
916 struct android_smpte2086_metadata smpte2086_meta = {
917 .displayPrimaryRed = {
918 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
919 },
920 .displayPrimaryGreen = {
921 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
922 },
923 .displayPrimaryBlue = {
924 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
925 },
926 .whitePoint = {
927 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
928 },
929 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
930 .minLuminance = hdrStaticInfo->mastering.minLuminance,
931 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800932 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800933 hdr.smpte2086 = smpte2086_meta;
934 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700935 // If the content light level fields are 0, do not use them, it
936 // indicates the value may not be present in the stream.
937 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
938 struct android_cta861_3_metadata cta861_meta = {
939 .maxContentLightLevel = hdrStaticInfo->maxCll,
940 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
941 };
942 hdr.validTypes |= HdrMetadata::CTA861_3;
943 hdr.cta8613 = cta861_meta;
944 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900945
946 // does not have valid info
947 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
948 hdrStaticInfo.reset();
949 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800950 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800951 if (hdrDynamicInfo
952 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800953 hdr.validTypes |= HdrMetadata::HDR10PLUS;
954 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800955 hdrDynamicInfo->m.data,
956 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800957 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800958 qbi.setHdrMetadata(hdr);
Wonsik Kima79c5522022-01-18 16:29:24 -0800959
960 SetHdrMetadataToGralloc4Handle(hdrStaticInfo, hdrDynamicInfo, block.handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800961 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800962 // we don't have dirty regions
963 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800964 android::IGraphicBufferProducer::QueueBufferOutput qbo;
965 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
966 if (result != OK) {
967 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800968 if (result == NO_INIT) {
969 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
970 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800971 return result;
972 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800973
974 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
975 ALOGD("[%s] queue buffer successful", mName);
976 } else {
977 ALOGV("[%s] queue buffer successful", mName);
978 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800979
980 int64_t mediaTimeUs = 0;
981 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
982 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
983
984 return OK;
985}
986
987status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
988 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
989 bool released = false;
990 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700991 Mutexed<Input>::Locked input(mInput);
992 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800993 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800994 }
995 }
996 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700997 Mutexed<Output>::Locked output(mOutput);
998 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800999 released = true;
1000 }
1001 }
1002 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001003 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001004 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001005 } else {
1006 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1007 }
1008 return OK;
1009}
1010
1011void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1012 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001013 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001014
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001015 if (!input->buffers->isArrayMode()) {
1016 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001017 }
1018
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001019 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001020}
1021
1022void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1023 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001024 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001025
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001026 if (!output->buffers->isArrayMode()) {
1027 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001028 }
1029
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001030 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001031}
1032
1033status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001034 const sp<AMessage> &inputFormat,
1035 const sp<AMessage> &outputFormat,
1036 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001037 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1038 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001039 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001040 C2PortReorderBufferDepthTuning::output reorderDepth;
1041 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001042 C2PortActualDelayTuning::input inputDelay(0);
1043 C2PortActualDelayTuning::output outputDelay(0);
1044 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001045 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001046
Pawin Vongmasa36653902018-11-15 00:10:25 -08001047 c2_status_t err = mComponent->query(
1048 {
1049 &iStreamFormat,
1050 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001051 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001052 &reorderDepth,
1053 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001054 &inputDelay,
1055 &pipelineDelay,
1056 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001057 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001058 },
1059 {},
1060 C2_DONT_BLOCK,
1061 nullptr);
1062 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001063 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001064 return UNKNOWN_ERROR;
1065 }
1066 } else if (err != C2_OK) {
1067 return UNKNOWN_ERROR;
1068 }
1069
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001070 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1071 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1072 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1073
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001074 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1075 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001076
Pawin Vongmasa36653902018-11-15 00:10:25 -08001077 // TODO: get this from input format
1078 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1079
Sungtak Lee04b30352020-07-27 13:57:25 -07001080 // secure mode is a static parameter (shall not change in the executing state)
1081 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1082
Pawin Vongmasa36653902018-11-15 00:10:25 -08001083 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001084 int poolMask = GetCodec2PoolMask();
1085 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001086
1087 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001088 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001089 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001090 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1091 API_REFLECTION |
1092 API_VALUES |
1093 API_CURRENT_VALUES |
1094 API_DEPENDENCY |
1095 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001096 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1097 C2StreamSampleRateInfo::input sampleRate(0u);
1098 C2StreamChannelCountInfo::input channelCount(0u);
1099 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001100 std::shared_ptr<C2BlockPool> pool;
1101 {
1102 Mutexed<BlockPools>::Locked pools(mBlockPools);
1103
1104 // set default allocator ID.
1105 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001106 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001107
1108 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1109 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1110 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001111 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001112 std::vector<C2Param *> stackParams({&featuresSetting});
1113 if (audioEncoder) {
1114 stackParams.push_back(&encoderFrameSize);
1115 stackParams.push_back(&sampleRate);
1116 stackParams.push_back(&channelCount);
1117 stackParams.push_back(&pcmEncoding);
1118 } else {
1119 encoderFrameSize.invalidate();
1120 sampleRate.invalidate();
1121 channelCount.invalidate();
1122 pcmEncoding.invalidate();
1123 }
1124 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001125 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1126 C2_DONT_BLOCK,
1127 &params);
1128 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1129 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1130 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001131 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001132 C2PortAllocatorsTuning::input *inputAllocators =
1133 C2PortAllocatorsTuning::input::From(params[0].get());
1134 if (inputAllocators && inputAllocators->flexCount() > 0) {
1135 std::shared_ptr<C2Allocator> allocator;
1136 // verify allocator IDs and resolve default allocator
1137 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1138 if (allocator) {
1139 pools->inputAllocatorId = allocator->getId();
1140 } else {
1141 ALOGD("[%s] component requested invalid input allocator ID %u",
1142 mName, inputAllocators->m.values[0]);
1143 }
1144 }
1145 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001146 if (featuresSetting) {
1147 apiFeatures = featuresSetting.value;
1148 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001149
1150 // TODO: use C2Component wrapper to associate this pool with ourselves
1151 if ((poolMask >> pools->inputAllocatorId) & 1) {
1152 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1153 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1154 mName, pools->inputAllocatorId,
1155 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1156 asString(err), err);
1157 } else {
1158 err = C2_NOT_FOUND;
1159 }
1160 if (err != C2_OK) {
1161 C2BlockPool::local_id_t inputPoolId =
1162 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1163 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1164 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1165 mName, (unsigned long long)inputPoolId,
1166 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1167 asString(err), err);
1168 if (err != C2_OK) {
1169 return NO_MEMORY;
1170 }
1171 }
1172 pools->inputPool = pool;
1173 }
1174
Wonsik Kim51051262018-11-28 13:59:05 -08001175 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001176 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001177 input->inputDelay = inputDelayValue;
1178 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001179 input->numSlots = numInputSlots;
1180 input->extraBuffers.flush();
1181 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001182 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001183 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1184 input->frameReassembler.init(
1185 pool,
1186 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1187 encoderFrameSize.value,
1188 sampleRate.value,
1189 channelCount.value,
1190 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1191 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001192 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1193 // For encrypted content, framework decrypts source buffer (ashmem) into
1194 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001195 if (!buffersBoundToCodec
1196 && !input->frameReassembler
1197 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001198 input->buffers.reset(new SlotInputBuffers(mName));
1199 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001200 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001201 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001202 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001203 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001204 // This is to ensure buffers do not get released prematurely.
1205 // TODO: handle this without going into array mode
1206 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001207 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001208 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001209 }
1210 } else {
1211 if (hasCryptoOrDescrambler()) {
1212 int32_t capacity = kLinearBufferSize;
1213 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1214 if ((size_t)capacity > kMaxLinearBufferSize) {
1215 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1216 capacity = kMaxLinearBufferSize;
1217 }
1218 if (mDealer == nullptr) {
1219 mDealer = new MemoryDealer(
1220 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001221 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001222 "EncryptedLinearInputBuffers");
1223 mDecryptDestination = mDealer->allocate((size_t)capacity);
1224 }
1225 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001226 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1227 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001228 } else {
1229 mHeapSeqNum = -1;
1230 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001231 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001232 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001233 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001234 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001235 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001236 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001237 }
1238 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001239 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001240
1241 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001242 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001243 } else {
1244 // TODO: error
1245 }
Wonsik Kim51051262018-11-28 13:59:05 -08001246
1247 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001248 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001249 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001250 }
1251
1252 if (outputFormat != nullptr) {
1253 sp<IGraphicBufferProducer> outputSurface;
1254 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001255 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001256 {
1257 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001258 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001259 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001260 outputSurface = output->surface ?
1261 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001262 if (outputSurface) {
1263 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1264 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001265 outputGeneration = output->generation;
1266 }
1267
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001268 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001269 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001270 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001271
1272 {
1273 Mutexed<BlockPools>::Locked pools(mBlockPools);
1274
David Stevensc3fbb282021-01-18 18:11:20 +09001275 prevOutputPoolId = pools->outputPoolId;
1276
Pawin Vongmasa36653902018-11-15 00:10:25 -08001277 // set default allocator ID.
1278 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001279 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001280
1281 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1282 // unsuccessful.
1283 std::vector<std::unique_ptr<C2Param>> params;
1284 err = mComponent->query({ },
1285 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1286 C2_DONT_BLOCK,
1287 &params);
1288 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1289 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1290 mName, params.size(), asString(err), err);
1291 } else if (err == C2_OK && params.size() == 1) {
1292 C2PortAllocatorsTuning::output *outputAllocators =
1293 C2PortAllocatorsTuning::output::From(params[0].get());
1294 if (outputAllocators && outputAllocators->flexCount() > 0) {
1295 std::shared_ptr<C2Allocator> allocator;
1296 // verify allocator IDs and resolve default allocator
1297 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1298 if (allocator) {
1299 pools->outputAllocatorId = allocator->getId();
1300 } else {
1301 ALOGD("[%s] component requested invalid output allocator ID %u",
1302 mName, outputAllocators->m.values[0]);
1303 }
1304 }
1305 }
1306
1307 // use bufferqueue if outputting to a surface.
1308 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1309 // if unsuccessful.
1310 if (outputSurface) {
1311 params.clear();
1312 err = mComponent->query({ },
1313 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1314 C2_DONT_BLOCK,
1315 &params);
1316 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1317 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1318 mName, params.size(), asString(err), err);
1319 } else if (err == C2_OK && params.size() == 1) {
1320 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1321 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1322 if (surfaceAllocator) {
1323 std::shared_ptr<C2Allocator> allocator;
1324 // verify allocator IDs and resolve default allocator
1325 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1326 if (allocator) {
1327 pools->outputAllocatorId = allocator->getId();
1328 } else {
1329 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1330 mName, surfaceAllocator->value);
1331 err = C2_BAD_VALUE;
1332 }
1333 }
1334 }
1335 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1336 && err != C2_OK
1337 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1338 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1339 }
1340 }
1341
1342 if ((poolMask >> pools->outputAllocatorId) & 1) {
1343 err = mComponent->createBlockPool(
1344 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1345 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1346 mName, pools->outputAllocatorId,
1347 (unsigned long long)pools->outputPoolId,
1348 asString(err));
1349 } else {
1350 err = C2_NOT_FOUND;
1351 }
1352 if (err != C2_OK) {
1353 // use basic pool instead
1354 pools->outputPoolId =
1355 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1356 }
1357
1358 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1359 // component.
1360 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1361 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1362
1363 std::vector<std::unique_ptr<C2SettingResult>> failures;
1364 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1365 ALOGD("[%s] Configured output block pool ids %llu => %s",
1366 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1367 outputPoolId_ = pools->outputPoolId;
1368 }
1369
David Stevensc3fbb282021-01-18 18:11:20 +09001370 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1371 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1372 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1373 if (err != C2_OK) {
1374 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1375 (unsigned long long) prevOutputPoolId, asString(err), err);
1376 }
1377 }
1378
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001379 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001380 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001381 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001382 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001383 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001384 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001385 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001386 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001387 }
1388 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001389 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001390 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001391 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001392
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001393 output->buffers->clearStash();
1394 if (reorderDepth) {
1395 output->buffers->setReorderDepth(reorderDepth.value);
1396 }
1397 if (reorderKey) {
1398 output->buffers->setReorderKey(reorderKey.value);
1399 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001400
1401 // Try to set output surface to created block pool if given.
1402 if (outputSurface) {
1403 mComponent->setOutputSurface(
1404 outputPoolId_,
1405 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001406 outputGeneration,
1407 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001408 } else {
1409 // configure CPU read consumer usage
1410 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1411 std::vector<std::unique_ptr<C2SettingResult>> failures;
1412 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1413 // do not print error message for now as most components may not yet
1414 // support this setting
1415 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1416 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001417 }
1418
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001419 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001420 if (buffersBoundToCodec) {
1421 // WORKAROUND: if we're using early CSD workaround we convert to
1422 // array mode, to appease apps assuming the output
1423 // buffers to be of the same size.
1424 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1425 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001426
1427 int32_t channelCount;
1428 int32_t sampleRate;
1429 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1430 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1431 int32_t delay = 0;
1432 int32_t padding = 0;;
1433 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1434 delay = 0;
1435 }
1436 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1437 padding = 0;
1438 }
1439 if (delay || padding) {
1440 // We need write access to the buffers, and we're already in
1441 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001442 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001443 }
1444 }
1445 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001446
1447 int32_t tunneled = 0;
1448 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1449 tunneled = 0;
1450 }
1451 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001452 }
1453
1454 // Set up pipeline control. This has to be done after mInputBuffers and
1455 // mOutputBuffers are initialized to make sure that lingering callbacks
1456 // about buffers from the previous generation do not interfere with the
1457 // newly initialized pipeline capacity.
1458
Wonsik Kim62545252021-01-20 11:25:41 -08001459 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001460 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001461 watcher->inputDelay(inputDelayValue)
1462 .pipelineDelay(pipelineDelayValue)
1463 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001464 .smoothnessFactor(kSmoothnessFactor);
1465 watcher->flush();
1466 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001467
1468 mInputMetEos = false;
1469 mSync.start();
1470 return OK;
1471}
1472
1473status_t CCodecBufferChannel::requestInitialInputBuffers() {
1474 if (mInputSurface) {
1475 return OK;
1476 }
1477
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001478 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001479 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1480 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1481 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001482 return UNKNOWN_ERROR;
1483 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001484 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001485
1486 struct ClientInputBuffer {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001487 size_t index;
1488 sp<MediaCodecBuffer> buffer;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001489 size_t capacity;
1490 };
1491 std::list<ClientInputBuffer> clientInputBuffers;
1492
1493 {
1494 Mutexed<Input>::Locked input(mInput);
1495 while (clientInputBuffers.size() < numInputSlots) {
1496 ClientInputBuffer clientInputBuffer;
1497 if (!input->buffers->requestNewBuffer(&clientInputBuffer.index,
1498 &clientInputBuffer.buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001499 break;
1500 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001501 clientInputBuffer.capacity = clientInputBuffer.buffer->capacity();
1502 clientInputBuffers.emplace_back(std::move(clientInputBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001503 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001504 }
1505 if (clientInputBuffers.empty()) {
1506 ALOGW("[%s] start: cannot allocate memory at all", mName);
1507 return NO_MEMORY;
1508 } else if (clientInputBuffers.size() < numInputSlots) {
1509 ALOGD("[%s] start: cannot allocate memory for all slots, "
1510 "only %zu buffers allocated",
1511 mName, clientInputBuffers.size());
1512 } else {
1513 ALOGV("[%s] %zu initial input buffers available",
1514 mName, clientInputBuffers.size());
1515 }
1516 // Sort input buffers by their capacities in increasing order.
1517 clientInputBuffers.sort(
1518 [](const ClientInputBuffer& a, const ClientInputBuffer& b) {
1519 return a.capacity < b.capacity;
1520 });
1521
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001522 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1523 mFlushedConfigs.lock()->swap(flushedConfigs);
1524 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001525 {
1526 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1527 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1528 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1529 watcher->onWorkQueued(
1530 work->input.ordinal.frameIndex.peeku(),
1531 std::vector(work->input.buffers),
1532 now);
1533 }
1534 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001535 err = mComponent->queue(&flushedConfigs);
1536 if (err != C2_OK) {
1537 ALOGW("[%s] Error while queueing a flushed config", mName);
1538 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001539 }
1540 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001541 if (oStreamFormat.value == C2BufferData::LINEAR &&
1542 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
1543 sp<MediaCodecBuffer> buffer = clientInputBuffers.front().buffer;
1544 // WORKAROUND: Some apps expect CSD available without queueing
1545 // any input. Queue an empty buffer to get the CSD.
1546 buffer->setRange(0, 0);
1547 buffer->meta()->clear();
1548 buffer->meta()->setInt64("timeUs", 0);
1549 if (queueInputBufferInternal(buffer) != OK) {
1550 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1551 mName);
1552 return UNKNOWN_ERROR;
1553 }
1554 clientInputBuffers.pop_front();
1555 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001556
1557 for (const ClientInputBuffer& clientInputBuffer: clientInputBuffers) {
1558 mCallback->onInputBufferAvailable(
1559 clientInputBuffer.index,
1560 clientInputBuffer.buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001561 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001562
Pawin Vongmasa36653902018-11-15 00:10:25 -08001563 return OK;
1564}
1565
1566void CCodecBufferChannel::stop() {
1567 mSync.stop();
1568 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001569}
1570
Wonsik Kim936a89c2020-05-08 16:07:50 -07001571void CCodecBufferChannel::reset() {
1572 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001573 if (mInputSurface != nullptr) {
1574 mInputSurface.reset();
1575 }
1576 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001577 {
1578 Mutexed<Input>::Locked input(mInput);
1579 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001580 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001581 }
1582 {
1583 Mutexed<Output>::Locked output(mOutput);
1584 output->buffers.reset();
1585 }
Sungtak Leec7da7a02022-05-05 08:45:33 +00001586 if (mOutputSurface.lock()->surface) {
1587 C2BlockPool::local_id_t outputPoolId;
1588 {
1589 Mutexed<BlockPools>::Locked pools(mBlockPools);
1590 outputPoolId = pools->outputPoolId;
1591 }
1592 mComponent->stopUsingOutputSurface(outputPoolId);
1593 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001594}
1595
1596void CCodecBufferChannel::release() {
1597 mComponent.reset();
1598 mInputAllocator.reset();
1599 mOutputSurface.lock()->surface.clear();
1600 {
1601 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1602 blockPools->inputPool.reset();
1603 blockPools->outputPoolIntf.reset();
1604 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001605 setCrypto(nullptr);
1606 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001607}
1608
Pawin Vongmasa36653902018-11-15 00:10:25 -08001609void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1610 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001611 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001612 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001613 {
1614 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1615 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1616 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1617 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1618 watcher->onWorkDone(frameIndex);
1619 continue;
1620 }
1621 if (work->input.buffers.empty()
1622 || work->input.buffers.front() == nullptr
1623 || work->input.buffers.front()->data().linearBlocks().empty()) {
1624 ALOGD("[%s] no linear codec config data found", mName);
1625 watcher->onWorkDone(frameIndex);
1626 continue;
1627 }
1628 std::unique_ptr<C2Work> copy(new C2Work);
1629 copy->input.flags = C2FrameData::flags_t(
1630 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1631 copy->input.ordinal = work->input.ordinal;
1632 copy->input.ordinal.frameIndex = mFrameIndex++;
1633 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1634 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1635 }
1636 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1637 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1638 }
1639 copy->input.infoBuffers.insert(
1640 copy->input.infoBuffers.begin(),
1641 work->input.infoBuffers.begin(),
1642 work->input.infoBuffers.end());
1643 copy->worklets.emplace_back(new C2Worklet);
1644 configs.push_back(std::move(copy));
1645 watcher->onWorkDone(frameIndex);
1646 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001647 }
1648 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001649 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001650 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001651 Mutexed<Input>::Locked input(mInput);
1652 input->buffers->flush();
1653 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001654 }
1655 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001656 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001657 if (output->buffers) {
1658 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001659 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001660 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001661 }
1662}
1663
1664void CCodecBufferChannel::onWorkDone(
1665 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001666 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001667 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001668 feedInputBufferIfAvailable();
1669 }
1670}
1671
1672void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001673 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001674 if (mInputSurface) {
1675 return;
1676 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001677 std::shared_ptr<C2Buffer> buffer =
1678 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001679 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001680 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001681 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001682 if (input->lastFlushIndex >= frameIndex) {
1683 ALOGD("[%s] Ignoring stale input buffer done callback: "
1684 "last flush index = %lld, frameIndex = %lld",
1685 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1686 } else {
1687 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1688 if (!newInputSlotAvailable) {
1689 (void)input->extraBuffers.expireComponentBuffer(buffer);
1690 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001691 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001692 }
1693 if (newInputSlotAvailable) {
1694 feedInputBufferIfAvailable();
1695 }
1696}
1697
1698bool CCodecBufferChannel::handleWork(
1699 std::unique_ptr<C2Work> work,
1700 const sp<AMessage> &outputFormat,
1701 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001702 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001703 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001704 if (!output->buffers) {
1705 return false;
1706 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001707 }
1708
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001709 // Whether the output buffer should be reported to the client or not.
1710 bool notifyClient = false;
1711
1712 if (work->result == C2_OK){
1713 notifyClient = true;
1714 } else if (work->result == C2_NOT_FOUND) {
1715 ALOGD("[%s] flushed work; ignored.", mName);
1716 } else {
1717 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1718 // the config update.
1719 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1720 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1721 return false;
1722 }
1723
1724 if ((work->input.ordinal.frameIndex -
1725 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001726 // Discard frames from previous generation.
1727 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001728 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001729 }
1730
Wonsik Kim524b0582019-03-12 11:28:57 -07001731 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001732 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001733 || !(work->worklets.front()->output.flags &
1734 C2FrameData::FLAG_INCOMPLETE))) {
1735 mPipelineWatcher.lock()->onWorkDone(
1736 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001737 }
1738
1739 // NOTE: MediaCodec usage supposedly have only one worklet
1740 if (work->worklets.size() != 1u) {
1741 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1742 mName, work->worklets.size());
1743 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1744 return false;
1745 }
1746
1747 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1748
1749 std::shared_ptr<C2Buffer> buffer;
1750 // NOTE: MediaCodec usage supposedly have only one output stream.
1751 if (worklet->output.buffers.size() > 1u) {
1752 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1753 mName, worklet->output.buffers.size());
1754 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1755 return false;
1756 } else if (worklet->output.buffers.size() == 1u) {
1757 buffer = worklet->output.buffers[0];
1758 if (!buffer) {
1759 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1760 }
1761 }
1762
Wonsik Kim3dedf682021-05-03 10:57:09 -07001763 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1764 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001765 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001766 while (!worklet->output.configUpdate.empty()) {
1767 std::unique_ptr<C2Param> param;
1768 worklet->output.configUpdate.back().swap(param);
1769 worklet->output.configUpdate.pop_back();
1770 switch (param->coreIndex().coreIndex()) {
1771 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1772 C2PortReorderBufferDepthTuning::output reorderDepth;
1773 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001774 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1775 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001776 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001777 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001778 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001779 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1780 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001781 }
1782 break;
1783 }
1784 case C2PortReorderKeySetting::CORE_INDEX: {
1785 C2PortReorderKeySetting::output reorderKey;
1786 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001787 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001788 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1789 mName, reorderKey.value);
1790 } else {
1791 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1792 }
1793 break;
1794 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001795 case C2PortActualDelayTuning::CORE_INDEX: {
1796 if (param->isGlobal()) {
1797 C2ActualPipelineDelayTuning pipelineDelay;
1798 if (pipelineDelay.updateFrom(*param)) {
1799 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1800 mName, pipelineDelay.value);
1801 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001802 (void)mPipelineWatcher.lock()->pipelineDelay(
1803 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001804 }
1805 }
1806 if (param->forInput()) {
1807 C2PortActualDelayTuning::input inputDelay;
1808 if (inputDelay.updateFrom(*param)) {
1809 ALOGV("[%s] onWorkDone: updating input delay %u",
1810 mName, inputDelay.value);
1811 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001812 (void)mPipelineWatcher.lock()->inputDelay(
1813 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001814 }
1815 }
1816 if (param->forOutput()) {
1817 C2PortActualDelayTuning::output outputDelay;
1818 if (outputDelay.updateFrom(*param)) {
1819 ALOGV("[%s] onWorkDone: updating output delay %u",
1820 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001821 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001822 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001823 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001824
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001825 }
1826 }
1827 break;
1828 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001829 case C2PortTunnelSystemTime::CORE_INDEX: {
1830 C2PortTunnelSystemTime::output frameRenderTime;
1831 if (frameRenderTime.updateFrom(*param)) {
1832 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1833 mName, (long long)frameRenderTime.value,
1834 (long long)worklet->output.ordinal.timestamp.peekll());
1835 mCCodecCallback->onOutputFramesRendered(
1836 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1837 }
1838 break;
1839 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001840 case C2StreamTunnelHoldRender::CORE_INDEX: {
1841 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1842 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1843 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1844 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1845 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1846 mCCodecCallback->onFirstTunnelFrameReady();
1847 break;
1848 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001849 default:
1850 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1851 mName, param->index());
1852 break;
1853 }
1854 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001855 if (newInputDelay || newPipelineDelay) {
1856 Mutexed<Input>::Locked input(mInput);
1857 size_t newNumSlots =
1858 newInputDelay.value_or(input->inputDelay) +
1859 newPipelineDelay.value_or(input->pipelineDelay) +
1860 kSmoothnessFactor;
1861 if (input->buffers->isArrayMode()) {
1862 if (input->numSlots >= newNumSlots) {
1863 input->numExtraSlots = 0;
1864 } else {
1865 input->numExtraSlots = newNumSlots - input->numSlots;
1866 }
1867 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1868 mName, input->numExtraSlots);
1869 } else {
1870 input->numSlots = newNumSlots;
1871 }
1872 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001873 size_t numOutputSlots = 0;
1874 uint32_t reorderDepth = 0;
1875 bool outputBuffersChanged = false;
1876 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
1877 Mutexed<Output>::Locked output(mOutput);
1878 if (!output->buffers) {
1879 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001880 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001881 numOutputSlots = output->numSlots;
1882 if (newReorderKey) {
1883 output->buffers->setReorderKey(newReorderKey.value());
1884 }
1885 if (newReorderDepth) {
1886 output->buffers->setReorderDepth(newReorderDepth.value());
1887 }
1888 reorderDepth = output->buffers->getReorderDepth();
1889 if (newOutputDelay) {
1890 output->outputDelay = newOutputDelay.value();
1891 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
1892 if (output->numSlots < numOutputSlots) {
1893 output->numSlots = numOutputSlots;
1894 if (output->buffers->isArrayMode()) {
1895 OutputBuffersArray *array =
1896 (OutputBuffersArray *)output->buffers.get();
1897 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1898 mName, numOutputSlots);
1899 array->grow(numOutputSlots);
1900 outputBuffersChanged = true;
1901 }
1902 }
1903 }
1904 numOutputSlots = output->numSlots;
1905 }
1906 if (outputBuffersChanged) {
1907 mCCodecCallback->onOutputBuffersChanged();
1908 }
1909 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07001910 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07001911 {
1912 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1913 maxDequeueCount = output->maxDequeueBuffers =
1914 numOutputSlots + reorderDepth + kRenderingDepth;
1915 if (output->surface) {
1916 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1917 }
1918 }
1919 if (maxDequeueCount > 0) {
1920 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001921 }
1922 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001923
Pawin Vongmasa36653902018-11-15 00:10:25 -08001924 int32_t flags = 0;
1925 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07001926 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001927 ALOGV("[%s] onWorkDone: output EOS", mName);
1928 }
1929
Pawin Vongmasa36653902018-11-15 00:10:25 -08001930 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1931 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1932 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1933 // shall correspond to the client input timesamp (in customOrdinal). By using the
1934 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1935 // produces multiple output.
1936 c2_cntr64_t timestamp =
1937 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1938 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001939 if (mInputSurface != nullptr) {
1940 // When using input surface we need to restore the original input timestamp.
1941 timestamp = work->input.ordinal.customOrdinal;
1942 }
My Name6bd9a7d2022-03-25 12:37:58 -07001943 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
1944 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001945 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1946 mName,
1947 work->input.ordinal.customOrdinal.peekll(),
1948 work->input.ordinal.timestamp.peekll(),
1949 worklet->output.ordinal.timestamp.peekll(),
1950 timestamp.peekll());
1951
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001952 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001953 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001954 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001955 if (output->buffers && outputFormat) {
1956 output->buffers->updateSkipCutBuffer(outputFormat);
1957 output->buffers->setFormat(outputFormat);
1958 }
1959 if (!notifyClient) {
1960 return false;
1961 }
1962 size_t index;
1963 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07001964 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001965 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07001966 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001967 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1968
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001969 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001970 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001971 } else {
1972 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001973 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001974 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001975 return false;
1976 }
1977 }
1978
Wonsik Kimec585c32021-10-01 01:11:00 -07001979 bool drop = false;
1980 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
1981 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
1982 drop = true;
1983 }
1984
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001985 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07001986 if (mTunneled && drop && outputFormat) {
1987 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
1988 mName, work->input.ordinal.frameIndex.peekull());
1989 } else {
1990 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1991 mName, work->input.ordinal.frameIndex.peekull());
1992 notifyClient = false;
1993 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001994 }
1995
1996 if (buffer) {
1997 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1998 // TODO: properly translate these to metadata
1999 switch (info->coreIndex().coreIndex()) {
2000 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002001 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002002 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002003 }
2004 break;
2005 default:
2006 break;
2007 }
2008 }
2009 }
2010
2011 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002012 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002013 if (!output->buffers) {
2014 return false;
2015 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002016 output->buffers->pushToStash(
2017 buffer,
2018 notifyClient,
2019 timestamp.peek(),
2020 flags,
2021 outputFormat,
2022 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002023 }
2024 sendOutputBuffers();
2025 return true;
2026}
2027
2028void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002029 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002030 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002031 sp<MediaCodecBuffer> outBuffer;
2032 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002033
2034 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002035 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002036 if (!output->buffers) {
2037 return;
2038 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002039 action = output->buffers->popFromStashAndRegister(
2040 &c2Buffer, &index, &outBuffer);
2041 switch (action) {
2042 case OutputBuffers::SKIP:
2043 return;
2044 case OutputBuffers::DISCARD:
2045 break;
2046 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00002047 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002048 mCallback->onOutputBufferAvailable(index, outBuffer);
2049 break;
2050 case OutputBuffers::REALLOCATE:
2051 if (!output->buffers->isArrayMode()) {
2052 output->buffers =
2053 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002054 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002055 static_cast<OutputBuffersArray*>(output->buffers.get())->
2056 realloc(c2Buffer);
2057 output.unlock();
2058 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002059 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002060 case OutputBuffers::RETRY:
2061 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2062 mName);
2063 return;
2064 default:
2065 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2066 "corrupted BufferAction value (%d) "
2067 "returned from popFromStashAndRegister.",
2068 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002069 return;
2070 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002071 }
2072}
2073
2074status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
2075 static std::atomic_uint32_t surfaceGeneration{0};
2076 uint32_t generation = (getpid() << 10) |
2077 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2078 & ((1 << 10) - 1));
2079
2080 sp<IGraphicBufferProducer> producer;
Sungtak Leedb14cba2021-04-10 00:50:23 -07002081 int maxDequeueCount = mOutputSurface.lock()->maxDequeueBuffers;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002082 if (newSurface) {
2083 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002084 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002085 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002086 producer = newSurface->getIGraphicBufferProducer();
2087 producer->setGenerationNumber(generation);
2088 } else {
2089 ALOGE("[%s] setting output surface to null", mName);
2090 return INVALID_OPERATION;
2091 }
2092
2093 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2094 C2BlockPool::local_id_t outputPoolId;
2095 {
2096 Mutexed<BlockPools>::Locked pools(mBlockPools);
2097 outputPoolId = pools->outputPoolId;
2098 outputPoolIntf = pools->outputPoolIntf;
2099 }
2100
2101 if (outputPoolIntf) {
2102 if (mComponent->setOutputSurface(
2103 outputPoolId,
2104 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002105 generation,
2106 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002107 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2108 return INVALID_OPERATION;
2109 }
2110 }
2111
2112 {
2113 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2114 output->surface = newSurface;
2115 output->generation = generation;
2116 }
2117
2118 return OK;
2119}
2120
Wonsik Kimab34ed62019-01-31 15:28:46 -08002121PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002122 // Otherwise, component may have stalled work due to input starvation up to
2123 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002124 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2125 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002126 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002127 size_t outputDelay = mOutput.lock()->outputDelay;
2128 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002129 Mutexed<Input>::Locked input(mInput);
2130 n = input->inputDelay + input->pipelineDelay + outputDelay;
2131 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002132 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002133}
2134
Pawin Vongmasa36653902018-11-15 00:10:25 -08002135void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2136 mMetaMode = mode;
2137}
2138
Wonsik Kim596187e2019-10-25 12:44:10 -07002139void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002140 if (mCrypto != nullptr) {
2141 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2142 mCrypto->unsetHeap(entry.second);
2143 }
2144 mHeapSeqNumMap.clear();
2145 if (mHeapSeqNum >= 0) {
2146 mCrypto->unsetHeap(mHeapSeqNum);
2147 mHeapSeqNum = -1;
2148 }
2149 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002150 mCrypto = crypto;
2151}
2152
2153void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2154 mDescrambler = descrambler;
2155}
2156
Pawin Vongmasa36653902018-11-15 00:10:25 -08002157status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2158 // C2_OK is always translated to OK.
2159 if (c2s == C2_OK) {
2160 return OK;
2161 }
2162
2163 // Operation-dependent translation
2164 // TODO: Add as necessary
2165 switch (c2op) {
2166 case C2_OPERATION_Component_start:
2167 switch (c2s) {
2168 case C2_NO_MEMORY:
2169 return NO_MEMORY;
2170 default:
2171 return UNKNOWN_ERROR;
2172 }
2173 default:
2174 break;
2175 }
2176
2177 // Backup operation-agnostic translation
2178 switch (c2s) {
2179 case C2_BAD_INDEX:
2180 return BAD_INDEX;
2181 case C2_BAD_VALUE:
2182 return BAD_VALUE;
2183 case C2_BLOCKING:
2184 return WOULD_BLOCK;
2185 case C2_DUPLICATE:
2186 return ALREADY_EXISTS;
2187 case C2_NO_INIT:
2188 return NO_INIT;
2189 case C2_NO_MEMORY:
2190 return NO_MEMORY;
2191 case C2_NOT_FOUND:
2192 return NAME_NOT_FOUND;
2193 case C2_TIMED_OUT:
2194 return TIMED_OUT;
2195 case C2_BAD_STATE:
2196 case C2_CANCELED:
2197 case C2_CANNOT_DO:
2198 case C2_CORRUPTED:
2199 case C2_OMITTED:
2200 case C2_REFUSED:
2201 return UNKNOWN_ERROR;
2202 default:
2203 return -static_cast<status_t>(c2s);
2204 }
2205}
2206
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +01002207status_t CCodecBufferChannel::pushBlankBufferToOutputSurface() {
2208 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2209 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(output->surface.get());
2210 if (nativeWindow == nullptr) {
2211 return INVALID_OPERATION;
2212 }
2213 return pushBlankBuffersToNativeWindow(nativeWindow.get());
2214}
2215
Pawin Vongmasa36653902018-11-15 00:10:25 -08002216} // namespace android