blob: 870660ea14162b7beab65d9f369b7e8a6007bf03 [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright 2017, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodecBufferChannel"
19#include <utils/Log.h>
20
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070021#include <algorithm>
Wonsik Kim6b2c8be2021-09-28 05:11:04 -070022#include <atomic>
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070023#include <list>
Pawin Vongmasa36653902018-11-15 00:10:25 -080024#include <numeric>
25
26#include <C2AllocatorGralloc.h>
27#include <C2PlatformSupport.h>
28#include <C2BlockInternal.h>
29#include <C2Config.h>
30#include <C2Debug.h>
31
32#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070033#include <android/hardware/drm/1.0/types.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080034#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080035#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080036#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080037#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070038#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080039#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070040#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080041#include <media/openmax/OMX_Core.h>
42#include <media/stagefright/foundation/ABuffer.h>
43#include <media/stagefright/foundation/ALookup.h>
44#include <media/stagefright/foundation/AMessage.h>
45#include <media/stagefright/foundation/AUtils.h>
46#include <media/stagefright/foundation/hexdump.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080047#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070048#include <media/stagefright/SkipCutBuffer.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080049#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070050#include <mediadrm/ICrypto.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080051#include <system/window.h>
52
53#include "CCodecBufferChannel.h"
54#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080055
56namespace android {
57
58using android::base::StringPrintf;
59using hardware::hidl_handle;
60using hardware::hidl_string;
61using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070062using hardware::fromHeap;
63using hardware::HidlMemory;
64
Pawin Vongmasa36653902018-11-15 00:10:25 -080065using namespace hardware::cas::V1_0;
66using namespace hardware::cas::native::V1_0;
67
68using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070069using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080070
Pawin Vongmasa36653902018-11-15 00:10:25 -080071namespace {
72
Wonsik Kim469c8342019-04-11 16:46:09 -070073constexpr size_t kSmoothnessFactor = 4;
74constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080075
Sungtak Leeab6f2f32019-02-15 14:43:51 -080076// This is for keeping IGBP's buffer dropping logic in legacy mode other
77// than making it non-blocking. Do not change this value.
78const static size_t kDequeueTimeoutNs = 0;
79
Pawin Vongmasa36653902018-11-15 00:10:25 -080080} // namespace
81
82CCodecBufferChannel::QueueGuard::QueueGuard(
83 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
84 Mutex::Autolock l(mSync.mGuardLock);
85 // At this point it's guaranteed that mSync is not under state transition,
86 // as we are holding its mutex.
87
88 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
89 if (count->value == -1) {
90 mRunning = false;
91 } else {
92 ++count->value;
93 mRunning = true;
94 }
95}
96
97CCodecBufferChannel::QueueGuard::~QueueGuard() {
98 if (mRunning) {
99 // We are not holding mGuardLock at this point so that QueueSync::stop() can
100 // keep holding the lock until mCount reaches zero.
101 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
102 --count->value;
103 count->cond.broadcast();
104 }
105}
106
107void CCodecBufferChannel::QueueSync::start() {
108 Mutex::Autolock l(mGuardLock);
109 // If stopped, it goes to running state; otherwise no-op.
110 Mutexed<Counter>::Locked count(mCount);
111 if (count->value == -1) {
112 count->value = 0;
113 }
114}
115
116void CCodecBufferChannel::QueueSync::stop() {
117 Mutex::Autolock l(mGuardLock);
118 Mutexed<Counter>::Locked count(mCount);
119 if (count->value == -1) {
120 // no-op
121 return;
122 }
123 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
124 // mCount can only decrement. In other words, threads that acquired the lock
125 // are allowed to finish execution but additional threads trying to acquire
126 // the lock at this point will block, and then get QueueGuard at STOPPED
127 // state.
128 while (count->value != 0) {
129 count.waitForCondition(count->cond);
130 }
131 count->value = -1;
132}
133
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700134// Input
135
136CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
137
Pawin Vongmasa36653902018-11-15 00:10:25 -0800138// CCodecBufferChannel
139
140CCodecBufferChannel::CCodecBufferChannel(
141 const std::shared_ptr<CCodecCallback> &callback)
142 : mHeapSeqNum(-1),
143 mCCodecCallback(callback),
144 mFrameIndex(0u),
145 mFirstValidFrameIndex(0u),
146 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700147 mInputMetEos(false),
148 mSendEncryptedInfoBuffer(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700149 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700150 {
151 Mutexed<Input>::Locked input(mInput);
152 input->buffers.reset(new DummyInputBuffers(""));
153 input->extraBuffers.flush();
154 input->inputDelay = 0u;
155 input->pipelineDelay = 0u;
156 input->numSlots = kSmoothnessFactor;
157 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700158 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700159 }
160 {
161 Mutexed<Output>::Locked output(mOutput);
162 output->outputDelay = 0u;
163 output->numSlots = kSmoothnessFactor;
164 }
David Stevensc3fbb282021-01-18 18:11:20 +0900165 {
166 Mutexed<BlockPools>::Locked pools(mBlockPools);
167 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
168 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800169}
170
171CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800172 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800173 mCrypto->unsetHeap(mHeapSeqNum);
174 }
175}
176
177void CCodecBufferChannel::setComponent(
178 const std::shared_ptr<Codec2Client::Component> &component) {
179 mComponent = component;
180 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
181 mName = mComponentName.c_str();
182}
183
184status_t CCodecBufferChannel::setInputSurface(
185 const std::shared_ptr<InputSurfaceWrapper> &surface) {
186 ALOGV("[%s] setInputSurface", mName);
187 mInputSurface = surface;
188 return mInputSurface->connect(mComponent);
189}
190
191status_t CCodecBufferChannel::signalEndOfInputStream() {
192 if (mInputSurface == nullptr) {
193 return INVALID_OPERATION;
194 }
195 return mInputSurface->signalEndOfInputStream();
196}
197
Sungtak Lee04b30352020-07-27 13:57:25 -0700198status_t CCodecBufferChannel::queueInputBufferInternal(
199 sp<MediaCodecBuffer> buffer,
200 std::shared_ptr<C2LinearBlock> encryptedBlock,
201 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800202 int64_t timeUs;
203 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
204
205 if (mInputMetEos) {
206 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
207 return OK;
208 }
209
210 int32_t flags = 0;
211 int32_t tmp = 0;
212 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200213 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800214 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
215 eos = true;
216 mInputMetEos = true;
217 ALOGV("[%s] input EOS", mName);
218 }
219 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
220 flags |= C2FrameData::FLAG_CODEC_CONFIG;
221 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200222 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
223 tunnelFirstFrame = true;
224 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800225 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800226 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800227 std::unique_ptr<C2Work> work(new C2Work);
228 work->input.ordinal.timestamp = timeUs;
229 work->input.ordinal.frameIndex = mFrameIndex++;
230 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
231 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
232 // Keep client timestamp in customOrdinal
233 work->input.ordinal.customOrdinal = timeUs;
234 work->input.buffers.clear();
235
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700236 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800237 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800238
Pawin Vongmasa36653902018-11-15 00:10:25 -0800239 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700240 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800241 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700242 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800243 return -ENOENT;
244 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700245 // TODO: we want to delay copying buffers.
246 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
247 copy = input->buffers->cloneAndReleaseBuffer(buffer);
248 if (copy != nullptr) {
249 (void)input->extraBuffers.assignSlot(copy);
250 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
251 return UNKNOWN_ERROR;
252 }
253 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
254 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
255 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700256 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700257 } else {
258 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
259 "buffer starvation on component.", mName);
260 }
261 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800262 if (input->frameReassembler) {
263 usesFrameReassembler = true;
264 input->frameReassembler.process(buffer, &items);
265 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900266 int32_t cvo = 0;
267 if (buffer->meta()->findInt32("cvo", &cvo)) {
268 int32_t rotation = cvo % 360;
269 // change rotation to counter-clock wise.
270 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
271
272 Mutexed<OutputSurface>::Locked output(mOutputSurface);
273 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
274 output->rotation[frameIndex] = rotation;
275 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800276 work->input.buffers.push_back(c2buffer);
277 if (encryptedBlock) {
278 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
279 kParamIndexEncryptedBuffer,
280 encryptedBlock->share(0, blockSize, C2Fence())));
281 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700282 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800283 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700284 Mutexed<Input>::Locked input(mInput);
285 if (input->frameReassembler) {
286 usesFrameReassembler = true;
287 // drain any pending items with eos
288 input->frameReassembler.process(buffer, &items);
289 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800290 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800291 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800292 if (usesFrameReassembler) {
293 if (!items.empty()) {
294 items.front()->input.configUpdate = std::move(mParamsToBeSet);
295 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
296 }
297 } else {
298 work->input.flags = (C2FrameData::flags_t)flags;
299 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800300
Wonsik Kime1104ca2020-11-24 15:01:33 -0800301 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200302 if (tunnelFirstFrame) {
303 C2StreamTunnelHoldRender::input tunnelHoldRender{
304 0u /* stream */,
305 C2_TRUE /* value */
306 };
307 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
308 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800309 work->worklets.clear();
310 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800311
Wonsik Kime1104ca2020-11-24 15:01:33 -0800312 items.push_back(std::move(work));
313
314 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800315 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800316 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800317 work.reset(new C2Work);
318 work->input.ordinal.timestamp = timeUs;
319 work->input.ordinal.frameIndex = mFrameIndex++;
320 // WORKAROUND: keep client timestamp in customOrdinal
321 work->input.ordinal.customOrdinal = timeUs;
322 work->input.buffers.clear();
323 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800324 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800325 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800326 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800327 c2_status_t err = C2_OK;
328 if (!items.empty()) {
329 {
330 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
331 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
332 for (const std::unique_ptr<C2Work> &work : items) {
333 watcher->onWorkQueued(
334 work->input.ordinal.frameIndex.peeku(),
335 std::vector(work->input.buffers),
336 now);
337 }
338 }
339 err = mComponent->queue(&items);
340 }
341 if (err != C2_OK) {
342 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
343 for (const std::unique_ptr<C2Work> &work : items) {
344 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
345 }
346 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700347 Mutexed<Input>::Locked input(mInput);
348 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700349 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700350 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700351 } else if (buffer) {
352 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700353 }
354 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
355 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800356 }
357
358 feedInputBufferIfAvailableInternal();
359 return err;
360}
361
362status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
363 QueueGuard guard(mSync);
364 if (!guard.isRunning()) {
365 ALOGD("[%s] setParameters is only supported in the running state.", mName);
366 return -ENOSYS;
367 }
368 mParamsToBeSet.insert(mParamsToBeSet.end(),
369 std::make_move_iterator(params.begin()),
370 std::make_move_iterator(params.end()));
371 params.clear();
372 return OK;
373}
374
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800375status_t CCodecBufferChannel::attachBuffer(
376 const std::shared_ptr<C2Buffer> &c2Buffer,
377 const sp<MediaCodecBuffer> &buffer) {
378 if (!buffer->copy(c2Buffer)) {
379 return -ENOSYS;
380 }
381 return OK;
382}
383
384void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
385 if (!mDecryptDestination || mDecryptDestination->size() < size) {
386 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
387 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
388 mCrypto->unsetHeap(mHeapSeqNum);
389 }
390 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
391 if (mCrypto) {
392 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
393 }
394 }
395}
396
397int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
398 CHECK(mCrypto);
399 auto it = mHeapSeqNumMap.find(memory);
400 int32_t heapSeqNum = -1;
401 if (it == mHeapSeqNumMap.end()) {
402 heapSeqNum = mCrypto->setHeap(memory);
403 mHeapSeqNumMap.emplace(memory, heapSeqNum);
404 } else {
405 heapSeqNum = it->second;
406 }
407 return heapSeqNum;
408}
409
410status_t CCodecBufferChannel::attachEncryptedBuffer(
411 const sp<hardware::HidlMemory> &memory,
412 bool secure,
413 const uint8_t *key,
414 const uint8_t *iv,
415 CryptoPlugin::Mode mode,
416 CryptoPlugin::Pattern pattern,
417 size_t offset,
418 const CryptoPlugin::SubSample *subSamples,
419 size_t numSubSamples,
420 const sp<MediaCodecBuffer> &buffer) {
421 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
422 static const C2MemoryUsage kDefaultReadWriteUsage{
423 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
424
425 size_t size = 0;
426 for (size_t i = 0; i < numSubSamples; ++i) {
427 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
428 }
429 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
430 std::shared_ptr<C2LinearBlock> block;
431 c2_status_t err = pool->fetchLinearBlock(
432 size,
433 secure ? kSecureUsage : kDefaultReadWriteUsage,
434 &block);
435 if (err != C2_OK) {
436 return NO_MEMORY;
437 }
438 if (!secure) {
439 ensureDecryptDestination(size);
440 }
441 ssize_t result = -1;
442 ssize_t codecDataOffset = 0;
443 if (mCrypto) {
444 AString errorDetailMsg;
445 int32_t heapSeqNum = getHeapSeqNum(memory);
446 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
447 hardware::drm::V1_0::DestinationBuffer dst;
448 if (secure) {
449 dst.type = DrmBufferType::NATIVE_HANDLE;
450 dst.secureMemory = hardware::hidl_handle(block->handle());
451 } else {
452 dst.type = DrmBufferType::SHARED_MEMORY;
453 IMemoryToSharedBuffer(
454 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
455 }
456 result = mCrypto->decrypt(
457 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
458 dst, &errorDetailMsg);
459 if (result < 0) {
460 return result;
461 }
462 if (dst.type == DrmBufferType::SHARED_MEMORY) {
463 C2WriteView view = block->map().get();
464 if (view.error() != C2_OK) {
465 return false;
466 }
467 if (view.size() < result) {
468 return false;
469 }
470 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
471 }
472 } else {
473 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
474 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
475 hidl_vec<SubSample> hidlSubSamples;
476 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
477
478 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
479 hardware::cas::native::V1_0::DestinationBuffer dst;
480 if (secure) {
481 dst.type = BufferType::NATIVE_HANDLE;
482 dst.secureMemory = hardware::hidl_handle(block->handle());
483 } else {
484 dst.type = BufferType::SHARED_MEMORY;
485 dst.nonsecureMemory = src;
486 }
487
488 CasStatus status = CasStatus::OK;
489 hidl_string detailedError;
490 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
491
492 if (key != nullptr) {
493 sctrl = (ScramblingControl)key[0];
494 // Adjust for the PES offset
495 codecDataOffset = key[2] | (key[3] << 8);
496 }
497
498 auto returnVoid = mDescrambler->descramble(
499 sctrl,
500 hidlSubSamples,
501 src,
502 0,
503 dst,
504 0,
505 [&status, &result, &detailedError] (
506 CasStatus _status, uint32_t _bytesWritten,
507 const hidl_string& _detailedError) {
508 status = _status;
509 result = (ssize_t)_bytesWritten;
510 detailedError = _detailedError;
511 });
512
513 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
514 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
515 mName, returnVoid.description().c_str(), status, result);
516 return UNKNOWN_ERROR;
517 }
518
519 if (result < codecDataOffset) {
520 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
521 return BAD_VALUE;
522 }
523 }
524 if (!secure) {
525 C2WriteView view = block->map().get();
526 if (view.error() != C2_OK) {
527 return UNKNOWN_ERROR;
528 }
529 if (view.size() < result) {
530 return UNKNOWN_ERROR;
531 }
532 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
533 }
534 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
535 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
536 if (!buffer->copy(c2Buffer)) {
537 return -ENOSYS;
538 }
539 return OK;
540}
541
Pawin Vongmasa36653902018-11-15 00:10:25 -0800542status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
543 QueueGuard guard(mSync);
544 if (!guard.isRunning()) {
545 ALOGD("[%s] No more buffers should be queued at current state.", mName);
546 return -ENOSYS;
547 }
548 return queueInputBufferInternal(buffer);
549}
550
551status_t CCodecBufferChannel::queueSecureInputBuffer(
552 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
553 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
554 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
555 AString *errorDetailMsg) {
556 QueueGuard guard(mSync);
557 if (!guard.isRunning()) {
558 ALOGD("[%s] No more buffers should be queued at current state.", mName);
559 return -ENOSYS;
560 }
561
562 if (!hasCryptoOrDescrambler()) {
563 return -ENOSYS;
564 }
565 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
566
Sungtak Lee04b30352020-07-27 13:57:25 -0700567 std::shared_ptr<C2LinearBlock> block;
568 size_t allocSize = buffer->size();
569 size_t bufferSize = 0;
570 c2_status_t blockRes = C2_OK;
571 bool copied = false;
572 if (mSendEncryptedInfoBuffer) {
573 static const C2MemoryUsage kDefaultReadWriteUsage{
574 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
575 constexpr int kAllocGranule0 = 1024 * 64;
576 constexpr int kAllocGranule1 = 1024 * 1024;
577 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
578 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
579 if (allocSize <= kAllocGranule1) {
580 bufferSize = align(allocSize, kAllocGranule0);
581 } else {
582 bufferSize = align(allocSize, kAllocGranule1);
583 }
584 blockRes = pool->fetchLinearBlock(
585 bufferSize, kDefaultReadWriteUsage, &block);
586
587 if (blockRes == C2_OK) {
588 C2WriteView view = block->map().get();
589 if (view.error() == C2_OK && view.size() == bufferSize) {
590 copied = true;
591 // TODO: only copy clear sections
592 memcpy(view.data(), buffer->data(), allocSize);
593 }
594 }
595 }
596
597 if (!copied) {
598 block.reset();
599 }
600
Pawin Vongmasa36653902018-11-15 00:10:25 -0800601 ssize_t result = -1;
602 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700603 if (numSubSamples == 1
604 && subSamples[0].mNumBytesOfClearData == 0
605 && subSamples[0].mNumBytesOfEncryptedData == 0) {
606 // We don't need to go through crypto or descrambler if the input is empty.
607 result = 0;
608 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700609 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800610 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700611 destination.type = DrmBufferType::NATIVE_HANDLE;
612 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800613 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700614 destination.type = DrmBufferType::SHARED_MEMORY;
615 IMemoryToSharedBuffer(
616 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800617 }
Robert Shih895fba92019-07-16 16:29:44 -0700618 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800619 encryptedBuffer->fillSourceBuffer(&source);
620 result = mCrypto->decrypt(
621 key, iv, mode, pattern, source, buffer->offset(),
622 subSamples, numSubSamples, destination, errorDetailMsg);
623 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700624 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800625 return result;
626 }
Robert Shih895fba92019-07-16 16:29:44 -0700627 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800628 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
629 }
630 } else {
631 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
632 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
633 hidl_vec<SubSample> hidlSubSamples;
634 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
635
636 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
637 encryptedBuffer->fillSourceBuffer(&srcBuffer);
638
639 DestinationBuffer dstBuffer;
640 if (secure) {
641 dstBuffer.type = BufferType::NATIVE_HANDLE;
642 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
643 } else {
644 dstBuffer.type = BufferType::SHARED_MEMORY;
645 dstBuffer.nonsecureMemory = srcBuffer;
646 }
647
648 CasStatus status = CasStatus::OK;
649 hidl_string detailedError;
650 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
651
652 if (key != nullptr) {
653 sctrl = (ScramblingControl)key[0];
654 // Adjust for the PES offset
655 codecDataOffset = key[2] | (key[3] << 8);
656 }
657
658 auto returnVoid = mDescrambler->descramble(
659 sctrl,
660 hidlSubSamples,
661 srcBuffer,
662 0,
663 dstBuffer,
664 0,
665 [&status, &result, &detailedError] (
666 CasStatus _status, uint32_t _bytesWritten,
667 const hidl_string& _detailedError) {
668 status = _status;
669 result = (ssize_t)_bytesWritten;
670 detailedError = _detailedError;
671 });
672
673 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
674 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
675 mName, returnVoid.description().c_str(), status, result);
676 return UNKNOWN_ERROR;
677 }
678
679 if (result < codecDataOffset) {
680 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
681 return BAD_VALUE;
682 }
683
684 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
685
686 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
687 encryptedBuffer->copyDecryptedContentFromMemory(result);
688 }
689 }
690
691 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700692
693 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800694}
695
696void CCodecBufferChannel::feedInputBufferIfAvailable() {
697 QueueGuard guard(mSync);
698 if (!guard.isRunning()) {
699 ALOGV("[%s] We're not running --- no input buffer reported", mName);
700 return;
701 }
702 feedInputBufferIfAvailableInternal();
703}
704
705void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900706 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800707 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700708 }
709 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700710 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700711 if (!output->buffers ||
712 output->buffers->hasPending() ||
Wonsik Kim0487b782020-10-28 11:45:50 -0700713 output->buffers->numActiveSlots() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800714 return;
715 }
716 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700717 size_t numActiveSlots = 0;
718 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800719 sp<MediaCodecBuffer> inBuffer;
720 size_t index;
721 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700722 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700723 numActiveSlots = input->buffers->numActiveSlots();
724 if (numActiveSlots >= input->numSlots) {
725 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800726 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700727 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800728 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800729 break;
730 }
731 }
732 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
733 mCallback->onInputBufferAvailable(index, inBuffer);
734 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700735 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800736}
737
738status_t CCodecBufferChannel::renderOutputBuffer(
739 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800740 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800741 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800742 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800743 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700744 Mutexed<Output>::Locked output(mOutput);
745 if (output->buffers) {
746 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800747 }
748 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800749 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
750 // set to true.
751 sendOutputBuffers();
752 // input buffer feeding may have been gated by pending output buffers
753 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800754 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800755 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700756 std::call_once(mRenderWarningFlag, [this] {
757 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
758 "timestamp or render=true with non-video buffers. Apps should "
759 "call releaseOutputBuffer() with render=false for those.",
760 mName);
761 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800762 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800763 return INVALID_OPERATION;
764 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800765
766#if 0
767 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
768 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
769 for (const std::shared_ptr<const C2Info> &info : infoParams) {
770 AString res;
771 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
772 if (ix) res.append(", ");
773 res.append(*((int32_t*)info.get() + (ix / 4)));
774 }
775 ALOGV(" [%s]", res.c_str());
776 }
777#endif
778 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
779 std::static_pointer_cast<const C2StreamRotationInfo::output>(
780 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
781 bool flip = rotation && (rotation->flip & 1);
782 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900783
784 {
785 Mutexed<OutputSurface>::Locked output(mOutputSurface);
786 if (output->surface == nullptr) {
787 ALOGI("[%s] cannot render buffer without surface", mName);
788 return OK;
789 }
790 int64_t frameIndex;
791 buffer->meta()->findInt64("frameIndex", &frameIndex);
792 if (output->rotation.count(frameIndex) != 0) {
793 auto it = output->rotation.find(frameIndex);
794 quarters = (it->second / 90) & 3;
795 output->rotation.erase(it);
796 }
797 }
798
Pawin Vongmasa36653902018-11-15 00:10:25 -0800799 uint32_t transform = 0;
800 switch (quarters) {
801 case 0: // no rotation
802 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
803 break;
804 case 1: // 90 degrees counter-clockwise
805 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
806 : HAL_TRANSFORM_ROT_270;
807 break;
808 case 2: // 180 degrees
809 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
810 break;
811 case 3: // 90 degrees clockwise
812 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
813 : HAL_TRANSFORM_ROT_90;
814 break;
815 }
816
817 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
818 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
819 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
820 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
821 if (surfaceScaling) {
822 videoScalingMode = surfaceScaling->value;
823 }
824
825 // Use dataspace from format as it has the default aspects already applied
826 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
827 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
828
829 // HDR static info
830 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
831 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
832 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
833
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800834 // HDR10 plus info
835 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
836 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
837 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800838 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
839 hdr10PlusInfo.reset();
840 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800841
Wonsik Kima79c5522022-01-18 16:29:24 -0800842 // HDR dynamic info
843 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
844 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
845 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
846 // TODO: make this sticky & enable unset
847 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
848 hdrDynamicInfo.reset();
849 }
850
851 if (hdr10PlusInfo) {
852 // C2StreamHdr10PlusInfo is deprecated; components should use
853 // C2StreamHdrDynamicMetadataInfo
854 // TODO: #metric
855 if (hdrDynamicInfo) {
856 // It is unexpected that C2StreamHdr10PlusInfo and
857 // C2StreamHdrDynamicMetadataInfo is both present.
858 // C2StreamHdrDynamicMetadataInfo takes priority.
859 // TODO: #metric
860 } else {
861 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
862 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
863 hdr10PlusInfo->flexCount(),
864 0u,
865 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
866 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
867 hdrDynamicInfo = info;
868 }
869 }
870
Pawin Vongmasa36653902018-11-15 00:10:25 -0800871 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
872 if (blocks.size() != 1u) {
873 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
874 return UNKNOWN_ERROR;
875 }
876 const C2ConstGraphicBlock &block = blocks.front();
877
878 // TODO: revisit this after C2Fence implementation.
879 android::IGraphicBufferProducer::QueueBufferInput qbi(
880 timestampNs,
881 false, // droppable
882 dataSpace,
883 Rect(blocks.front().crop().left,
884 blocks.front().crop().top,
885 blocks.front().crop().right(),
886 blocks.front().crop().bottom()),
887 videoScalingMode,
888 transform,
889 Fence::NO_FENCE, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800890 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800891 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800892 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800893 // If mastering max and min luminance fields are 0, do not use them.
894 // It indicates the value may not be present in the stream.
895 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
896 hdrStaticInfo->mastering.minLuminance > 0.0f) {
897 struct android_smpte2086_metadata smpte2086_meta = {
898 .displayPrimaryRed = {
899 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
900 },
901 .displayPrimaryGreen = {
902 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
903 },
904 .displayPrimaryBlue = {
905 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
906 },
907 .whitePoint = {
908 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
909 },
910 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
911 .minLuminance = hdrStaticInfo->mastering.minLuminance,
912 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800913 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800914 hdr.smpte2086 = smpte2086_meta;
915 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700916 // If the content light level fields are 0, do not use them, it
917 // indicates the value may not be present in the stream.
918 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
919 struct android_cta861_3_metadata cta861_meta = {
920 .maxContentLightLevel = hdrStaticInfo->maxCll,
921 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
922 };
923 hdr.validTypes |= HdrMetadata::CTA861_3;
924 hdr.cta8613 = cta861_meta;
925 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800926 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800927 if (hdrDynamicInfo
928 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800929 hdr.validTypes |= HdrMetadata::HDR10PLUS;
930 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800931 hdrDynamicInfo->m.data,
932 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800933 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800934 qbi.setHdrMetadata(hdr);
Wonsik Kima79c5522022-01-18 16:29:24 -0800935
936 SetHdrMetadataToGralloc4Handle(hdrStaticInfo, hdrDynamicInfo, block.handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800937 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800938 // we don't have dirty regions
939 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800940 android::IGraphicBufferProducer::QueueBufferOutput qbo;
941 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
942 if (result != OK) {
943 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800944 if (result == NO_INIT) {
945 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
946 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800947 return result;
948 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800949
950 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
951 ALOGD("[%s] queue buffer successful", mName);
952 } else {
953 ALOGV("[%s] queue buffer successful", mName);
954 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800955
956 int64_t mediaTimeUs = 0;
957 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
958 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
959
960 return OK;
961}
962
963status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
964 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
965 bool released = false;
966 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700967 Mutexed<Input>::Locked input(mInput);
968 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800969 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800970 }
971 }
972 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700973 Mutexed<Output>::Locked output(mOutput);
974 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800975 released = true;
976 }
977 }
978 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800979 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800980 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800981 } else {
982 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
983 }
984 return OK;
985}
986
987void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
988 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700989 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800990
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700991 if (!input->buffers->isArrayMode()) {
992 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800993 }
994
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700995 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800996}
997
998void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
999 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001000 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001001
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001002 if (!output->buffers->isArrayMode()) {
1003 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001004 }
1005
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001006 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001007}
1008
1009status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001010 const sp<AMessage> &inputFormat,
1011 const sp<AMessage> &outputFormat,
1012 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001013 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1014 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001015 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001016 C2PortReorderBufferDepthTuning::output reorderDepth;
1017 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001018 C2PortActualDelayTuning::input inputDelay(0);
1019 C2PortActualDelayTuning::output outputDelay(0);
1020 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001021 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001022
Pawin Vongmasa36653902018-11-15 00:10:25 -08001023 c2_status_t err = mComponent->query(
1024 {
1025 &iStreamFormat,
1026 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001027 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001028 &reorderDepth,
1029 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001030 &inputDelay,
1031 &pipelineDelay,
1032 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001033 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001034 },
1035 {},
1036 C2_DONT_BLOCK,
1037 nullptr);
1038 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001039 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001040 return UNKNOWN_ERROR;
1041 }
1042 } else if (err != C2_OK) {
1043 return UNKNOWN_ERROR;
1044 }
1045
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001046 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1047 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1048 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1049
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001050 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1051 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001052
Pawin Vongmasa36653902018-11-15 00:10:25 -08001053 // TODO: get this from input format
1054 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1055
Sungtak Lee04b30352020-07-27 13:57:25 -07001056 // secure mode is a static parameter (shall not change in the executing state)
1057 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1058
Pawin Vongmasa36653902018-11-15 00:10:25 -08001059 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001060 int poolMask = GetCodec2PoolMask();
1061 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001062
1063 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001064 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001065 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001066 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1067 API_REFLECTION |
1068 API_VALUES |
1069 API_CURRENT_VALUES |
1070 API_DEPENDENCY |
1071 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001072 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1073 C2StreamSampleRateInfo::input sampleRate(0u);
1074 C2StreamChannelCountInfo::input channelCount(0u);
1075 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001076 std::shared_ptr<C2BlockPool> pool;
1077 {
1078 Mutexed<BlockPools>::Locked pools(mBlockPools);
1079
1080 // set default allocator ID.
1081 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001082 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001083
1084 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1085 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1086 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001087 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001088 std::vector<C2Param *> stackParams({&featuresSetting});
1089 if (audioEncoder) {
1090 stackParams.push_back(&encoderFrameSize);
1091 stackParams.push_back(&sampleRate);
1092 stackParams.push_back(&channelCount);
1093 stackParams.push_back(&pcmEncoding);
1094 } else {
1095 encoderFrameSize.invalidate();
1096 sampleRate.invalidate();
1097 channelCount.invalidate();
1098 pcmEncoding.invalidate();
1099 }
1100 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001101 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1102 C2_DONT_BLOCK,
1103 &params);
1104 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1105 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1106 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001107 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001108 C2PortAllocatorsTuning::input *inputAllocators =
1109 C2PortAllocatorsTuning::input::From(params[0].get());
1110 if (inputAllocators && inputAllocators->flexCount() > 0) {
1111 std::shared_ptr<C2Allocator> allocator;
1112 // verify allocator IDs and resolve default allocator
1113 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1114 if (allocator) {
1115 pools->inputAllocatorId = allocator->getId();
1116 } else {
1117 ALOGD("[%s] component requested invalid input allocator ID %u",
1118 mName, inputAllocators->m.values[0]);
1119 }
1120 }
1121 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001122 if (featuresSetting) {
1123 apiFeatures = featuresSetting.value;
1124 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001125
1126 // TODO: use C2Component wrapper to associate this pool with ourselves
1127 if ((poolMask >> pools->inputAllocatorId) & 1) {
1128 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1129 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1130 mName, pools->inputAllocatorId,
1131 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1132 asString(err), err);
1133 } else {
1134 err = C2_NOT_FOUND;
1135 }
1136 if (err != C2_OK) {
1137 C2BlockPool::local_id_t inputPoolId =
1138 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1139 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1140 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1141 mName, (unsigned long long)inputPoolId,
1142 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1143 asString(err), err);
1144 if (err != C2_OK) {
1145 return NO_MEMORY;
1146 }
1147 }
1148 pools->inputPool = pool;
1149 }
1150
Wonsik Kim51051262018-11-28 13:59:05 -08001151 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001152 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001153 input->inputDelay = inputDelayValue;
1154 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001155 input->numSlots = numInputSlots;
1156 input->extraBuffers.flush();
1157 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001158 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001159 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1160 input->frameReassembler.init(
1161 pool,
1162 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1163 encoderFrameSize.value,
1164 sampleRate.value,
1165 channelCount.value,
1166 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1167 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001168 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1169 // For encrypted content, framework decrypts source buffer (ashmem) into
1170 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001171 if (!buffersBoundToCodec
1172 && !input->frameReassembler
1173 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001174 input->buffers.reset(new SlotInputBuffers(mName));
1175 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001176 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001177 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001178 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001179 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001180 // This is to ensure buffers do not get released prematurely.
1181 // TODO: handle this without going into array mode
1182 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001183 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001184 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001185 }
1186 } else {
1187 if (hasCryptoOrDescrambler()) {
1188 int32_t capacity = kLinearBufferSize;
1189 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1190 if ((size_t)capacity > kMaxLinearBufferSize) {
1191 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1192 capacity = kMaxLinearBufferSize;
1193 }
1194 if (mDealer == nullptr) {
1195 mDealer = new MemoryDealer(
1196 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001197 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001198 "EncryptedLinearInputBuffers");
1199 mDecryptDestination = mDealer->allocate((size_t)capacity);
1200 }
1201 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001202 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1203 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001204 } else {
1205 mHeapSeqNum = -1;
1206 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001207 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001208 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001209 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001210 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001211 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001212 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001213 }
1214 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001215 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001216
1217 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001218 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001219 } else {
1220 // TODO: error
1221 }
Wonsik Kim51051262018-11-28 13:59:05 -08001222
1223 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001224 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001225 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001226 }
1227
1228 if (outputFormat != nullptr) {
1229 sp<IGraphicBufferProducer> outputSurface;
1230 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001231 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001232 {
1233 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001234 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001235 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001236 outputSurface = output->surface ?
1237 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001238 if (outputSurface) {
1239 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1240 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001241 outputGeneration = output->generation;
1242 }
1243
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001244 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001245 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001246 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001247
1248 {
1249 Mutexed<BlockPools>::Locked pools(mBlockPools);
1250
David Stevensc3fbb282021-01-18 18:11:20 +09001251 prevOutputPoolId = pools->outputPoolId;
1252
Pawin Vongmasa36653902018-11-15 00:10:25 -08001253 // set default allocator ID.
1254 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001255 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001256
1257 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1258 // unsuccessful.
1259 std::vector<std::unique_ptr<C2Param>> params;
1260 err = mComponent->query({ },
1261 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1262 C2_DONT_BLOCK,
1263 &params);
1264 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1265 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1266 mName, params.size(), asString(err), err);
1267 } else if (err == C2_OK && params.size() == 1) {
1268 C2PortAllocatorsTuning::output *outputAllocators =
1269 C2PortAllocatorsTuning::output::From(params[0].get());
1270 if (outputAllocators && outputAllocators->flexCount() > 0) {
1271 std::shared_ptr<C2Allocator> allocator;
1272 // verify allocator IDs and resolve default allocator
1273 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1274 if (allocator) {
1275 pools->outputAllocatorId = allocator->getId();
1276 } else {
1277 ALOGD("[%s] component requested invalid output allocator ID %u",
1278 mName, outputAllocators->m.values[0]);
1279 }
1280 }
1281 }
1282
1283 // use bufferqueue if outputting to a surface.
1284 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1285 // if unsuccessful.
1286 if (outputSurface) {
1287 params.clear();
1288 err = mComponent->query({ },
1289 { C2PortSurfaceAllocatorTuning::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 surface allocator returned %zu params => %s (%u)",
1294 mName, params.size(), asString(err), err);
1295 } else if (err == C2_OK && params.size() == 1) {
1296 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1297 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1298 if (surfaceAllocator) {
1299 std::shared_ptr<C2Allocator> allocator;
1300 // verify allocator IDs and resolve default allocator
1301 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1302 if (allocator) {
1303 pools->outputAllocatorId = allocator->getId();
1304 } else {
1305 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1306 mName, surfaceAllocator->value);
1307 err = C2_BAD_VALUE;
1308 }
1309 }
1310 }
1311 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1312 && err != C2_OK
1313 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1314 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1315 }
1316 }
1317
1318 if ((poolMask >> pools->outputAllocatorId) & 1) {
1319 err = mComponent->createBlockPool(
1320 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1321 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1322 mName, pools->outputAllocatorId,
1323 (unsigned long long)pools->outputPoolId,
1324 asString(err));
1325 } else {
1326 err = C2_NOT_FOUND;
1327 }
1328 if (err != C2_OK) {
1329 // use basic pool instead
1330 pools->outputPoolId =
1331 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1332 }
1333
1334 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1335 // component.
1336 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1337 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1338
1339 std::vector<std::unique_ptr<C2SettingResult>> failures;
1340 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1341 ALOGD("[%s] Configured output block pool ids %llu => %s",
1342 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1343 outputPoolId_ = pools->outputPoolId;
1344 }
1345
David Stevensc3fbb282021-01-18 18:11:20 +09001346 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1347 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1348 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1349 if (err != C2_OK) {
1350 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1351 (unsigned long long) prevOutputPoolId, asString(err), err);
1352 }
1353 }
1354
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001355 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001356 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001357 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001358 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001359 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001360 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001361 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001362 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001363 }
1364 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001365 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001366 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001367 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001368
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001369 output->buffers->clearStash();
1370 if (reorderDepth) {
1371 output->buffers->setReorderDepth(reorderDepth.value);
1372 }
1373 if (reorderKey) {
1374 output->buffers->setReorderKey(reorderKey.value);
1375 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001376
1377 // Try to set output surface to created block pool if given.
1378 if (outputSurface) {
1379 mComponent->setOutputSurface(
1380 outputPoolId_,
1381 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001382 outputGeneration,
1383 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001384 } else {
1385 // configure CPU read consumer usage
1386 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1387 std::vector<std::unique_ptr<C2SettingResult>> failures;
1388 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1389 // do not print error message for now as most components may not yet
1390 // support this setting
1391 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1392 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001393 }
1394
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001395 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001396 if (buffersBoundToCodec) {
1397 // WORKAROUND: if we're using early CSD workaround we convert to
1398 // array mode, to appease apps assuming the output
1399 // buffers to be of the same size.
1400 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1401 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001402
1403 int32_t channelCount;
1404 int32_t sampleRate;
1405 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1406 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1407 int32_t delay = 0;
1408 int32_t padding = 0;;
1409 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1410 delay = 0;
1411 }
1412 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1413 padding = 0;
1414 }
1415 if (delay || padding) {
1416 // We need write access to the buffers, and we're already in
1417 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001418 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001419 }
1420 }
1421 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001422
1423 int32_t tunneled = 0;
1424 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1425 tunneled = 0;
1426 }
1427 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001428 }
1429
1430 // Set up pipeline control. This has to be done after mInputBuffers and
1431 // mOutputBuffers are initialized to make sure that lingering callbacks
1432 // about buffers from the previous generation do not interfere with the
1433 // newly initialized pipeline capacity.
1434
Wonsik Kim62545252021-01-20 11:25:41 -08001435 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001436 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001437 watcher->inputDelay(inputDelayValue)
1438 .pipelineDelay(pipelineDelayValue)
1439 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001440 .smoothnessFactor(kSmoothnessFactor);
1441 watcher->flush();
1442 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001443
1444 mInputMetEos = false;
1445 mSync.start();
1446 return OK;
1447}
1448
1449status_t CCodecBufferChannel::requestInitialInputBuffers() {
1450 if (mInputSurface) {
1451 return OK;
1452 }
1453
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001454 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001455 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1456 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1457 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001458 return UNKNOWN_ERROR;
1459 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001460 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001461
1462 struct ClientInputBuffer {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001463 size_t index;
1464 sp<MediaCodecBuffer> buffer;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001465 size_t capacity;
1466 };
1467 std::list<ClientInputBuffer> clientInputBuffers;
1468
1469 {
1470 Mutexed<Input>::Locked input(mInput);
1471 while (clientInputBuffers.size() < numInputSlots) {
1472 ClientInputBuffer clientInputBuffer;
1473 if (!input->buffers->requestNewBuffer(&clientInputBuffer.index,
1474 &clientInputBuffer.buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001475 break;
1476 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001477 clientInputBuffer.capacity = clientInputBuffer.buffer->capacity();
1478 clientInputBuffers.emplace_back(std::move(clientInputBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001479 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001480 }
1481 if (clientInputBuffers.empty()) {
1482 ALOGW("[%s] start: cannot allocate memory at all", mName);
1483 return NO_MEMORY;
1484 } else if (clientInputBuffers.size() < numInputSlots) {
1485 ALOGD("[%s] start: cannot allocate memory for all slots, "
1486 "only %zu buffers allocated",
1487 mName, clientInputBuffers.size());
1488 } else {
1489 ALOGV("[%s] %zu initial input buffers available",
1490 mName, clientInputBuffers.size());
1491 }
1492 // Sort input buffers by their capacities in increasing order.
1493 clientInputBuffers.sort(
1494 [](const ClientInputBuffer& a, const ClientInputBuffer& b) {
1495 return a.capacity < b.capacity;
1496 });
1497
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001498 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1499 mFlushedConfigs.lock()->swap(flushedConfigs);
1500 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001501 {
1502 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1503 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1504 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1505 watcher->onWorkQueued(
1506 work->input.ordinal.frameIndex.peeku(),
1507 std::vector(work->input.buffers),
1508 now);
1509 }
1510 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001511 err = mComponent->queue(&flushedConfigs);
1512 if (err != C2_OK) {
1513 ALOGW("[%s] Error while queueing a flushed config", mName);
1514 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001515 }
1516 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001517 if (oStreamFormat.value == C2BufferData::LINEAR &&
1518 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
1519 sp<MediaCodecBuffer> buffer = clientInputBuffers.front().buffer;
1520 // WORKAROUND: Some apps expect CSD available without queueing
1521 // any input. Queue an empty buffer to get the CSD.
1522 buffer->setRange(0, 0);
1523 buffer->meta()->clear();
1524 buffer->meta()->setInt64("timeUs", 0);
1525 if (queueInputBufferInternal(buffer) != OK) {
1526 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1527 mName);
1528 return UNKNOWN_ERROR;
1529 }
1530 clientInputBuffers.pop_front();
1531 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001532
1533 for (const ClientInputBuffer& clientInputBuffer: clientInputBuffers) {
1534 mCallback->onInputBufferAvailable(
1535 clientInputBuffer.index,
1536 clientInputBuffer.buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001537 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001538
Pawin Vongmasa36653902018-11-15 00:10:25 -08001539 return OK;
1540}
1541
1542void CCodecBufferChannel::stop() {
1543 mSync.stop();
1544 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001545}
1546
Wonsik Kim936a89c2020-05-08 16:07:50 -07001547void CCodecBufferChannel::reset() {
1548 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001549 if (mInputSurface != nullptr) {
1550 mInputSurface.reset();
1551 }
1552 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001553 {
1554 Mutexed<Input>::Locked input(mInput);
1555 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001556 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001557 }
1558 {
1559 Mutexed<Output>::Locked output(mOutput);
1560 output->buffers.reset();
1561 }
1562}
1563
1564void CCodecBufferChannel::release() {
1565 mComponent.reset();
1566 mInputAllocator.reset();
1567 mOutputSurface.lock()->surface.clear();
1568 {
1569 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1570 blockPools->inputPool.reset();
1571 blockPools->outputPoolIntf.reset();
1572 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001573 setCrypto(nullptr);
1574 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001575}
1576
Pawin Vongmasa36653902018-11-15 00:10:25 -08001577void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1578 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001579 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001580 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001581 {
1582 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1583 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1584 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1585 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1586 watcher->onWorkDone(frameIndex);
1587 continue;
1588 }
1589 if (work->input.buffers.empty()
1590 || work->input.buffers.front() == nullptr
1591 || work->input.buffers.front()->data().linearBlocks().empty()) {
1592 ALOGD("[%s] no linear codec config data found", mName);
1593 watcher->onWorkDone(frameIndex);
1594 continue;
1595 }
1596 std::unique_ptr<C2Work> copy(new C2Work);
1597 copy->input.flags = C2FrameData::flags_t(
1598 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1599 copy->input.ordinal = work->input.ordinal;
1600 copy->input.ordinal.frameIndex = mFrameIndex++;
1601 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1602 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1603 }
1604 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1605 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1606 }
1607 copy->input.infoBuffers.insert(
1608 copy->input.infoBuffers.begin(),
1609 work->input.infoBuffers.begin(),
1610 work->input.infoBuffers.end());
1611 copy->worklets.emplace_back(new C2Worklet);
1612 configs.push_back(std::move(copy));
1613 watcher->onWorkDone(frameIndex);
1614 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001615 }
1616 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001617 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001618 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001619 Mutexed<Input>::Locked input(mInput);
1620 input->buffers->flush();
1621 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001622 }
1623 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001624 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001625 if (output->buffers) {
1626 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001627 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001628 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001629 }
1630}
1631
1632void CCodecBufferChannel::onWorkDone(
1633 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001634 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001635 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001636 feedInputBufferIfAvailable();
1637 }
1638}
1639
1640void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001641 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001642 if (mInputSurface) {
1643 return;
1644 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001645 std::shared_ptr<C2Buffer> buffer =
1646 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001647 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001648 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001649 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001650 if (input->lastFlushIndex >= frameIndex) {
1651 ALOGD("[%s] Ignoring stale input buffer done callback: "
1652 "last flush index = %lld, frameIndex = %lld",
1653 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1654 } else {
1655 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1656 if (!newInputSlotAvailable) {
1657 (void)input->extraBuffers.expireComponentBuffer(buffer);
1658 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001659 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001660 }
1661 if (newInputSlotAvailable) {
1662 feedInputBufferIfAvailable();
1663 }
1664}
1665
1666bool CCodecBufferChannel::handleWork(
1667 std::unique_ptr<C2Work> work,
1668 const sp<AMessage> &outputFormat,
1669 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001670 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001671 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001672 if (!output->buffers) {
1673 return false;
1674 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001675 }
1676
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001677 // Whether the output buffer should be reported to the client or not.
1678 bool notifyClient = false;
1679
1680 if (work->result == C2_OK){
1681 notifyClient = true;
1682 } else if (work->result == C2_NOT_FOUND) {
1683 ALOGD("[%s] flushed work; ignored.", mName);
1684 } else {
1685 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1686 // the config update.
1687 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1688 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1689 return false;
1690 }
1691
1692 if ((work->input.ordinal.frameIndex -
1693 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001694 // Discard frames from previous generation.
1695 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001696 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001697 }
1698
Wonsik Kim524b0582019-03-12 11:28:57 -07001699 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001700 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001701 || !(work->worklets.front()->output.flags &
1702 C2FrameData::FLAG_INCOMPLETE))) {
1703 mPipelineWatcher.lock()->onWorkDone(
1704 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001705 }
1706
1707 // NOTE: MediaCodec usage supposedly have only one worklet
1708 if (work->worklets.size() != 1u) {
1709 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1710 mName, work->worklets.size());
1711 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1712 return false;
1713 }
1714
1715 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1716
1717 std::shared_ptr<C2Buffer> buffer;
1718 // NOTE: MediaCodec usage supposedly have only one output stream.
1719 if (worklet->output.buffers.size() > 1u) {
1720 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1721 mName, worklet->output.buffers.size());
1722 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1723 return false;
1724 } else if (worklet->output.buffers.size() == 1u) {
1725 buffer = worklet->output.buffers[0];
1726 if (!buffer) {
1727 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1728 }
1729 }
1730
Wonsik Kim3dedf682021-05-03 10:57:09 -07001731 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1732 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001733 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001734 while (!worklet->output.configUpdate.empty()) {
1735 std::unique_ptr<C2Param> param;
1736 worklet->output.configUpdate.back().swap(param);
1737 worklet->output.configUpdate.pop_back();
1738 switch (param->coreIndex().coreIndex()) {
1739 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1740 C2PortReorderBufferDepthTuning::output reorderDepth;
1741 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001742 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1743 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001744 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001745 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001746 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001747 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1748 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001749 }
1750 break;
1751 }
1752 case C2PortReorderKeySetting::CORE_INDEX: {
1753 C2PortReorderKeySetting::output reorderKey;
1754 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001755 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001756 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1757 mName, reorderKey.value);
1758 } else {
1759 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1760 }
1761 break;
1762 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001763 case C2PortActualDelayTuning::CORE_INDEX: {
1764 if (param->isGlobal()) {
1765 C2ActualPipelineDelayTuning pipelineDelay;
1766 if (pipelineDelay.updateFrom(*param)) {
1767 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1768 mName, pipelineDelay.value);
1769 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001770 (void)mPipelineWatcher.lock()->pipelineDelay(
1771 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001772 }
1773 }
1774 if (param->forInput()) {
1775 C2PortActualDelayTuning::input inputDelay;
1776 if (inputDelay.updateFrom(*param)) {
1777 ALOGV("[%s] onWorkDone: updating input delay %u",
1778 mName, inputDelay.value);
1779 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001780 (void)mPipelineWatcher.lock()->inputDelay(
1781 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001782 }
1783 }
1784 if (param->forOutput()) {
1785 C2PortActualDelayTuning::output outputDelay;
1786 if (outputDelay.updateFrom(*param)) {
1787 ALOGV("[%s] onWorkDone: updating output delay %u",
1788 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001789 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001790 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001791 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001792
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001793 }
1794 }
1795 break;
1796 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001797 case C2PortTunnelSystemTime::CORE_INDEX: {
1798 C2PortTunnelSystemTime::output frameRenderTime;
1799 if (frameRenderTime.updateFrom(*param)) {
1800 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1801 mName, (long long)frameRenderTime.value,
1802 (long long)worklet->output.ordinal.timestamp.peekll());
1803 mCCodecCallback->onOutputFramesRendered(
1804 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1805 }
1806 break;
1807 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001808 case C2StreamTunnelHoldRender::CORE_INDEX: {
1809 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1810 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1811 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1812 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1813 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1814 mCCodecCallback->onFirstTunnelFrameReady();
1815 break;
1816 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001817 default:
1818 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1819 mName, param->index());
1820 break;
1821 }
1822 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001823 if (newInputDelay || newPipelineDelay) {
1824 Mutexed<Input>::Locked input(mInput);
1825 size_t newNumSlots =
1826 newInputDelay.value_or(input->inputDelay) +
1827 newPipelineDelay.value_or(input->pipelineDelay) +
1828 kSmoothnessFactor;
1829 if (input->buffers->isArrayMode()) {
1830 if (input->numSlots >= newNumSlots) {
1831 input->numExtraSlots = 0;
1832 } else {
1833 input->numExtraSlots = newNumSlots - input->numSlots;
1834 }
1835 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1836 mName, input->numExtraSlots);
1837 } else {
1838 input->numSlots = newNumSlots;
1839 }
1840 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001841 size_t numOutputSlots = 0;
1842 uint32_t reorderDepth = 0;
1843 bool outputBuffersChanged = false;
1844 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
1845 Mutexed<Output>::Locked output(mOutput);
1846 if (!output->buffers) {
1847 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001848 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001849 numOutputSlots = output->numSlots;
1850 if (newReorderKey) {
1851 output->buffers->setReorderKey(newReorderKey.value());
1852 }
1853 if (newReorderDepth) {
1854 output->buffers->setReorderDepth(newReorderDepth.value());
1855 }
1856 reorderDepth = output->buffers->getReorderDepth();
1857 if (newOutputDelay) {
1858 output->outputDelay = newOutputDelay.value();
1859 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
1860 if (output->numSlots < numOutputSlots) {
1861 output->numSlots = numOutputSlots;
1862 if (output->buffers->isArrayMode()) {
1863 OutputBuffersArray *array =
1864 (OutputBuffersArray *)output->buffers.get();
1865 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1866 mName, numOutputSlots);
1867 array->grow(numOutputSlots);
1868 outputBuffersChanged = true;
1869 }
1870 }
1871 }
1872 numOutputSlots = output->numSlots;
1873 }
1874 if (outputBuffersChanged) {
1875 mCCodecCallback->onOutputBuffersChanged();
1876 }
1877 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07001878 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07001879 {
1880 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1881 maxDequeueCount = output->maxDequeueBuffers =
1882 numOutputSlots + reorderDepth + kRenderingDepth;
1883 if (output->surface) {
1884 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1885 }
1886 }
1887 if (maxDequeueCount > 0) {
1888 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001889 }
1890 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001891
Pawin Vongmasa36653902018-11-15 00:10:25 -08001892 int32_t flags = 0;
1893 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07001894 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001895 ALOGV("[%s] onWorkDone: output EOS", mName);
1896 }
1897
Pawin Vongmasa36653902018-11-15 00:10:25 -08001898 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1899 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1900 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1901 // shall correspond to the client input timesamp (in customOrdinal). By using the
1902 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1903 // produces multiple output.
1904 c2_cntr64_t timestamp =
1905 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1906 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001907 if (mInputSurface != nullptr) {
1908 // When using input surface we need to restore the original input timestamp.
1909 timestamp = work->input.ordinal.customOrdinal;
1910 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001911 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1912 mName,
1913 work->input.ordinal.customOrdinal.peekll(),
1914 work->input.ordinal.timestamp.peekll(),
1915 worklet->output.ordinal.timestamp.peekll(),
1916 timestamp.peekll());
1917
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001918 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001919 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001920 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001921 if (output->buffers && outputFormat) {
1922 output->buffers->updateSkipCutBuffer(outputFormat);
1923 output->buffers->setFormat(outputFormat);
1924 }
1925 if (!notifyClient) {
1926 return false;
1927 }
1928 size_t index;
1929 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07001930 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001931 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07001932 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001933 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1934
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001935 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001936 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001937 } else {
1938 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001939 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001940 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001941 return false;
1942 }
1943 }
1944
Wonsik Kimec585c32021-10-01 01:11:00 -07001945 bool drop = false;
1946 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
1947 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
1948 drop = true;
1949 }
1950
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001951 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07001952 if (mTunneled && drop && outputFormat) {
1953 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
1954 mName, work->input.ordinal.frameIndex.peekull());
1955 } else {
1956 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1957 mName, work->input.ordinal.frameIndex.peekull());
1958 notifyClient = false;
1959 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001960 }
1961
1962 if (buffer) {
1963 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1964 // TODO: properly translate these to metadata
1965 switch (info->coreIndex().coreIndex()) {
1966 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001967 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07001968 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001969 }
1970 break;
1971 default:
1972 break;
1973 }
1974 }
1975 }
1976
1977 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001978 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07001979 if (!output->buffers) {
1980 return false;
1981 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001982 output->buffers->pushToStash(
1983 buffer,
1984 notifyClient,
1985 timestamp.peek(),
1986 flags,
1987 outputFormat,
1988 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001989 }
1990 sendOutputBuffers();
1991 return true;
1992}
1993
1994void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001995 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001996 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001997 sp<MediaCodecBuffer> outBuffer;
1998 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001999
2000 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002001 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002002 if (!output->buffers) {
2003 return;
2004 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002005 action = output->buffers->popFromStashAndRegister(
2006 &c2Buffer, &index, &outBuffer);
2007 switch (action) {
2008 case OutputBuffers::SKIP:
2009 return;
2010 case OutputBuffers::DISCARD:
2011 break;
2012 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00002013 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002014 mCallback->onOutputBufferAvailable(index, outBuffer);
2015 break;
2016 case OutputBuffers::REALLOCATE:
2017 if (!output->buffers->isArrayMode()) {
2018 output->buffers =
2019 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002020 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002021 static_cast<OutputBuffersArray*>(output->buffers.get())->
2022 realloc(c2Buffer);
2023 output.unlock();
2024 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002025 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002026 case OutputBuffers::RETRY:
2027 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2028 mName);
2029 return;
2030 default:
2031 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2032 "corrupted BufferAction value (%d) "
2033 "returned from popFromStashAndRegister.",
2034 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002035 return;
2036 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002037 }
2038}
2039
2040status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
2041 static std::atomic_uint32_t surfaceGeneration{0};
2042 uint32_t generation = (getpid() << 10) |
2043 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2044 & ((1 << 10) - 1));
2045
2046 sp<IGraphicBufferProducer> producer;
Sungtak Leedb14cba2021-04-10 00:50:23 -07002047 int maxDequeueCount = mOutputSurface.lock()->maxDequeueBuffers;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002048 if (newSurface) {
2049 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002050 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002051 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002052 producer = newSurface->getIGraphicBufferProducer();
2053 producer->setGenerationNumber(generation);
2054 } else {
2055 ALOGE("[%s] setting output surface to null", mName);
2056 return INVALID_OPERATION;
2057 }
2058
2059 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2060 C2BlockPool::local_id_t outputPoolId;
2061 {
2062 Mutexed<BlockPools>::Locked pools(mBlockPools);
2063 outputPoolId = pools->outputPoolId;
2064 outputPoolIntf = pools->outputPoolIntf;
2065 }
2066
2067 if (outputPoolIntf) {
2068 if (mComponent->setOutputSurface(
2069 outputPoolId,
2070 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002071 generation,
2072 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002073 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2074 return INVALID_OPERATION;
2075 }
2076 }
2077
2078 {
2079 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2080 output->surface = newSurface;
2081 output->generation = generation;
2082 }
2083
2084 return OK;
2085}
2086
Wonsik Kimab34ed62019-01-31 15:28:46 -08002087PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002088 // When client pushed EOS, we want all the work to be done quickly.
2089 // Otherwise, component may have stalled work due to input starvation up to
2090 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002091 size_t n = 0;
2092 if (!mInputMetEos) {
2093 size_t outputDelay = mOutput.lock()->outputDelay;
2094 Mutexed<Input>::Locked input(mInput);
2095 n = input->inputDelay + input->pipelineDelay + outputDelay;
2096 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002097 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002098}
2099
Pawin Vongmasa36653902018-11-15 00:10:25 -08002100void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2101 mMetaMode = mode;
2102}
2103
Wonsik Kim596187e2019-10-25 12:44:10 -07002104void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002105 if (mCrypto != nullptr) {
2106 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2107 mCrypto->unsetHeap(entry.second);
2108 }
2109 mHeapSeqNumMap.clear();
2110 if (mHeapSeqNum >= 0) {
2111 mCrypto->unsetHeap(mHeapSeqNum);
2112 mHeapSeqNum = -1;
2113 }
2114 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002115 mCrypto = crypto;
2116}
2117
2118void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2119 mDescrambler = descrambler;
2120}
2121
Pawin Vongmasa36653902018-11-15 00:10:25 -08002122status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2123 // C2_OK is always translated to OK.
2124 if (c2s == C2_OK) {
2125 return OK;
2126 }
2127
2128 // Operation-dependent translation
2129 // TODO: Add as necessary
2130 switch (c2op) {
2131 case C2_OPERATION_Component_start:
2132 switch (c2s) {
2133 case C2_NO_MEMORY:
2134 return NO_MEMORY;
2135 default:
2136 return UNKNOWN_ERROR;
2137 }
2138 default:
2139 break;
2140 }
2141
2142 // Backup operation-agnostic translation
2143 switch (c2s) {
2144 case C2_BAD_INDEX:
2145 return BAD_INDEX;
2146 case C2_BAD_VALUE:
2147 return BAD_VALUE;
2148 case C2_BLOCKING:
2149 return WOULD_BLOCK;
2150 case C2_DUPLICATE:
2151 return ALREADY_EXISTS;
2152 case C2_NO_INIT:
2153 return NO_INIT;
2154 case C2_NO_MEMORY:
2155 return NO_MEMORY;
2156 case C2_NOT_FOUND:
2157 return NAME_NOT_FOUND;
2158 case C2_TIMED_OUT:
2159 return TIMED_OUT;
2160 case C2_BAD_STATE:
2161 case C2_CANCELED:
2162 case C2_CANNOT_DO:
2163 case C2_CORRUPTED:
2164 case C2_OMITTED:
2165 case C2_REFUSED:
2166 return UNKNOWN_ERROR;
2167 default:
2168 return -static_cast<status_t>(c2s);
2169 }
2170}
2171
2172} // namespace android