blob: f27cc21116c12d59bddc44f11f18c65c1036a5bd [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 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700435 if (size == 0) {
436 buffer->setRange(0, 0);
437 return OK;
438 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800439 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
440 std::shared_ptr<C2LinearBlock> block;
441 c2_status_t err = pool->fetchLinearBlock(
442 size,
443 secure ? kSecureUsage : kDefaultReadWriteUsage,
444 &block);
445 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700446 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
447 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800448 return NO_MEMORY;
449 }
450 if (!secure) {
451 ensureDecryptDestination(size);
452 }
453 ssize_t result = -1;
454 ssize_t codecDataOffset = 0;
455 if (mCrypto) {
456 AString errorDetailMsg;
457 int32_t heapSeqNum = getHeapSeqNum(memory);
458 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
459 hardware::drm::V1_0::DestinationBuffer dst;
460 if (secure) {
461 dst.type = DrmBufferType::NATIVE_HANDLE;
462 dst.secureMemory = hardware::hidl_handle(block->handle());
463 } else {
464 dst.type = DrmBufferType::SHARED_MEMORY;
465 IMemoryToSharedBuffer(
466 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
467 }
468 result = mCrypto->decrypt(
469 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
470 dst, &errorDetailMsg);
471 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700472 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800473 return result;
474 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800475 } else {
476 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
477 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
478 hidl_vec<SubSample> hidlSubSamples;
479 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
480
481 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
482 hardware::cas::native::V1_0::DestinationBuffer dst;
483 if (secure) {
484 dst.type = BufferType::NATIVE_HANDLE;
485 dst.secureMemory = hardware::hidl_handle(block->handle());
486 } else {
487 dst.type = BufferType::SHARED_MEMORY;
488 dst.nonsecureMemory = src;
489 }
490
491 CasStatus status = CasStatus::OK;
492 hidl_string detailedError;
493 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
494
495 if (key != nullptr) {
496 sctrl = (ScramblingControl)key[0];
497 // Adjust for the PES offset
498 codecDataOffset = key[2] | (key[3] << 8);
499 }
500
501 auto returnVoid = mDescrambler->descramble(
502 sctrl,
503 hidlSubSamples,
504 src,
505 0,
506 dst,
507 0,
508 [&status, &result, &detailedError] (
509 CasStatus _status, uint32_t _bytesWritten,
510 const hidl_string& _detailedError) {
511 status = _status;
512 result = (ssize_t)_bytesWritten;
513 detailedError = _detailedError;
514 });
515
516 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
517 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
518 mName, returnVoid.description().c_str(), status, result);
519 return UNKNOWN_ERROR;
520 }
521
522 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700523 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
524 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800525 return BAD_VALUE;
526 }
527 }
528 if (!secure) {
529 C2WriteView view = block->map().get();
530 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700531 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
532 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800533 return UNKNOWN_ERROR;
534 }
535 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700536 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
537 "(non-secure)",
538 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800539 return UNKNOWN_ERROR;
540 }
541 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
542 }
543 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
544 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
545 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700546 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800547 return -ENOSYS;
548 }
549 return OK;
550}
551
Pawin Vongmasa36653902018-11-15 00:10:25 -0800552status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
553 QueueGuard guard(mSync);
554 if (!guard.isRunning()) {
555 ALOGD("[%s] No more buffers should be queued at current state.", mName);
556 return -ENOSYS;
557 }
558 return queueInputBufferInternal(buffer);
559}
560
561status_t CCodecBufferChannel::queueSecureInputBuffer(
562 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
563 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
564 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
565 AString *errorDetailMsg) {
566 QueueGuard guard(mSync);
567 if (!guard.isRunning()) {
568 ALOGD("[%s] No more buffers should be queued at current state.", mName);
569 return -ENOSYS;
570 }
571
572 if (!hasCryptoOrDescrambler()) {
573 return -ENOSYS;
574 }
575 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
576
Sungtak Lee04b30352020-07-27 13:57:25 -0700577 std::shared_ptr<C2LinearBlock> block;
578 size_t allocSize = buffer->size();
579 size_t bufferSize = 0;
580 c2_status_t blockRes = C2_OK;
581 bool copied = false;
582 if (mSendEncryptedInfoBuffer) {
583 static const C2MemoryUsage kDefaultReadWriteUsage{
584 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
585 constexpr int kAllocGranule0 = 1024 * 64;
586 constexpr int kAllocGranule1 = 1024 * 1024;
587 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
588 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
589 if (allocSize <= kAllocGranule1) {
590 bufferSize = align(allocSize, kAllocGranule0);
591 } else {
592 bufferSize = align(allocSize, kAllocGranule1);
593 }
594 blockRes = pool->fetchLinearBlock(
595 bufferSize, kDefaultReadWriteUsage, &block);
596
597 if (blockRes == C2_OK) {
598 C2WriteView view = block->map().get();
599 if (view.error() == C2_OK && view.size() == bufferSize) {
600 copied = true;
601 // TODO: only copy clear sections
602 memcpy(view.data(), buffer->data(), allocSize);
603 }
604 }
605 }
606
607 if (!copied) {
608 block.reset();
609 }
610
Pawin Vongmasa36653902018-11-15 00:10:25 -0800611 ssize_t result = -1;
612 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700613 if (numSubSamples == 1
614 && subSamples[0].mNumBytesOfClearData == 0
615 && subSamples[0].mNumBytesOfEncryptedData == 0) {
616 // We don't need to go through crypto or descrambler if the input is empty.
617 result = 0;
618 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700619 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800620 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700621 destination.type = DrmBufferType::NATIVE_HANDLE;
622 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800623 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700624 destination.type = DrmBufferType::SHARED_MEMORY;
625 IMemoryToSharedBuffer(
626 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800627 }
Robert Shih895fba92019-07-16 16:29:44 -0700628 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800629 encryptedBuffer->fillSourceBuffer(&source);
630 result = mCrypto->decrypt(
631 key, iv, mode, pattern, source, buffer->offset(),
632 subSamples, numSubSamples, destination, errorDetailMsg);
633 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700634 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800635 return result;
636 }
Robert Shih895fba92019-07-16 16:29:44 -0700637 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800638 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
639 }
640 } else {
641 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
642 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
643 hidl_vec<SubSample> hidlSubSamples;
644 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
645
646 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
647 encryptedBuffer->fillSourceBuffer(&srcBuffer);
648
649 DestinationBuffer dstBuffer;
650 if (secure) {
651 dstBuffer.type = BufferType::NATIVE_HANDLE;
652 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
653 } else {
654 dstBuffer.type = BufferType::SHARED_MEMORY;
655 dstBuffer.nonsecureMemory = srcBuffer;
656 }
657
658 CasStatus status = CasStatus::OK;
659 hidl_string detailedError;
660 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
661
662 if (key != nullptr) {
663 sctrl = (ScramblingControl)key[0];
664 // Adjust for the PES offset
665 codecDataOffset = key[2] | (key[3] << 8);
666 }
667
668 auto returnVoid = mDescrambler->descramble(
669 sctrl,
670 hidlSubSamples,
671 srcBuffer,
672 0,
673 dstBuffer,
674 0,
675 [&status, &result, &detailedError] (
676 CasStatus _status, uint32_t _bytesWritten,
677 const hidl_string& _detailedError) {
678 status = _status;
679 result = (ssize_t)_bytesWritten;
680 detailedError = _detailedError;
681 });
682
683 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
684 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
685 mName, returnVoid.description().c_str(), status, result);
686 return UNKNOWN_ERROR;
687 }
688
689 if (result < codecDataOffset) {
690 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
691 return BAD_VALUE;
692 }
693
694 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
695
696 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
697 encryptedBuffer->copyDecryptedContentFromMemory(result);
698 }
699 }
700
701 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700702
703 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800704}
705
706void CCodecBufferChannel::feedInputBufferIfAvailable() {
707 QueueGuard guard(mSync);
708 if (!guard.isRunning()) {
709 ALOGV("[%s] We're not running --- no input buffer reported", mName);
710 return;
711 }
712 feedInputBufferIfAvailableInternal();
713}
714
715void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900716 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800717 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700718 }
719 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700720 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700721 if (!output->buffers ||
722 output->buffers->hasPending() ||
Wonsik Kim0487b782020-10-28 11:45:50 -0700723 output->buffers->numActiveSlots() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800724 return;
725 }
726 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700727 size_t numActiveSlots = 0;
728 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800729 sp<MediaCodecBuffer> inBuffer;
730 size_t index;
731 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700732 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700733 numActiveSlots = input->buffers->numActiveSlots();
734 if (numActiveSlots >= input->numSlots) {
735 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800736 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700737 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800738 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800739 break;
740 }
741 }
742 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
743 mCallback->onInputBufferAvailable(index, inBuffer);
744 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700745 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800746}
747
748status_t CCodecBufferChannel::renderOutputBuffer(
749 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800750 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800751 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800752 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800753 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700754 Mutexed<Output>::Locked output(mOutput);
755 if (output->buffers) {
756 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800757 }
758 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800759 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
760 // set to true.
761 sendOutputBuffers();
762 // input buffer feeding may have been gated by pending output buffers
763 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800764 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800765 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700766 std::call_once(mRenderWarningFlag, [this] {
767 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
768 "timestamp or render=true with non-video buffers. Apps should "
769 "call releaseOutputBuffer() with render=false for those.",
770 mName);
771 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800772 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800773 return INVALID_OPERATION;
774 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800775
776#if 0
777 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
778 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
779 for (const std::shared_ptr<const C2Info> &info : infoParams) {
780 AString res;
781 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
782 if (ix) res.append(", ");
783 res.append(*((int32_t*)info.get() + (ix / 4)));
784 }
785 ALOGV(" [%s]", res.c_str());
786 }
787#endif
788 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
789 std::static_pointer_cast<const C2StreamRotationInfo::output>(
790 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
791 bool flip = rotation && (rotation->flip & 1);
792 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900793
794 {
795 Mutexed<OutputSurface>::Locked output(mOutputSurface);
796 if (output->surface == nullptr) {
797 ALOGI("[%s] cannot render buffer without surface", mName);
798 return OK;
799 }
800 int64_t frameIndex;
801 buffer->meta()->findInt64("frameIndex", &frameIndex);
802 if (output->rotation.count(frameIndex) != 0) {
803 auto it = output->rotation.find(frameIndex);
804 quarters = (it->second / 90) & 3;
805 output->rotation.erase(it);
806 }
807 }
808
Pawin Vongmasa36653902018-11-15 00:10:25 -0800809 uint32_t transform = 0;
810 switch (quarters) {
811 case 0: // no rotation
812 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
813 break;
814 case 1: // 90 degrees counter-clockwise
815 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
816 : HAL_TRANSFORM_ROT_270;
817 break;
818 case 2: // 180 degrees
819 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
820 break;
821 case 3: // 90 degrees clockwise
822 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
823 : HAL_TRANSFORM_ROT_90;
824 break;
825 }
826
827 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
828 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
829 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
830 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
831 if (surfaceScaling) {
832 videoScalingMode = surfaceScaling->value;
833 }
834
835 // Use dataspace from format as it has the default aspects already applied
836 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
837 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
838
839 // HDR static info
840 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
841 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
842 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
843
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800844 // HDR10 plus info
845 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
846 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
847 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800848 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
849 hdr10PlusInfo.reset();
850 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800851
Wonsik Kima79c5522022-01-18 16:29:24 -0800852 // HDR dynamic info
853 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
854 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
855 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
856 // TODO: make this sticky & enable unset
857 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
858 hdrDynamicInfo.reset();
859 }
860
861 if (hdr10PlusInfo) {
862 // C2StreamHdr10PlusInfo is deprecated; components should use
863 // C2StreamHdrDynamicMetadataInfo
864 // TODO: #metric
865 if (hdrDynamicInfo) {
866 // It is unexpected that C2StreamHdr10PlusInfo and
867 // C2StreamHdrDynamicMetadataInfo is both present.
868 // C2StreamHdrDynamicMetadataInfo takes priority.
869 // TODO: #metric
870 } else {
871 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
872 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
873 hdr10PlusInfo->flexCount(),
874 0u,
875 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
876 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
877 hdrDynamicInfo = info;
878 }
879 }
880
Pawin Vongmasa36653902018-11-15 00:10:25 -0800881 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
882 if (blocks.size() != 1u) {
883 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
884 return UNKNOWN_ERROR;
885 }
886 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -0700887 C2Fence c2fence = block.fence();
888 sp<Fence> fence = Fence::NO_FENCE;
889 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
890 // Once C2Fence::type() is added, check the exact C2Fence type
891 if (c2fence.isHW()) {
892 int fenceFd = c2fence.fd();
893 fence = sp<Fence>::make(fenceFd);
894 if (!fence) {
895 ALOGE("[%s] Failed to allocate a fence", mName);
896 close(fenceFd);
897 return NO_MEMORY;
898 }
899 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800900
901 // TODO: revisit this after C2Fence implementation.
902 android::IGraphicBufferProducer::QueueBufferInput qbi(
903 timestampNs,
904 false, // droppable
905 dataSpace,
906 Rect(blocks.front().crop().left,
907 blocks.front().crop().top,
908 blocks.front().crop().right(),
909 blocks.front().crop().bottom()),
910 videoScalingMode,
911 transform,
Lubin Yin92427a52022-04-18 16:57:39 -0700912 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800913 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800914 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800915 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800916 // If mastering max and min luminance fields are 0, do not use them.
917 // It indicates the value may not be present in the stream.
918 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
919 hdrStaticInfo->mastering.minLuminance > 0.0f) {
920 struct android_smpte2086_metadata smpte2086_meta = {
921 .displayPrimaryRed = {
922 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
923 },
924 .displayPrimaryGreen = {
925 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
926 },
927 .displayPrimaryBlue = {
928 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
929 },
930 .whitePoint = {
931 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
932 },
933 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
934 .minLuminance = hdrStaticInfo->mastering.minLuminance,
935 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800936 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800937 hdr.smpte2086 = smpte2086_meta;
938 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700939 // If the content light level fields are 0, do not use them, it
940 // indicates the value may not be present in the stream.
941 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
942 struct android_cta861_3_metadata cta861_meta = {
943 .maxContentLightLevel = hdrStaticInfo->maxCll,
944 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
945 };
946 hdr.validTypes |= HdrMetadata::CTA861_3;
947 hdr.cta8613 = cta861_meta;
948 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900949
950 // does not have valid info
951 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
952 hdrStaticInfo.reset();
953 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800954 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800955 if (hdrDynamicInfo
956 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800957 hdr.validTypes |= HdrMetadata::HDR10PLUS;
958 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800959 hdrDynamicInfo->m.data,
960 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800961 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800962 qbi.setHdrMetadata(hdr);
Wonsik Kima79c5522022-01-18 16:29:24 -0800963
964 SetHdrMetadataToGralloc4Handle(hdrStaticInfo, hdrDynamicInfo, block.handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800965 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800966 // we don't have dirty regions
967 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800968 android::IGraphicBufferProducer::QueueBufferOutput qbo;
969 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
970 if (result != OK) {
971 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800972 if (result == NO_INIT) {
973 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
974 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800975 return result;
976 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800977
978 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
979 ALOGD("[%s] queue buffer successful", mName);
980 } else {
981 ALOGV("[%s] queue buffer successful", mName);
982 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800983
984 int64_t mediaTimeUs = 0;
985 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
986 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
987
988 return OK;
989}
990
991status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
992 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
993 bool released = false;
994 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700995 Mutexed<Input>::Locked input(mInput);
996 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800997 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800998 }
999 }
1000 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001001 Mutexed<Output>::Locked output(mOutput);
1002 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001003 released = true;
1004 }
1005 }
1006 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001007 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001008 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001009 } else {
1010 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1011 }
1012 return OK;
1013}
1014
1015void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1016 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001017 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001018
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001019 if (!input->buffers->isArrayMode()) {
1020 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001021 }
1022
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001023 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001024}
1025
1026void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1027 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001028 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001029
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001030 if (!output->buffers->isArrayMode()) {
1031 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001032 }
1033
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001034 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001035}
1036
1037status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001038 const sp<AMessage> &inputFormat,
1039 const sp<AMessage> &outputFormat,
1040 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001041 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1042 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001043 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001044 C2PortReorderBufferDepthTuning::output reorderDepth;
1045 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001046 C2PortActualDelayTuning::input inputDelay(0);
1047 C2PortActualDelayTuning::output outputDelay(0);
1048 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001049 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001050
Pawin Vongmasa36653902018-11-15 00:10:25 -08001051 c2_status_t err = mComponent->query(
1052 {
1053 &iStreamFormat,
1054 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001055 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001056 &reorderDepth,
1057 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001058 &inputDelay,
1059 &pipelineDelay,
1060 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001061 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001062 },
1063 {},
1064 C2_DONT_BLOCK,
1065 nullptr);
1066 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001067 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001068 return UNKNOWN_ERROR;
1069 }
1070 } else if (err != C2_OK) {
1071 return UNKNOWN_ERROR;
1072 }
1073
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001074 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1075 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1076 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1077
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001078 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1079 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001080
Pawin Vongmasa36653902018-11-15 00:10:25 -08001081 // TODO: get this from input format
1082 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1083
Sungtak Lee04b30352020-07-27 13:57:25 -07001084 // secure mode is a static parameter (shall not change in the executing state)
1085 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1086
Pawin Vongmasa36653902018-11-15 00:10:25 -08001087 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001088 int poolMask = GetCodec2PoolMask();
1089 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001090
1091 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001092 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001093 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001094 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1095 API_REFLECTION |
1096 API_VALUES |
1097 API_CURRENT_VALUES |
1098 API_DEPENDENCY |
1099 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001100 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1101 C2StreamSampleRateInfo::input sampleRate(0u);
1102 C2StreamChannelCountInfo::input channelCount(0u);
1103 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001104 std::shared_ptr<C2BlockPool> pool;
1105 {
1106 Mutexed<BlockPools>::Locked pools(mBlockPools);
1107
1108 // set default allocator ID.
1109 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001110 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001111
1112 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1113 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1114 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001115 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001116 std::vector<C2Param *> stackParams({&featuresSetting});
1117 if (audioEncoder) {
1118 stackParams.push_back(&encoderFrameSize);
1119 stackParams.push_back(&sampleRate);
1120 stackParams.push_back(&channelCount);
1121 stackParams.push_back(&pcmEncoding);
1122 } else {
1123 encoderFrameSize.invalidate();
1124 sampleRate.invalidate();
1125 channelCount.invalidate();
1126 pcmEncoding.invalidate();
1127 }
1128 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001129 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1130 C2_DONT_BLOCK,
1131 &params);
1132 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1133 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1134 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001135 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001136 C2PortAllocatorsTuning::input *inputAllocators =
1137 C2PortAllocatorsTuning::input::From(params[0].get());
1138 if (inputAllocators && inputAllocators->flexCount() > 0) {
1139 std::shared_ptr<C2Allocator> allocator;
1140 // verify allocator IDs and resolve default allocator
1141 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1142 if (allocator) {
1143 pools->inputAllocatorId = allocator->getId();
1144 } else {
1145 ALOGD("[%s] component requested invalid input allocator ID %u",
1146 mName, inputAllocators->m.values[0]);
1147 }
1148 }
1149 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001150 if (featuresSetting) {
1151 apiFeatures = featuresSetting.value;
1152 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001153
1154 // TODO: use C2Component wrapper to associate this pool with ourselves
1155 if ((poolMask >> pools->inputAllocatorId) & 1) {
1156 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1157 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1158 mName, pools->inputAllocatorId,
1159 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1160 asString(err), err);
1161 } else {
1162 err = C2_NOT_FOUND;
1163 }
1164 if (err != C2_OK) {
1165 C2BlockPool::local_id_t inputPoolId =
1166 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1167 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1168 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1169 mName, (unsigned long long)inputPoolId,
1170 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1171 asString(err), err);
1172 if (err != C2_OK) {
1173 return NO_MEMORY;
1174 }
1175 }
1176 pools->inputPool = pool;
1177 }
1178
Wonsik Kim51051262018-11-28 13:59:05 -08001179 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001180 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001181 input->inputDelay = inputDelayValue;
1182 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001183 input->numSlots = numInputSlots;
1184 input->extraBuffers.flush();
1185 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001186 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001187 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1188 input->frameReassembler.init(
1189 pool,
1190 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1191 encoderFrameSize.value,
1192 sampleRate.value,
1193 channelCount.value,
1194 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1195 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001196 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1197 // For encrypted content, framework decrypts source buffer (ashmem) into
1198 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001199 if (!buffersBoundToCodec
1200 && !input->frameReassembler
1201 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001202 input->buffers.reset(new SlotInputBuffers(mName));
1203 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001204 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001205 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001206 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001207 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001208 // This is to ensure buffers do not get released prematurely.
1209 // TODO: handle this without going into array mode
1210 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001211 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001212 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001213 }
1214 } else {
1215 if (hasCryptoOrDescrambler()) {
1216 int32_t capacity = kLinearBufferSize;
1217 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1218 if ((size_t)capacity > kMaxLinearBufferSize) {
1219 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1220 capacity = kMaxLinearBufferSize;
1221 }
1222 if (mDealer == nullptr) {
1223 mDealer = new MemoryDealer(
1224 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001225 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001226 "EncryptedLinearInputBuffers");
1227 mDecryptDestination = mDealer->allocate((size_t)capacity);
1228 }
1229 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001230 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1231 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001232 } else {
1233 mHeapSeqNum = -1;
1234 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001235 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001236 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001237 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001238 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001239 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001240 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001241 }
1242 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001243 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001244
1245 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001246 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001247 } else {
1248 // TODO: error
1249 }
Wonsik Kim51051262018-11-28 13:59:05 -08001250
1251 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001252 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001253 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001254 }
1255
1256 if (outputFormat != nullptr) {
1257 sp<IGraphicBufferProducer> outputSurface;
1258 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001259 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001260 {
1261 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001262 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001263 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001264 outputSurface = output->surface ?
1265 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001266 if (outputSurface) {
1267 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1268 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001269 outputGeneration = output->generation;
1270 }
1271
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001272 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001273 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001274 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001275
1276 {
1277 Mutexed<BlockPools>::Locked pools(mBlockPools);
1278
David Stevensc3fbb282021-01-18 18:11:20 +09001279 prevOutputPoolId = pools->outputPoolId;
1280
Pawin Vongmasa36653902018-11-15 00:10:25 -08001281 // set default allocator ID.
1282 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001283 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001284
1285 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1286 // unsuccessful.
1287 std::vector<std::unique_ptr<C2Param>> params;
1288 err = mComponent->query({ },
1289 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1290 C2_DONT_BLOCK,
1291 &params);
1292 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1293 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1294 mName, params.size(), asString(err), err);
1295 } else if (err == C2_OK && params.size() == 1) {
1296 C2PortAllocatorsTuning::output *outputAllocators =
1297 C2PortAllocatorsTuning::output::From(params[0].get());
1298 if (outputAllocators && outputAllocators->flexCount() > 0) {
1299 std::shared_ptr<C2Allocator> allocator;
1300 // verify allocator IDs and resolve default allocator
1301 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1302 if (allocator) {
1303 pools->outputAllocatorId = allocator->getId();
1304 } else {
1305 ALOGD("[%s] component requested invalid output allocator ID %u",
1306 mName, outputAllocators->m.values[0]);
1307 }
1308 }
1309 }
1310
1311 // use bufferqueue if outputting to a surface.
1312 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1313 // if unsuccessful.
1314 if (outputSurface) {
1315 params.clear();
1316 err = mComponent->query({ },
1317 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1318 C2_DONT_BLOCK,
1319 &params);
1320 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1321 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1322 mName, params.size(), asString(err), err);
1323 } else if (err == C2_OK && params.size() == 1) {
1324 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1325 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1326 if (surfaceAllocator) {
1327 std::shared_ptr<C2Allocator> allocator;
1328 // verify allocator IDs and resolve default allocator
1329 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1330 if (allocator) {
1331 pools->outputAllocatorId = allocator->getId();
1332 } else {
1333 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1334 mName, surfaceAllocator->value);
1335 err = C2_BAD_VALUE;
1336 }
1337 }
1338 }
1339 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1340 && err != C2_OK
1341 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1342 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1343 }
1344 }
1345
1346 if ((poolMask >> pools->outputAllocatorId) & 1) {
1347 err = mComponent->createBlockPool(
1348 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1349 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1350 mName, pools->outputAllocatorId,
1351 (unsigned long long)pools->outputPoolId,
1352 asString(err));
1353 } else {
1354 err = C2_NOT_FOUND;
1355 }
1356 if (err != C2_OK) {
1357 // use basic pool instead
1358 pools->outputPoolId =
1359 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1360 }
1361
1362 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1363 // component.
1364 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1365 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1366
1367 std::vector<std::unique_ptr<C2SettingResult>> failures;
1368 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1369 ALOGD("[%s] Configured output block pool ids %llu => %s",
1370 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1371 outputPoolId_ = pools->outputPoolId;
1372 }
1373
David Stevensc3fbb282021-01-18 18:11:20 +09001374 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1375 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1376 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1377 if (err != C2_OK) {
1378 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1379 (unsigned long long) prevOutputPoolId, asString(err), err);
1380 }
1381 }
1382
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001383 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001384 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001385 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001386 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001387 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001388 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001389 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001390 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001391 }
1392 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001393 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001395 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001396
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001397 output->buffers->clearStash();
1398 if (reorderDepth) {
1399 output->buffers->setReorderDepth(reorderDepth.value);
1400 }
1401 if (reorderKey) {
1402 output->buffers->setReorderKey(reorderKey.value);
1403 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001404
1405 // Try to set output surface to created block pool if given.
1406 if (outputSurface) {
1407 mComponent->setOutputSurface(
1408 outputPoolId_,
1409 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001410 outputGeneration,
1411 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001412 } else {
1413 // configure CPU read consumer usage
1414 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1415 std::vector<std::unique_ptr<C2SettingResult>> failures;
1416 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1417 // do not print error message for now as most components may not yet
1418 // support this setting
1419 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1420 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001421 }
1422
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001423 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001424 if (buffersBoundToCodec) {
1425 // WORKAROUND: if we're using early CSD workaround we convert to
1426 // array mode, to appease apps assuming the output
1427 // buffers to be of the same size.
1428 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1429 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001430
1431 int32_t channelCount;
1432 int32_t sampleRate;
1433 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1434 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1435 int32_t delay = 0;
1436 int32_t padding = 0;;
1437 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1438 delay = 0;
1439 }
1440 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1441 padding = 0;
1442 }
1443 if (delay || padding) {
1444 // We need write access to the buffers, and we're already in
1445 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001446 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001447 }
1448 }
1449 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001450
1451 int32_t tunneled = 0;
1452 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1453 tunneled = 0;
1454 }
1455 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001456 }
1457
1458 // Set up pipeline control. This has to be done after mInputBuffers and
1459 // mOutputBuffers are initialized to make sure that lingering callbacks
1460 // about buffers from the previous generation do not interfere with the
1461 // newly initialized pipeline capacity.
1462
Wonsik Kim62545252021-01-20 11:25:41 -08001463 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001464 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001465 watcher->inputDelay(inputDelayValue)
1466 .pipelineDelay(pipelineDelayValue)
1467 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001468 .smoothnessFactor(kSmoothnessFactor);
1469 watcher->flush();
1470 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001471
1472 mInputMetEos = false;
1473 mSync.start();
1474 return OK;
1475}
1476
Wonsik Kim34b28b42022-05-20 15:49:32 -07001477status_t CCodecBufferChannel::prepareInitialInputBuffers(
1478 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001479 if (mInputSurface) {
1480 return OK;
1481 }
1482
Wonsik Kim34b28b42022-05-20 15:49:32 -07001483 size_t numInputSlots = mInput.lock()->numSlots;
1484
1485 {
1486 Mutexed<Input>::Locked input(mInput);
1487 while (clientInputBuffers->size() < numInputSlots) {
1488 size_t index;
1489 sp<MediaCodecBuffer> buffer;
1490 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
1491 break;
1492 }
1493 clientInputBuffers->emplace(index, buffer);
1494 }
1495 }
1496 if (clientInputBuffers->empty()) {
1497 ALOGW("[%s] start: cannot allocate memory at all", mName);
1498 return NO_MEMORY;
1499 } else if (clientInputBuffers->size() < numInputSlots) {
1500 ALOGD("[%s] start: cannot allocate memory for all slots, "
1501 "only %zu buffers allocated",
1502 mName, clientInputBuffers->size());
1503 } else {
1504 ALOGV("[%s] %zu initial input buffers available",
1505 mName, clientInputBuffers->size());
1506 }
1507 return OK;
1508}
1509
1510status_t CCodecBufferChannel::requestInitialInputBuffers(
1511 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001512 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001513 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1514 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1515 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001516 return UNKNOWN_ERROR;
1517 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001518
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001519 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1520 mFlushedConfigs.lock()->swap(flushedConfigs);
1521 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001522 {
1523 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1524 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1525 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1526 watcher->onWorkQueued(
1527 work->input.ordinal.frameIndex.peeku(),
1528 std::vector(work->input.buffers),
1529 now);
1530 }
1531 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001532 err = mComponent->queue(&flushedConfigs);
1533 if (err != C2_OK) {
1534 ALOGW("[%s] Error while queueing a flushed config", mName);
1535 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001536 }
1537 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001538 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07001539 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
1540 !clientInputBuffers.empty()) {
1541 size_t minIndex = clientInputBuffers.begin()->first;
1542 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
1543 for (const auto &[index, buffer] : clientInputBuffers) {
1544 if (minBuffer->capacity() > buffer->capacity()) {
1545 minIndex = index;
1546 minBuffer = buffer;
1547 }
1548 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001549 // WORKAROUND: Some apps expect CSD available without queueing
1550 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07001551 minBuffer->setRange(0, 0);
1552 minBuffer->meta()->clear();
1553 minBuffer->meta()->setInt64("timeUs", 0);
1554 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001555 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1556 mName);
1557 return UNKNOWN_ERROR;
1558 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07001559 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001560 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001561
Wonsik Kim34b28b42022-05-20 15:49:32 -07001562 for (const auto &[index, buffer] : clientInputBuffers) {
1563 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001564 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001565
Pawin Vongmasa36653902018-11-15 00:10:25 -08001566 return OK;
1567}
1568
1569void CCodecBufferChannel::stop() {
1570 mSync.stop();
1571 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001572}
1573
Wonsik Kim936a89c2020-05-08 16:07:50 -07001574void CCodecBufferChannel::reset() {
1575 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001576 if (mInputSurface != nullptr) {
1577 mInputSurface.reset();
1578 }
1579 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001580 {
1581 Mutexed<Input>::Locked input(mInput);
1582 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001583 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001584 }
1585 {
1586 Mutexed<Output>::Locked output(mOutput);
1587 output->buffers.reset();
1588 }
Sungtak Leec7da7a02022-05-05 08:45:33 +00001589 if (mOutputSurface.lock()->surface) {
1590 C2BlockPool::local_id_t outputPoolId;
1591 {
1592 Mutexed<BlockPools>::Locked pools(mBlockPools);
1593 outputPoolId = pools->outputPoolId;
1594 }
1595 mComponent->stopUsingOutputSurface(outputPoolId);
1596 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001597}
1598
1599void CCodecBufferChannel::release() {
1600 mComponent.reset();
1601 mInputAllocator.reset();
1602 mOutputSurface.lock()->surface.clear();
1603 {
1604 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1605 blockPools->inputPool.reset();
1606 blockPools->outputPoolIntf.reset();
1607 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001608 setCrypto(nullptr);
1609 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001610}
1611
Pawin Vongmasa36653902018-11-15 00:10:25 -08001612void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1613 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001614 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001615 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001616 {
1617 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1618 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1619 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1620 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1621 watcher->onWorkDone(frameIndex);
1622 continue;
1623 }
1624 if (work->input.buffers.empty()
1625 || work->input.buffers.front() == nullptr
1626 || work->input.buffers.front()->data().linearBlocks().empty()) {
1627 ALOGD("[%s] no linear codec config data found", mName);
1628 watcher->onWorkDone(frameIndex);
1629 continue;
1630 }
1631 std::unique_ptr<C2Work> copy(new C2Work);
1632 copy->input.flags = C2FrameData::flags_t(
1633 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1634 copy->input.ordinal = work->input.ordinal;
1635 copy->input.ordinal.frameIndex = mFrameIndex++;
1636 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1637 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1638 }
1639 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1640 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1641 }
1642 copy->input.infoBuffers.insert(
1643 copy->input.infoBuffers.begin(),
1644 work->input.infoBuffers.begin(),
1645 work->input.infoBuffers.end());
1646 copy->worklets.emplace_back(new C2Worklet);
1647 configs.push_back(std::move(copy));
1648 watcher->onWorkDone(frameIndex);
1649 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001650 }
1651 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001652 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001653 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001654 Mutexed<Input>::Locked input(mInput);
1655 input->buffers->flush();
1656 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001657 }
1658 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001659 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001660 if (output->buffers) {
1661 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001662 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001663 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001664 }
1665}
1666
1667void CCodecBufferChannel::onWorkDone(
1668 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001669 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001670 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001671 feedInputBufferIfAvailable();
1672 }
1673}
1674
1675void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001676 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001677 if (mInputSurface) {
1678 return;
1679 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001680 std::shared_ptr<C2Buffer> buffer =
1681 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001682 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001683 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001684 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001685 if (input->lastFlushIndex >= frameIndex) {
1686 ALOGD("[%s] Ignoring stale input buffer done callback: "
1687 "last flush index = %lld, frameIndex = %lld",
1688 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1689 } else {
1690 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1691 if (!newInputSlotAvailable) {
1692 (void)input->extraBuffers.expireComponentBuffer(buffer);
1693 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001694 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001695 }
1696 if (newInputSlotAvailable) {
1697 feedInputBufferIfAvailable();
1698 }
1699}
1700
1701bool CCodecBufferChannel::handleWork(
1702 std::unique_ptr<C2Work> work,
1703 const sp<AMessage> &outputFormat,
1704 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001705 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001706 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001707 if (!output->buffers) {
1708 return false;
1709 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001710 }
1711
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001712 // Whether the output buffer should be reported to the client or not.
1713 bool notifyClient = false;
1714
1715 if (work->result == C2_OK){
1716 notifyClient = true;
1717 } else if (work->result == C2_NOT_FOUND) {
1718 ALOGD("[%s] flushed work; ignored.", mName);
1719 } else {
1720 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1721 // the config update.
1722 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1723 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1724 return false;
1725 }
1726
1727 if ((work->input.ordinal.frameIndex -
1728 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001729 // Discard frames from previous generation.
1730 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001731 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001732 }
1733
Wonsik Kim524b0582019-03-12 11:28:57 -07001734 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001735 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001736 || !(work->worklets.front()->output.flags &
1737 C2FrameData::FLAG_INCOMPLETE))) {
1738 mPipelineWatcher.lock()->onWorkDone(
1739 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001740 }
1741
1742 // NOTE: MediaCodec usage supposedly have only one worklet
1743 if (work->worklets.size() != 1u) {
1744 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1745 mName, work->worklets.size());
1746 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1747 return false;
1748 }
1749
1750 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1751
1752 std::shared_ptr<C2Buffer> buffer;
1753 // NOTE: MediaCodec usage supposedly have only one output stream.
1754 if (worklet->output.buffers.size() > 1u) {
1755 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1756 mName, worklet->output.buffers.size());
1757 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1758 return false;
1759 } else if (worklet->output.buffers.size() == 1u) {
1760 buffer = worklet->output.buffers[0];
1761 if (!buffer) {
1762 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1763 }
1764 }
1765
Wonsik Kim3dedf682021-05-03 10:57:09 -07001766 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1767 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001768 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001769 while (!worklet->output.configUpdate.empty()) {
1770 std::unique_ptr<C2Param> param;
1771 worklet->output.configUpdate.back().swap(param);
1772 worklet->output.configUpdate.pop_back();
1773 switch (param->coreIndex().coreIndex()) {
1774 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1775 C2PortReorderBufferDepthTuning::output reorderDepth;
1776 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001777 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1778 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001779 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001780 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001781 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001782 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1783 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001784 }
1785 break;
1786 }
1787 case C2PortReorderKeySetting::CORE_INDEX: {
1788 C2PortReorderKeySetting::output reorderKey;
1789 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001790 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001791 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1792 mName, reorderKey.value);
1793 } else {
1794 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1795 }
1796 break;
1797 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001798 case C2PortActualDelayTuning::CORE_INDEX: {
1799 if (param->isGlobal()) {
1800 C2ActualPipelineDelayTuning pipelineDelay;
1801 if (pipelineDelay.updateFrom(*param)) {
1802 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1803 mName, pipelineDelay.value);
1804 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001805 (void)mPipelineWatcher.lock()->pipelineDelay(
1806 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001807 }
1808 }
1809 if (param->forInput()) {
1810 C2PortActualDelayTuning::input inputDelay;
1811 if (inputDelay.updateFrom(*param)) {
1812 ALOGV("[%s] onWorkDone: updating input delay %u",
1813 mName, inputDelay.value);
1814 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001815 (void)mPipelineWatcher.lock()->inputDelay(
1816 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001817 }
1818 }
1819 if (param->forOutput()) {
1820 C2PortActualDelayTuning::output outputDelay;
1821 if (outputDelay.updateFrom(*param)) {
1822 ALOGV("[%s] onWorkDone: updating output delay %u",
1823 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001824 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001825 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001826 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001827
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001828 }
1829 }
1830 break;
1831 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001832 case C2PortTunnelSystemTime::CORE_INDEX: {
1833 C2PortTunnelSystemTime::output frameRenderTime;
1834 if (frameRenderTime.updateFrom(*param)) {
1835 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1836 mName, (long long)frameRenderTime.value,
1837 (long long)worklet->output.ordinal.timestamp.peekll());
1838 mCCodecCallback->onOutputFramesRendered(
1839 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1840 }
1841 break;
1842 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001843 case C2StreamTunnelHoldRender::CORE_INDEX: {
1844 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1845 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1846 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1847 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1848 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1849 mCCodecCallback->onFirstTunnelFrameReady();
1850 break;
1851 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001852 default:
1853 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1854 mName, param->index());
1855 break;
1856 }
1857 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001858 if (newInputDelay || newPipelineDelay) {
1859 Mutexed<Input>::Locked input(mInput);
1860 size_t newNumSlots =
1861 newInputDelay.value_or(input->inputDelay) +
1862 newPipelineDelay.value_or(input->pipelineDelay) +
1863 kSmoothnessFactor;
1864 if (input->buffers->isArrayMode()) {
1865 if (input->numSlots >= newNumSlots) {
1866 input->numExtraSlots = 0;
1867 } else {
1868 input->numExtraSlots = newNumSlots - input->numSlots;
1869 }
1870 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1871 mName, input->numExtraSlots);
1872 } else {
1873 input->numSlots = newNumSlots;
1874 }
1875 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001876 size_t numOutputSlots = 0;
1877 uint32_t reorderDepth = 0;
1878 bool outputBuffersChanged = false;
1879 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
1880 Mutexed<Output>::Locked output(mOutput);
1881 if (!output->buffers) {
1882 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001883 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001884 numOutputSlots = output->numSlots;
1885 if (newReorderKey) {
1886 output->buffers->setReorderKey(newReorderKey.value());
1887 }
1888 if (newReorderDepth) {
1889 output->buffers->setReorderDepth(newReorderDepth.value());
1890 }
1891 reorderDepth = output->buffers->getReorderDepth();
1892 if (newOutputDelay) {
1893 output->outputDelay = newOutputDelay.value();
1894 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
1895 if (output->numSlots < numOutputSlots) {
1896 output->numSlots = numOutputSlots;
1897 if (output->buffers->isArrayMode()) {
1898 OutputBuffersArray *array =
1899 (OutputBuffersArray *)output->buffers.get();
1900 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1901 mName, numOutputSlots);
1902 array->grow(numOutputSlots);
1903 outputBuffersChanged = true;
1904 }
1905 }
1906 }
1907 numOutputSlots = output->numSlots;
1908 }
1909 if (outputBuffersChanged) {
1910 mCCodecCallback->onOutputBuffersChanged();
1911 }
1912 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07001913 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07001914 {
1915 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1916 maxDequeueCount = output->maxDequeueBuffers =
1917 numOutputSlots + reorderDepth + kRenderingDepth;
1918 if (output->surface) {
1919 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1920 }
1921 }
1922 if (maxDequeueCount > 0) {
1923 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001924 }
1925 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001926
Pawin Vongmasa36653902018-11-15 00:10:25 -08001927 int32_t flags = 0;
1928 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07001929 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001930 ALOGV("[%s] onWorkDone: output EOS", mName);
1931 }
1932
Pawin Vongmasa36653902018-11-15 00:10:25 -08001933 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1934 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1935 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1936 // shall correspond to the client input timesamp (in customOrdinal). By using the
1937 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1938 // produces multiple output.
1939 c2_cntr64_t timestamp =
1940 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1941 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001942 if (mInputSurface != nullptr) {
1943 // When using input surface we need to restore the original input timestamp.
1944 timestamp = work->input.ordinal.customOrdinal;
1945 }
My Name6bd9a7d2022-03-25 12:37:58 -07001946 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
1947 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001948 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1949 mName,
1950 work->input.ordinal.customOrdinal.peekll(),
1951 work->input.ordinal.timestamp.peekll(),
1952 worklet->output.ordinal.timestamp.peekll(),
1953 timestamp.peekll());
1954
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001955 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001956 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001957 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001958 if (output->buffers && outputFormat) {
1959 output->buffers->updateSkipCutBuffer(outputFormat);
1960 output->buffers->setFormat(outputFormat);
1961 }
1962 if (!notifyClient) {
1963 return false;
1964 }
1965 size_t index;
1966 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07001967 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001968 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07001969 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001970 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1971
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001972 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001973 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001974 } else {
1975 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001976 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001977 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001978 return false;
1979 }
1980 }
1981
Wonsik Kimec585c32021-10-01 01:11:00 -07001982 bool drop = false;
1983 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
1984 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
1985 drop = true;
1986 }
1987
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001988 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07001989 if (mTunneled && drop && outputFormat) {
1990 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
1991 mName, work->input.ordinal.frameIndex.peekull());
1992 } else {
1993 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1994 mName, work->input.ordinal.frameIndex.peekull());
1995 notifyClient = false;
1996 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001997 }
1998
1999 if (buffer) {
2000 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2001 // TODO: properly translate these to metadata
2002 switch (info->coreIndex().coreIndex()) {
2003 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002004 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002005 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002006 }
2007 break;
2008 default:
2009 break;
2010 }
2011 }
2012 }
2013
2014 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002015 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002016 if (!output->buffers) {
2017 return false;
2018 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002019 output->buffers->pushToStash(
2020 buffer,
2021 notifyClient,
2022 timestamp.peek(),
2023 flags,
2024 outputFormat,
2025 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002026 }
2027 sendOutputBuffers();
2028 return true;
2029}
2030
2031void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002032 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002033 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002034 sp<MediaCodecBuffer> outBuffer;
2035 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002036
2037 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002038 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002039 if (!output->buffers) {
2040 return;
2041 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002042 action = output->buffers->popFromStashAndRegister(
2043 &c2Buffer, &index, &outBuffer);
2044 switch (action) {
2045 case OutputBuffers::SKIP:
2046 return;
2047 case OutputBuffers::DISCARD:
2048 break;
2049 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00002050 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002051 mCallback->onOutputBufferAvailable(index, outBuffer);
2052 break;
2053 case OutputBuffers::REALLOCATE:
2054 if (!output->buffers->isArrayMode()) {
2055 output->buffers =
2056 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002057 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002058 static_cast<OutputBuffersArray*>(output->buffers.get())->
2059 realloc(c2Buffer);
2060 output.unlock();
2061 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002062 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002063 case OutputBuffers::RETRY:
2064 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2065 mName);
2066 return;
2067 default:
2068 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2069 "corrupted BufferAction value (%d) "
2070 "returned from popFromStashAndRegister.",
2071 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002072 return;
2073 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002074 }
2075}
2076
2077status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
2078 static std::atomic_uint32_t surfaceGeneration{0};
2079 uint32_t generation = (getpid() << 10) |
2080 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2081 & ((1 << 10) - 1));
2082
2083 sp<IGraphicBufferProducer> producer;
Sungtak Leedb14cba2021-04-10 00:50:23 -07002084 int maxDequeueCount = mOutputSurface.lock()->maxDequeueBuffers;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002085 if (newSurface) {
2086 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002087 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002088 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002089 producer = newSurface->getIGraphicBufferProducer();
2090 producer->setGenerationNumber(generation);
2091 } else {
2092 ALOGE("[%s] setting output surface to null", mName);
2093 return INVALID_OPERATION;
2094 }
2095
2096 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2097 C2BlockPool::local_id_t outputPoolId;
2098 {
2099 Mutexed<BlockPools>::Locked pools(mBlockPools);
2100 outputPoolId = pools->outputPoolId;
2101 outputPoolIntf = pools->outputPoolIntf;
2102 }
2103
2104 if (outputPoolIntf) {
2105 if (mComponent->setOutputSurface(
2106 outputPoolId,
2107 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002108 generation,
2109 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002110 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2111 return INVALID_OPERATION;
2112 }
2113 }
2114
2115 {
2116 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2117 output->surface = newSurface;
2118 output->generation = generation;
2119 }
2120
2121 return OK;
2122}
2123
Wonsik Kimab34ed62019-01-31 15:28:46 -08002124PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002125 // Otherwise, component may have stalled work due to input starvation up to
2126 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002127 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2128 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002129 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002130 size_t outputDelay = mOutput.lock()->outputDelay;
2131 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002132 Mutexed<Input>::Locked input(mInput);
2133 n = input->inputDelay + input->pipelineDelay + outputDelay;
2134 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002135 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002136}
2137
Pawin Vongmasa36653902018-11-15 00:10:25 -08002138void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2139 mMetaMode = mode;
2140}
2141
Wonsik Kim596187e2019-10-25 12:44:10 -07002142void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002143 if (mCrypto != nullptr) {
2144 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2145 mCrypto->unsetHeap(entry.second);
2146 }
2147 mHeapSeqNumMap.clear();
2148 if (mHeapSeqNum >= 0) {
2149 mCrypto->unsetHeap(mHeapSeqNum);
2150 mHeapSeqNum = -1;
2151 }
2152 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002153 mCrypto = crypto;
2154}
2155
2156void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2157 mDescrambler = descrambler;
2158}
2159
Pawin Vongmasa36653902018-11-15 00:10:25 -08002160status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2161 // C2_OK is always translated to OK.
2162 if (c2s == C2_OK) {
2163 return OK;
2164 }
2165
2166 // Operation-dependent translation
2167 // TODO: Add as necessary
2168 switch (c2op) {
2169 case C2_OPERATION_Component_start:
2170 switch (c2s) {
2171 case C2_NO_MEMORY:
2172 return NO_MEMORY;
2173 default:
2174 return UNKNOWN_ERROR;
2175 }
2176 default:
2177 break;
2178 }
2179
2180 // Backup operation-agnostic translation
2181 switch (c2s) {
2182 case C2_BAD_INDEX:
2183 return BAD_INDEX;
2184 case C2_BAD_VALUE:
2185 return BAD_VALUE;
2186 case C2_BLOCKING:
2187 return WOULD_BLOCK;
2188 case C2_DUPLICATE:
2189 return ALREADY_EXISTS;
2190 case C2_NO_INIT:
2191 return NO_INIT;
2192 case C2_NO_MEMORY:
2193 return NO_MEMORY;
2194 case C2_NOT_FOUND:
2195 return NAME_NOT_FOUND;
2196 case C2_TIMED_OUT:
2197 return TIMED_OUT;
2198 case C2_BAD_STATE:
2199 case C2_CANCELED:
2200 case C2_CANNOT_DO:
2201 case C2_CORRUPTED:
2202 case C2_OMITTED:
2203 case C2_REFUSED:
2204 return UNKNOWN_ERROR;
2205 default:
2206 return -static_cast<status_t>(c2s);
2207 }
2208}
2209
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +01002210status_t CCodecBufferChannel::pushBlankBufferToOutputSurface() {
2211 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2212 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(output->surface.get());
2213 if (nativeWindow == nullptr) {
2214 return INVALID_OPERATION;
2215 }
2216 return pushBlankBuffersToNativeWindow(nativeWindow.get());
2217}
2218
Pawin Vongmasa36653902018-11-15 00:10:25 -08002219} // namespace android