blob: 5546bd274efc4fb85d467b04c9f22c9bc0db0f12 [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>
47#include <media/stagefright/MediaCodec.h>
48#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070049#include <media/stagefright/SkipCutBuffer.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080050#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070051#include <mediadrm/ICrypto.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080052#include <system/window.h>
53
54#include "CCodecBufferChannel.h"
55#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080056
57namespace android {
58
59using android::base::StringPrintf;
60using hardware::hidl_handle;
61using hardware::hidl_string;
62using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070063using hardware::fromHeap;
64using hardware::HidlMemory;
65
Pawin Vongmasa36653902018-11-15 00:10:25 -080066using namespace hardware::cas::V1_0;
67using namespace hardware::cas::native::V1_0;
68
69using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070070using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080071
Pawin Vongmasa36653902018-11-15 00:10:25 -080072namespace {
73
Wonsik Kim469c8342019-04-11 16:46:09 -070074constexpr size_t kSmoothnessFactor = 4;
75constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080076
Sungtak Leeab6f2f32019-02-15 14:43:51 -080077// This is for keeping IGBP's buffer dropping logic in legacy mode other
78// than making it non-blocking. Do not change this value.
79const static size_t kDequeueTimeoutNs = 0;
80
Pawin Vongmasa36653902018-11-15 00:10:25 -080081} // namespace
82
83CCodecBufferChannel::QueueGuard::QueueGuard(
84 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
85 Mutex::Autolock l(mSync.mGuardLock);
86 // At this point it's guaranteed that mSync is not under state transition,
87 // as we are holding its mutex.
88
89 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
90 if (count->value == -1) {
91 mRunning = false;
92 } else {
93 ++count->value;
94 mRunning = true;
95 }
96}
97
98CCodecBufferChannel::QueueGuard::~QueueGuard() {
99 if (mRunning) {
100 // We are not holding mGuardLock at this point so that QueueSync::stop() can
101 // keep holding the lock until mCount reaches zero.
102 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
103 --count->value;
104 count->cond.broadcast();
105 }
106}
107
108void CCodecBufferChannel::QueueSync::start() {
109 Mutex::Autolock l(mGuardLock);
110 // If stopped, it goes to running state; otherwise no-op.
111 Mutexed<Counter>::Locked count(mCount);
112 if (count->value == -1) {
113 count->value = 0;
114 }
115}
116
117void CCodecBufferChannel::QueueSync::stop() {
118 Mutex::Autolock l(mGuardLock);
119 Mutexed<Counter>::Locked count(mCount);
120 if (count->value == -1) {
121 // no-op
122 return;
123 }
124 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
125 // mCount can only decrement. In other words, threads that acquired the lock
126 // are allowed to finish execution but additional threads trying to acquire
127 // the lock at this point will block, and then get QueueGuard at STOPPED
128 // state.
129 while (count->value != 0) {
130 count.waitForCondition(count->cond);
131 }
132 count->value = -1;
133}
134
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700135// Input
136
137CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
138
Pawin Vongmasa36653902018-11-15 00:10:25 -0800139// CCodecBufferChannel
140
141CCodecBufferChannel::CCodecBufferChannel(
142 const std::shared_ptr<CCodecCallback> &callback)
143 : mHeapSeqNum(-1),
144 mCCodecCallback(callback),
145 mFrameIndex(0u),
146 mFirstValidFrameIndex(0u),
147 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700148 mInputMetEos(false),
149 mSendEncryptedInfoBuffer(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700150 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700151 {
152 Mutexed<Input>::Locked input(mInput);
153 input->buffers.reset(new DummyInputBuffers(""));
154 input->extraBuffers.flush();
155 input->inputDelay = 0u;
156 input->pipelineDelay = 0u;
157 input->numSlots = kSmoothnessFactor;
158 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700159 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700160 }
161 {
162 Mutexed<Output>::Locked output(mOutput);
163 output->outputDelay = 0u;
164 output->numSlots = kSmoothnessFactor;
165 }
David Stevensc3fbb282021-01-18 18:11:20 +0900166 {
167 Mutexed<BlockPools>::Locked pools(mBlockPools);
168 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
169 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800170}
171
172CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800173 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800174 mCrypto->unsetHeap(mHeapSeqNum);
175 }
176}
177
178void CCodecBufferChannel::setComponent(
179 const std::shared_ptr<Codec2Client::Component> &component) {
180 mComponent = component;
181 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
182 mName = mComponentName.c_str();
183}
184
185status_t CCodecBufferChannel::setInputSurface(
186 const std::shared_ptr<InputSurfaceWrapper> &surface) {
187 ALOGV("[%s] setInputSurface", mName);
188 mInputSurface = surface;
189 return mInputSurface->connect(mComponent);
190}
191
192status_t CCodecBufferChannel::signalEndOfInputStream() {
193 if (mInputSurface == nullptr) {
194 return INVALID_OPERATION;
195 }
196 return mInputSurface->signalEndOfInputStream();
197}
198
Sungtak Lee04b30352020-07-27 13:57:25 -0700199status_t CCodecBufferChannel::queueInputBufferInternal(
200 sp<MediaCodecBuffer> buffer,
201 std::shared_ptr<C2LinearBlock> encryptedBlock,
202 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800203 int64_t timeUs;
204 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
205
206 if (mInputMetEos) {
207 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
208 return OK;
209 }
210
211 int32_t flags = 0;
212 int32_t tmp = 0;
213 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200214 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800215 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
216 eos = true;
217 mInputMetEos = true;
218 ALOGV("[%s] input EOS", mName);
219 }
220 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
221 flags |= C2FrameData::FLAG_CODEC_CONFIG;
222 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200223 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
224 tunnelFirstFrame = true;
225 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800226 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800227 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800228 std::unique_ptr<C2Work> work(new C2Work);
229 work->input.ordinal.timestamp = timeUs;
230 work->input.ordinal.frameIndex = mFrameIndex++;
231 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
232 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
233 // Keep client timestamp in customOrdinal
234 work->input.ordinal.customOrdinal = timeUs;
235 work->input.buffers.clear();
236
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700237 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800238 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800239
Pawin Vongmasa36653902018-11-15 00:10:25 -0800240 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700241 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800242 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700243 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800244 return -ENOENT;
245 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700246 // TODO: we want to delay copying buffers.
247 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
248 copy = input->buffers->cloneAndReleaseBuffer(buffer);
249 if (copy != nullptr) {
250 (void)input->extraBuffers.assignSlot(copy);
251 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
252 return UNKNOWN_ERROR;
253 }
254 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
255 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
256 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700257 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700258 } else {
259 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
260 "buffer starvation on component.", mName);
261 }
262 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800263 if (input->frameReassembler) {
264 usesFrameReassembler = true;
265 input->frameReassembler.process(buffer, &items);
266 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900267 int32_t cvo = 0;
268 if (buffer->meta()->findInt32("cvo", &cvo)) {
269 int32_t rotation = cvo % 360;
270 // change rotation to counter-clock wise.
271 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
272
273 Mutexed<OutputSurface>::Locked output(mOutputSurface);
274 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
275 output->rotation[frameIndex] = rotation;
276 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800277 work->input.buffers.push_back(c2buffer);
278 if (encryptedBlock) {
279 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
280 kParamIndexEncryptedBuffer,
281 encryptedBlock->share(0, blockSize, C2Fence())));
282 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700283 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800284 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700285 Mutexed<Input>::Locked input(mInput);
286 if (input->frameReassembler) {
287 usesFrameReassembler = true;
288 // drain any pending items with eos
289 input->frameReassembler.process(buffer, &items);
290 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800291 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800292 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800293 if (usesFrameReassembler) {
294 if (!items.empty()) {
295 items.front()->input.configUpdate = std::move(mParamsToBeSet);
296 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
297 }
298 } else {
299 work->input.flags = (C2FrameData::flags_t)flags;
300 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800301
Wonsik Kime1104ca2020-11-24 15:01:33 -0800302 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200303 if (tunnelFirstFrame) {
304 C2StreamTunnelHoldRender::input tunnelHoldRender{
305 0u /* stream */,
306 C2_TRUE /* value */
307 };
308 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
309 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800310 work->worklets.clear();
311 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800312
Wonsik Kime1104ca2020-11-24 15:01:33 -0800313 items.push_back(std::move(work));
314
315 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800316 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800317 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800318 work.reset(new C2Work);
319 work->input.ordinal.timestamp = timeUs;
320 work->input.ordinal.frameIndex = mFrameIndex++;
321 // WORKAROUND: keep client timestamp in customOrdinal
322 work->input.ordinal.customOrdinal = timeUs;
323 work->input.buffers.clear();
324 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800325 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800326 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800327 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800328 c2_status_t err = C2_OK;
329 if (!items.empty()) {
330 {
331 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
332 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
333 for (const std::unique_ptr<C2Work> &work : items) {
334 watcher->onWorkQueued(
335 work->input.ordinal.frameIndex.peeku(),
336 std::vector(work->input.buffers),
337 now);
338 }
339 }
340 err = mComponent->queue(&items);
341 }
342 if (err != C2_OK) {
343 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
344 for (const std::unique_ptr<C2Work> &work : items) {
345 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
346 }
347 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700348 Mutexed<Input>::Locked input(mInput);
349 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700350 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700351 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700352 } else if (buffer) {
353 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700354 }
355 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
356 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800357 }
358
359 feedInputBufferIfAvailableInternal();
360 return err;
361}
362
363status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
364 QueueGuard guard(mSync);
365 if (!guard.isRunning()) {
366 ALOGD("[%s] setParameters is only supported in the running state.", mName);
367 return -ENOSYS;
368 }
369 mParamsToBeSet.insert(mParamsToBeSet.end(),
370 std::make_move_iterator(params.begin()),
371 std::make_move_iterator(params.end()));
372 params.clear();
373 return OK;
374}
375
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800376status_t CCodecBufferChannel::attachBuffer(
377 const std::shared_ptr<C2Buffer> &c2Buffer,
378 const sp<MediaCodecBuffer> &buffer) {
379 if (!buffer->copy(c2Buffer)) {
380 return -ENOSYS;
381 }
382 return OK;
383}
384
385void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
386 if (!mDecryptDestination || mDecryptDestination->size() < size) {
387 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
388 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
389 mCrypto->unsetHeap(mHeapSeqNum);
390 }
391 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
392 if (mCrypto) {
393 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
394 }
395 }
396}
397
398int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
399 CHECK(mCrypto);
400 auto it = mHeapSeqNumMap.find(memory);
401 int32_t heapSeqNum = -1;
402 if (it == mHeapSeqNumMap.end()) {
403 heapSeqNum = mCrypto->setHeap(memory);
404 mHeapSeqNumMap.emplace(memory, heapSeqNum);
405 } else {
406 heapSeqNum = it->second;
407 }
408 return heapSeqNum;
409}
410
411status_t CCodecBufferChannel::attachEncryptedBuffer(
412 const sp<hardware::HidlMemory> &memory,
413 bool secure,
414 const uint8_t *key,
415 const uint8_t *iv,
416 CryptoPlugin::Mode mode,
417 CryptoPlugin::Pattern pattern,
418 size_t offset,
419 const CryptoPlugin::SubSample *subSamples,
420 size_t numSubSamples,
421 const sp<MediaCodecBuffer> &buffer) {
422 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
423 static const C2MemoryUsage kDefaultReadWriteUsage{
424 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
425
426 size_t size = 0;
427 for (size_t i = 0; i < numSubSamples; ++i) {
428 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
429 }
430 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
431 std::shared_ptr<C2LinearBlock> block;
432 c2_status_t err = pool->fetchLinearBlock(
433 size,
434 secure ? kSecureUsage : kDefaultReadWriteUsage,
435 &block);
436 if (err != C2_OK) {
437 return NO_MEMORY;
438 }
439 if (!secure) {
440 ensureDecryptDestination(size);
441 }
442 ssize_t result = -1;
443 ssize_t codecDataOffset = 0;
444 if (mCrypto) {
445 AString errorDetailMsg;
446 int32_t heapSeqNum = getHeapSeqNum(memory);
447 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
448 hardware::drm::V1_0::DestinationBuffer dst;
449 if (secure) {
450 dst.type = DrmBufferType::NATIVE_HANDLE;
451 dst.secureMemory = hardware::hidl_handle(block->handle());
452 } else {
453 dst.type = DrmBufferType::SHARED_MEMORY;
454 IMemoryToSharedBuffer(
455 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
456 }
457 result = mCrypto->decrypt(
458 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
459 dst, &errorDetailMsg);
460 if (result < 0) {
461 return result;
462 }
463 if (dst.type == DrmBufferType::SHARED_MEMORY) {
464 C2WriteView view = block->map().get();
465 if (view.error() != C2_OK) {
466 return false;
467 }
468 if (view.size() < result) {
469 return false;
470 }
471 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
472 }
473 } else {
474 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
475 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
476 hidl_vec<SubSample> hidlSubSamples;
477 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
478
479 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
480 hardware::cas::native::V1_0::DestinationBuffer dst;
481 if (secure) {
482 dst.type = BufferType::NATIVE_HANDLE;
483 dst.secureMemory = hardware::hidl_handle(block->handle());
484 } else {
485 dst.type = BufferType::SHARED_MEMORY;
486 dst.nonsecureMemory = src;
487 }
488
489 CasStatus status = CasStatus::OK;
490 hidl_string detailedError;
491 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
492
493 if (key != nullptr) {
494 sctrl = (ScramblingControl)key[0];
495 // Adjust for the PES offset
496 codecDataOffset = key[2] | (key[3] << 8);
497 }
498
499 auto returnVoid = mDescrambler->descramble(
500 sctrl,
501 hidlSubSamples,
502 src,
503 0,
504 dst,
505 0,
506 [&status, &result, &detailedError] (
507 CasStatus _status, uint32_t _bytesWritten,
508 const hidl_string& _detailedError) {
509 status = _status;
510 result = (ssize_t)_bytesWritten;
511 detailedError = _detailedError;
512 });
513
514 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
515 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
516 mName, returnVoid.description().c_str(), status, result);
517 return UNKNOWN_ERROR;
518 }
519
520 if (result < codecDataOffset) {
521 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
522 return BAD_VALUE;
523 }
524 }
525 if (!secure) {
526 C2WriteView view = block->map().get();
527 if (view.error() != C2_OK) {
528 return UNKNOWN_ERROR;
529 }
530 if (view.size() < result) {
531 return UNKNOWN_ERROR;
532 }
533 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
534 }
535 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
536 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
537 if (!buffer->copy(c2Buffer)) {
538 return -ENOSYS;
539 }
540 return OK;
541}
542
Pawin Vongmasa36653902018-11-15 00:10:25 -0800543status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
544 QueueGuard guard(mSync);
545 if (!guard.isRunning()) {
546 ALOGD("[%s] No more buffers should be queued at current state.", mName);
547 return -ENOSYS;
548 }
549 return queueInputBufferInternal(buffer);
550}
551
552status_t CCodecBufferChannel::queueSecureInputBuffer(
553 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
554 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
555 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
556 AString *errorDetailMsg) {
557 QueueGuard guard(mSync);
558 if (!guard.isRunning()) {
559 ALOGD("[%s] No more buffers should be queued at current state.", mName);
560 return -ENOSYS;
561 }
562
563 if (!hasCryptoOrDescrambler()) {
564 return -ENOSYS;
565 }
566 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
567
Sungtak Lee04b30352020-07-27 13:57:25 -0700568 std::shared_ptr<C2LinearBlock> block;
569 size_t allocSize = buffer->size();
570 size_t bufferSize = 0;
571 c2_status_t blockRes = C2_OK;
572 bool copied = false;
573 if (mSendEncryptedInfoBuffer) {
574 static const C2MemoryUsage kDefaultReadWriteUsage{
575 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
576 constexpr int kAllocGranule0 = 1024 * 64;
577 constexpr int kAllocGranule1 = 1024 * 1024;
578 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
579 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
580 if (allocSize <= kAllocGranule1) {
581 bufferSize = align(allocSize, kAllocGranule0);
582 } else {
583 bufferSize = align(allocSize, kAllocGranule1);
584 }
585 blockRes = pool->fetchLinearBlock(
586 bufferSize, kDefaultReadWriteUsage, &block);
587
588 if (blockRes == C2_OK) {
589 C2WriteView view = block->map().get();
590 if (view.error() == C2_OK && view.size() == bufferSize) {
591 copied = true;
592 // TODO: only copy clear sections
593 memcpy(view.data(), buffer->data(), allocSize);
594 }
595 }
596 }
597
598 if (!copied) {
599 block.reset();
600 }
601
Pawin Vongmasa36653902018-11-15 00:10:25 -0800602 ssize_t result = -1;
603 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700604 if (numSubSamples == 1
605 && subSamples[0].mNumBytesOfClearData == 0
606 && subSamples[0].mNumBytesOfEncryptedData == 0) {
607 // We don't need to go through crypto or descrambler if the input is empty.
608 result = 0;
609 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700610 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800611 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700612 destination.type = DrmBufferType::NATIVE_HANDLE;
613 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800614 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700615 destination.type = DrmBufferType::SHARED_MEMORY;
616 IMemoryToSharedBuffer(
617 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800618 }
Robert Shih895fba92019-07-16 16:29:44 -0700619 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800620 encryptedBuffer->fillSourceBuffer(&source);
621 result = mCrypto->decrypt(
622 key, iv, mode, pattern, source, buffer->offset(),
623 subSamples, numSubSamples, destination, errorDetailMsg);
624 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700625 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800626 return result;
627 }
Robert Shih895fba92019-07-16 16:29:44 -0700628 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800629 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
630 }
631 } else {
632 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
633 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
634 hidl_vec<SubSample> hidlSubSamples;
635 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
636
637 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
638 encryptedBuffer->fillSourceBuffer(&srcBuffer);
639
640 DestinationBuffer dstBuffer;
641 if (secure) {
642 dstBuffer.type = BufferType::NATIVE_HANDLE;
643 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
644 } else {
645 dstBuffer.type = BufferType::SHARED_MEMORY;
646 dstBuffer.nonsecureMemory = srcBuffer;
647 }
648
649 CasStatus status = CasStatus::OK;
650 hidl_string detailedError;
651 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
652
653 if (key != nullptr) {
654 sctrl = (ScramblingControl)key[0];
655 // Adjust for the PES offset
656 codecDataOffset = key[2] | (key[3] << 8);
657 }
658
659 auto returnVoid = mDescrambler->descramble(
660 sctrl,
661 hidlSubSamples,
662 srcBuffer,
663 0,
664 dstBuffer,
665 0,
666 [&status, &result, &detailedError] (
667 CasStatus _status, uint32_t _bytesWritten,
668 const hidl_string& _detailedError) {
669 status = _status;
670 result = (ssize_t)_bytesWritten;
671 detailedError = _detailedError;
672 });
673
674 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
675 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
676 mName, returnVoid.description().c_str(), status, result);
677 return UNKNOWN_ERROR;
678 }
679
680 if (result < codecDataOffset) {
681 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
682 return BAD_VALUE;
683 }
684
685 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
686
687 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
688 encryptedBuffer->copyDecryptedContentFromMemory(result);
689 }
690 }
691
692 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700693
694 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800695}
696
697void CCodecBufferChannel::feedInputBufferIfAvailable() {
698 QueueGuard guard(mSync);
699 if (!guard.isRunning()) {
700 ALOGV("[%s] We're not running --- no input buffer reported", mName);
701 return;
702 }
703 feedInputBufferIfAvailableInternal();
704}
705
706void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900707 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800708 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700709 }
710 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700711 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700712 if (!output->buffers ||
713 output->buffers->hasPending() ||
Wonsik Kim0487b782020-10-28 11:45:50 -0700714 output->buffers->numActiveSlots() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800715 return;
716 }
717 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700718 size_t numActiveSlots = 0;
719 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800720 sp<MediaCodecBuffer> inBuffer;
721 size_t index;
722 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700723 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700724 numActiveSlots = input->buffers->numActiveSlots();
725 if (numActiveSlots >= input->numSlots) {
726 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800727 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700728 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800729 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800730 break;
731 }
732 }
733 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
734 mCallback->onInputBufferAvailable(index, inBuffer);
735 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700736 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800737}
738
739status_t CCodecBufferChannel::renderOutputBuffer(
740 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800741 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800742 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800743 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800744 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700745 Mutexed<Output>::Locked output(mOutput);
746 if (output->buffers) {
747 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748 }
749 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800750 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
751 // set to true.
752 sendOutputBuffers();
753 // input buffer feeding may have been gated by pending output buffers
754 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800755 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800756 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700757 std::call_once(mRenderWarningFlag, [this] {
758 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
759 "timestamp or render=true with non-video buffers. Apps should "
760 "call releaseOutputBuffer() with render=false for those.",
761 mName);
762 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800763 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800764 return INVALID_OPERATION;
765 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800766
767#if 0
768 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
769 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
770 for (const std::shared_ptr<const C2Info> &info : infoParams) {
771 AString res;
772 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
773 if (ix) res.append(", ");
774 res.append(*((int32_t*)info.get() + (ix / 4)));
775 }
776 ALOGV(" [%s]", res.c_str());
777 }
778#endif
779 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
780 std::static_pointer_cast<const C2StreamRotationInfo::output>(
781 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
782 bool flip = rotation && (rotation->flip & 1);
783 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900784
785 {
786 Mutexed<OutputSurface>::Locked output(mOutputSurface);
787 if (output->surface == nullptr) {
788 ALOGI("[%s] cannot render buffer without surface", mName);
789 return OK;
790 }
791 int64_t frameIndex;
792 buffer->meta()->findInt64("frameIndex", &frameIndex);
793 if (output->rotation.count(frameIndex) != 0) {
794 auto it = output->rotation.find(frameIndex);
795 quarters = (it->second / 90) & 3;
796 output->rotation.erase(it);
797 }
798 }
799
Pawin Vongmasa36653902018-11-15 00:10:25 -0800800 uint32_t transform = 0;
801 switch (quarters) {
802 case 0: // no rotation
803 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
804 break;
805 case 1: // 90 degrees counter-clockwise
806 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
807 : HAL_TRANSFORM_ROT_270;
808 break;
809 case 2: // 180 degrees
810 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
811 break;
812 case 3: // 90 degrees clockwise
813 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
814 : HAL_TRANSFORM_ROT_90;
815 break;
816 }
817
818 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
819 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
820 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
821 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
822 if (surfaceScaling) {
823 videoScalingMode = surfaceScaling->value;
824 }
825
826 // Use dataspace from format as it has the default aspects already applied
827 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
828 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
829
830 // HDR static info
831 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
832 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
833 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
834
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800835 // HDR10 plus info
836 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
837 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
838 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800839 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
840 hdr10PlusInfo.reset();
841 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800842
Wonsik Kima79c5522022-01-18 16:29:24 -0800843 // HDR dynamic info
844 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
845 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
846 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
847 // TODO: make this sticky & enable unset
848 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
849 hdrDynamicInfo.reset();
850 }
851
852 if (hdr10PlusInfo) {
853 // C2StreamHdr10PlusInfo is deprecated; components should use
854 // C2StreamHdrDynamicMetadataInfo
855 // TODO: #metric
856 if (hdrDynamicInfo) {
857 // It is unexpected that C2StreamHdr10PlusInfo and
858 // C2StreamHdrDynamicMetadataInfo is both present.
859 // C2StreamHdrDynamicMetadataInfo takes priority.
860 // TODO: #metric
861 } else {
862 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
863 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
864 hdr10PlusInfo->flexCount(),
865 0u,
866 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
867 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
868 hdrDynamicInfo = info;
869 }
870 }
871
Pawin Vongmasa36653902018-11-15 00:10:25 -0800872 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
873 if (blocks.size() != 1u) {
874 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
875 return UNKNOWN_ERROR;
876 }
877 const C2ConstGraphicBlock &block = blocks.front();
878
879 // TODO: revisit this after C2Fence implementation.
880 android::IGraphicBufferProducer::QueueBufferInput qbi(
881 timestampNs,
882 false, // droppable
883 dataSpace,
884 Rect(blocks.front().crop().left,
885 blocks.front().crop().top,
886 blocks.front().crop().right(),
887 blocks.front().crop().bottom()),
888 videoScalingMode,
889 transform,
890 Fence::NO_FENCE, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -0800891 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800892 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800893 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800894 // If mastering max and min luminance fields are 0, do not use them.
895 // It indicates the value may not be present in the stream.
896 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
897 hdrStaticInfo->mastering.minLuminance > 0.0f) {
898 struct android_smpte2086_metadata smpte2086_meta = {
899 .displayPrimaryRed = {
900 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
901 },
902 .displayPrimaryGreen = {
903 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
904 },
905 .displayPrimaryBlue = {
906 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
907 },
908 .whitePoint = {
909 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
910 },
911 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
912 .minLuminance = hdrStaticInfo->mastering.minLuminance,
913 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800914 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800915 hdr.smpte2086 = smpte2086_meta;
916 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700917 // If the content light level fields are 0, do not use them, it
918 // indicates the value may not be present in the stream.
919 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
920 struct android_cta861_3_metadata cta861_meta = {
921 .maxContentLightLevel = hdrStaticInfo->maxCll,
922 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
923 };
924 hdr.validTypes |= HdrMetadata::CTA861_3;
925 hdr.cta8613 = cta861_meta;
926 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +0900927
928 // does not have valid info
929 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
930 hdrStaticInfo.reset();
931 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800932 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800933 if (hdrDynamicInfo
934 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800935 hdr.validTypes |= HdrMetadata::HDR10PLUS;
936 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800937 hdrDynamicInfo->m.data,
938 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800939 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800940 qbi.setHdrMetadata(hdr);
Wonsik Kima79c5522022-01-18 16:29:24 -0800941
942 SetHdrMetadataToGralloc4Handle(hdrStaticInfo, hdrDynamicInfo, block.handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800943 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800944 // we don't have dirty regions
945 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800946 android::IGraphicBufferProducer::QueueBufferOutput qbo;
947 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
948 if (result != OK) {
949 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800950 if (result == NO_INIT) {
951 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
952 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800953 return result;
954 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800955
956 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
957 ALOGD("[%s] queue buffer successful", mName);
958 } else {
959 ALOGV("[%s] queue buffer successful", mName);
960 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800961
962 int64_t mediaTimeUs = 0;
963 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
964 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
965
966 return OK;
967}
968
969status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
970 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
971 bool released = false;
972 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700973 Mutexed<Input>::Locked input(mInput);
974 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800975 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800976 }
977 }
978 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700979 Mutexed<Output>::Locked output(mOutput);
980 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800981 released = true;
982 }
983 }
984 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800985 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800986 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800987 } else {
988 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
989 }
990 return OK;
991}
992
993void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
994 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700995 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800996
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700997 if (!input->buffers->isArrayMode()) {
998 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800999 }
1000
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001001 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001002}
1003
1004void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1005 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001006 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001007
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001008 if (!output->buffers->isArrayMode()) {
1009 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001010 }
1011
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001012 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001013}
1014
1015status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001016 const sp<AMessage> &inputFormat,
1017 const sp<AMessage> &outputFormat,
1018 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001019 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1020 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001021 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001022 C2PortReorderBufferDepthTuning::output reorderDepth;
1023 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001024 C2PortActualDelayTuning::input inputDelay(0);
1025 C2PortActualDelayTuning::output outputDelay(0);
1026 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001027 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001028
Pawin Vongmasa36653902018-11-15 00:10:25 -08001029 c2_status_t err = mComponent->query(
1030 {
1031 &iStreamFormat,
1032 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001033 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001034 &reorderDepth,
1035 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001036 &inputDelay,
1037 &pipelineDelay,
1038 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001039 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001040 },
1041 {},
1042 C2_DONT_BLOCK,
1043 nullptr);
1044 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001045 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001046 return UNKNOWN_ERROR;
1047 }
1048 } else if (err != C2_OK) {
1049 return UNKNOWN_ERROR;
1050 }
1051
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001052 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1053 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1054 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1055
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001056 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1057 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001058
Pawin Vongmasa36653902018-11-15 00:10:25 -08001059 // TODO: get this from input format
1060 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1061
Sungtak Lee04b30352020-07-27 13:57:25 -07001062 // secure mode is a static parameter (shall not change in the executing state)
1063 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1064
Pawin Vongmasa36653902018-11-15 00:10:25 -08001065 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001066 int poolMask = GetCodec2PoolMask();
1067 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001068
1069 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001070 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001071 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001072 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1073 API_REFLECTION |
1074 API_VALUES |
1075 API_CURRENT_VALUES |
1076 API_DEPENDENCY |
1077 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001078 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1079 C2StreamSampleRateInfo::input sampleRate(0u);
1080 C2StreamChannelCountInfo::input channelCount(0u);
1081 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001082 std::shared_ptr<C2BlockPool> pool;
1083 {
1084 Mutexed<BlockPools>::Locked pools(mBlockPools);
1085
1086 // set default allocator ID.
1087 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001088 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001089
1090 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1091 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1092 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001093 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001094 std::vector<C2Param *> stackParams({&featuresSetting});
1095 if (audioEncoder) {
1096 stackParams.push_back(&encoderFrameSize);
1097 stackParams.push_back(&sampleRate);
1098 stackParams.push_back(&channelCount);
1099 stackParams.push_back(&pcmEncoding);
1100 } else {
1101 encoderFrameSize.invalidate();
1102 sampleRate.invalidate();
1103 channelCount.invalidate();
1104 pcmEncoding.invalidate();
1105 }
1106 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001107 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1108 C2_DONT_BLOCK,
1109 &params);
1110 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1111 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1112 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001113 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001114 C2PortAllocatorsTuning::input *inputAllocators =
1115 C2PortAllocatorsTuning::input::From(params[0].get());
1116 if (inputAllocators && inputAllocators->flexCount() > 0) {
1117 std::shared_ptr<C2Allocator> allocator;
1118 // verify allocator IDs and resolve default allocator
1119 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1120 if (allocator) {
1121 pools->inputAllocatorId = allocator->getId();
1122 } else {
1123 ALOGD("[%s] component requested invalid input allocator ID %u",
1124 mName, inputAllocators->m.values[0]);
1125 }
1126 }
1127 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001128 if (featuresSetting) {
1129 apiFeatures = featuresSetting.value;
1130 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001131
1132 // TODO: use C2Component wrapper to associate this pool with ourselves
1133 if ((poolMask >> pools->inputAllocatorId) & 1) {
1134 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1135 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1136 mName, pools->inputAllocatorId,
1137 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1138 asString(err), err);
1139 } else {
1140 err = C2_NOT_FOUND;
1141 }
1142 if (err != C2_OK) {
1143 C2BlockPool::local_id_t inputPoolId =
1144 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1145 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1146 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1147 mName, (unsigned long long)inputPoolId,
1148 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1149 asString(err), err);
1150 if (err != C2_OK) {
1151 return NO_MEMORY;
1152 }
1153 }
1154 pools->inputPool = pool;
1155 }
1156
Wonsik Kim51051262018-11-28 13:59:05 -08001157 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001158 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001159 input->inputDelay = inputDelayValue;
1160 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001161 input->numSlots = numInputSlots;
1162 input->extraBuffers.flush();
1163 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001164 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001165 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1166 input->frameReassembler.init(
1167 pool,
1168 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1169 encoderFrameSize.value,
1170 sampleRate.value,
1171 channelCount.value,
1172 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1173 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001174 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1175 // For encrypted content, framework decrypts source buffer (ashmem) into
1176 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001177 if (!buffersBoundToCodec
1178 && !input->frameReassembler
1179 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001180 input->buffers.reset(new SlotInputBuffers(mName));
1181 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001182 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001183 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001184 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001185 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001186 // This is to ensure buffers do not get released prematurely.
1187 // TODO: handle this without going into array mode
1188 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001189 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001190 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001191 }
1192 } else {
1193 if (hasCryptoOrDescrambler()) {
1194 int32_t capacity = kLinearBufferSize;
1195 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1196 if ((size_t)capacity > kMaxLinearBufferSize) {
1197 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1198 capacity = kMaxLinearBufferSize;
1199 }
1200 if (mDealer == nullptr) {
1201 mDealer = new MemoryDealer(
1202 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001203 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001204 "EncryptedLinearInputBuffers");
1205 mDecryptDestination = mDealer->allocate((size_t)capacity);
1206 }
1207 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001208 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1209 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001210 } else {
1211 mHeapSeqNum = -1;
1212 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001213 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001214 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001215 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001216 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001217 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001218 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001219 }
1220 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001221 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001222
1223 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001224 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001225 } else {
1226 // TODO: error
1227 }
Wonsik Kim51051262018-11-28 13:59:05 -08001228
1229 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001230 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001231 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001232 }
1233
1234 if (outputFormat != nullptr) {
1235 sp<IGraphicBufferProducer> outputSurface;
1236 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001237 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001238 {
1239 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001240 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001241 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001242 outputSurface = output->surface ?
1243 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001244 if (outputSurface) {
1245 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1246 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001247 outputGeneration = output->generation;
1248 }
1249
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001250 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001251 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001252 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001253
1254 {
1255 Mutexed<BlockPools>::Locked pools(mBlockPools);
1256
David Stevensc3fbb282021-01-18 18:11:20 +09001257 prevOutputPoolId = pools->outputPoolId;
1258
Pawin Vongmasa36653902018-11-15 00:10:25 -08001259 // set default allocator ID.
1260 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001261 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001262
1263 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1264 // unsuccessful.
1265 std::vector<std::unique_ptr<C2Param>> params;
1266 err = mComponent->query({ },
1267 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1268 C2_DONT_BLOCK,
1269 &params);
1270 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1271 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1272 mName, params.size(), asString(err), err);
1273 } else if (err == C2_OK && params.size() == 1) {
1274 C2PortAllocatorsTuning::output *outputAllocators =
1275 C2PortAllocatorsTuning::output::From(params[0].get());
1276 if (outputAllocators && outputAllocators->flexCount() > 0) {
1277 std::shared_ptr<C2Allocator> allocator;
1278 // verify allocator IDs and resolve default allocator
1279 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1280 if (allocator) {
1281 pools->outputAllocatorId = allocator->getId();
1282 } else {
1283 ALOGD("[%s] component requested invalid output allocator ID %u",
1284 mName, outputAllocators->m.values[0]);
1285 }
1286 }
1287 }
1288
1289 // use bufferqueue if outputting to a surface.
1290 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1291 // if unsuccessful.
1292 if (outputSurface) {
1293 params.clear();
1294 err = mComponent->query({ },
1295 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1296 C2_DONT_BLOCK,
1297 &params);
1298 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1299 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1300 mName, params.size(), asString(err), err);
1301 } else if (err == C2_OK && params.size() == 1) {
1302 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1303 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1304 if (surfaceAllocator) {
1305 std::shared_ptr<C2Allocator> allocator;
1306 // verify allocator IDs and resolve default allocator
1307 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1308 if (allocator) {
1309 pools->outputAllocatorId = allocator->getId();
1310 } else {
1311 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1312 mName, surfaceAllocator->value);
1313 err = C2_BAD_VALUE;
1314 }
1315 }
1316 }
1317 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1318 && err != C2_OK
1319 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1320 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1321 }
1322 }
1323
1324 if ((poolMask >> pools->outputAllocatorId) & 1) {
1325 err = mComponent->createBlockPool(
1326 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1327 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1328 mName, pools->outputAllocatorId,
1329 (unsigned long long)pools->outputPoolId,
1330 asString(err));
1331 } else {
1332 err = C2_NOT_FOUND;
1333 }
1334 if (err != C2_OK) {
1335 // use basic pool instead
1336 pools->outputPoolId =
1337 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1338 }
1339
1340 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1341 // component.
1342 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1343 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1344
1345 std::vector<std::unique_ptr<C2SettingResult>> failures;
1346 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1347 ALOGD("[%s] Configured output block pool ids %llu => %s",
1348 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1349 outputPoolId_ = pools->outputPoolId;
1350 }
1351
David Stevensc3fbb282021-01-18 18:11:20 +09001352 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1353 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1354 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1355 if (err != C2_OK) {
1356 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1357 (unsigned long long) prevOutputPoolId, asString(err), err);
1358 }
1359 }
1360
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001361 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001362 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001363 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001364 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001365 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001366 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001367 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001368 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001369 }
1370 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001371 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001372 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001373 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001374
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001375 output->buffers->clearStash();
1376 if (reorderDepth) {
1377 output->buffers->setReorderDepth(reorderDepth.value);
1378 }
1379 if (reorderKey) {
1380 output->buffers->setReorderKey(reorderKey.value);
1381 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001382
1383 // Try to set output surface to created block pool if given.
1384 if (outputSurface) {
1385 mComponent->setOutputSurface(
1386 outputPoolId_,
1387 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001388 outputGeneration,
1389 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001390 } else {
1391 // configure CPU read consumer usage
1392 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1393 std::vector<std::unique_ptr<C2SettingResult>> failures;
1394 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1395 // do not print error message for now as most components may not yet
1396 // support this setting
1397 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1398 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001399 }
1400
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001401 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001402 if (buffersBoundToCodec) {
1403 // WORKAROUND: if we're using early CSD workaround we convert to
1404 // array mode, to appease apps assuming the output
1405 // buffers to be of the same size.
1406 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1407 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001408
1409 int32_t channelCount;
1410 int32_t sampleRate;
1411 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1412 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1413 int32_t delay = 0;
1414 int32_t padding = 0;;
1415 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1416 delay = 0;
1417 }
1418 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1419 padding = 0;
1420 }
1421 if (delay || padding) {
1422 // We need write access to the buffers, and we're already in
1423 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001424 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001425 }
1426 }
1427 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001428
1429 int32_t tunneled = 0;
1430 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1431 tunneled = 0;
1432 }
1433 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001434 }
1435
1436 // Set up pipeline control. This has to be done after mInputBuffers and
1437 // mOutputBuffers are initialized to make sure that lingering callbacks
1438 // about buffers from the previous generation do not interfere with the
1439 // newly initialized pipeline capacity.
1440
Wonsik Kim62545252021-01-20 11:25:41 -08001441 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001442 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001443 watcher->inputDelay(inputDelayValue)
1444 .pipelineDelay(pipelineDelayValue)
1445 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001446 .smoothnessFactor(kSmoothnessFactor);
1447 watcher->flush();
1448 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001449
1450 mInputMetEos = false;
1451 mSync.start();
1452 return OK;
1453}
1454
1455status_t CCodecBufferChannel::requestInitialInputBuffers() {
1456 if (mInputSurface) {
1457 return OK;
1458 }
1459
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001460 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001461 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1462 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1463 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001464 return UNKNOWN_ERROR;
1465 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001466 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001467
1468 struct ClientInputBuffer {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001469 size_t index;
1470 sp<MediaCodecBuffer> buffer;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001471 size_t capacity;
1472 };
1473 std::list<ClientInputBuffer> clientInputBuffers;
1474
1475 {
1476 Mutexed<Input>::Locked input(mInput);
1477 while (clientInputBuffers.size() < numInputSlots) {
1478 ClientInputBuffer clientInputBuffer;
1479 if (!input->buffers->requestNewBuffer(&clientInputBuffer.index,
1480 &clientInputBuffer.buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001481 break;
1482 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001483 clientInputBuffer.capacity = clientInputBuffer.buffer->capacity();
1484 clientInputBuffers.emplace_back(std::move(clientInputBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001485 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001486 }
1487 if (clientInputBuffers.empty()) {
1488 ALOGW("[%s] start: cannot allocate memory at all", mName);
1489 return NO_MEMORY;
1490 } else if (clientInputBuffers.size() < numInputSlots) {
1491 ALOGD("[%s] start: cannot allocate memory for all slots, "
1492 "only %zu buffers allocated",
1493 mName, clientInputBuffers.size());
1494 } else {
1495 ALOGV("[%s] %zu initial input buffers available",
1496 mName, clientInputBuffers.size());
1497 }
1498 // Sort input buffers by their capacities in increasing order.
1499 clientInputBuffers.sort(
1500 [](const ClientInputBuffer& a, const ClientInputBuffer& b) {
1501 return a.capacity < b.capacity;
1502 });
1503
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001504 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1505 mFlushedConfigs.lock()->swap(flushedConfigs);
1506 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001507 {
1508 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1509 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1510 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1511 watcher->onWorkQueued(
1512 work->input.ordinal.frameIndex.peeku(),
1513 std::vector(work->input.buffers),
1514 now);
1515 }
1516 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001517 err = mComponent->queue(&flushedConfigs);
1518 if (err != C2_OK) {
1519 ALOGW("[%s] Error while queueing a flushed config", mName);
1520 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001521 }
1522 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001523 if (oStreamFormat.value == C2BufferData::LINEAR &&
1524 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
1525 sp<MediaCodecBuffer> buffer = clientInputBuffers.front().buffer;
1526 // WORKAROUND: Some apps expect CSD available without queueing
1527 // any input. Queue an empty buffer to get the CSD.
1528 buffer->setRange(0, 0);
1529 buffer->meta()->clear();
1530 buffer->meta()->setInt64("timeUs", 0);
1531 if (queueInputBufferInternal(buffer) != OK) {
1532 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1533 mName);
1534 return UNKNOWN_ERROR;
1535 }
1536 clientInputBuffers.pop_front();
1537 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001538
1539 for (const ClientInputBuffer& clientInputBuffer: clientInputBuffers) {
1540 mCallback->onInputBufferAvailable(
1541 clientInputBuffer.index,
1542 clientInputBuffer.buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001543 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001544
Pawin Vongmasa36653902018-11-15 00:10:25 -08001545 return OK;
1546}
1547
1548void CCodecBufferChannel::stop() {
1549 mSync.stop();
1550 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001551}
1552
Wonsik Kim936a89c2020-05-08 16:07:50 -07001553void CCodecBufferChannel::reset() {
1554 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001555 if (mInputSurface != nullptr) {
1556 mInputSurface.reset();
1557 }
1558 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001559 {
1560 Mutexed<Input>::Locked input(mInput);
1561 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001562 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001563 }
1564 {
1565 Mutexed<Output>::Locked output(mOutput);
1566 output->buffers.reset();
1567 }
1568}
1569
1570void CCodecBufferChannel::release() {
1571 mComponent.reset();
1572 mInputAllocator.reset();
1573 mOutputSurface.lock()->surface.clear();
1574 {
1575 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1576 blockPools->inputPool.reset();
1577 blockPools->outputPoolIntf.reset();
1578 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001579 setCrypto(nullptr);
1580 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001581}
1582
Pawin Vongmasa36653902018-11-15 00:10:25 -08001583void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1584 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001585 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001586 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001587 {
1588 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1589 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1590 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1591 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1592 watcher->onWorkDone(frameIndex);
1593 continue;
1594 }
1595 if (work->input.buffers.empty()
1596 || work->input.buffers.front() == nullptr
1597 || work->input.buffers.front()->data().linearBlocks().empty()) {
1598 ALOGD("[%s] no linear codec config data found", mName);
1599 watcher->onWorkDone(frameIndex);
1600 continue;
1601 }
1602 std::unique_ptr<C2Work> copy(new C2Work);
1603 copy->input.flags = C2FrameData::flags_t(
1604 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1605 copy->input.ordinal = work->input.ordinal;
1606 copy->input.ordinal.frameIndex = mFrameIndex++;
1607 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1608 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1609 }
1610 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1611 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1612 }
1613 copy->input.infoBuffers.insert(
1614 copy->input.infoBuffers.begin(),
1615 work->input.infoBuffers.begin(),
1616 work->input.infoBuffers.end());
1617 copy->worklets.emplace_back(new C2Worklet);
1618 configs.push_back(std::move(copy));
1619 watcher->onWorkDone(frameIndex);
1620 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001621 }
1622 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001623 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001624 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001625 Mutexed<Input>::Locked input(mInput);
1626 input->buffers->flush();
1627 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001628 }
1629 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001630 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001631 if (output->buffers) {
1632 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001633 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001634 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001635 }
1636}
1637
1638void CCodecBufferChannel::onWorkDone(
1639 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001640 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001641 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001642 feedInputBufferIfAvailable();
1643 }
1644}
1645
1646void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001647 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001648 if (mInputSurface) {
1649 return;
1650 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001651 std::shared_ptr<C2Buffer> buffer =
1652 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001653 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001654 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001655 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001656 if (input->lastFlushIndex >= frameIndex) {
1657 ALOGD("[%s] Ignoring stale input buffer done callback: "
1658 "last flush index = %lld, frameIndex = %lld",
1659 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1660 } else {
1661 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1662 if (!newInputSlotAvailable) {
1663 (void)input->extraBuffers.expireComponentBuffer(buffer);
1664 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001665 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001666 }
1667 if (newInputSlotAvailable) {
1668 feedInputBufferIfAvailable();
1669 }
1670}
1671
1672bool CCodecBufferChannel::handleWork(
1673 std::unique_ptr<C2Work> work,
1674 const sp<AMessage> &outputFormat,
1675 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001676 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001677 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001678 if (!output->buffers) {
1679 return false;
1680 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001681 }
1682
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001683 // Whether the output buffer should be reported to the client or not.
1684 bool notifyClient = false;
1685
1686 if (work->result == C2_OK){
1687 notifyClient = true;
1688 } else if (work->result == C2_NOT_FOUND) {
1689 ALOGD("[%s] flushed work; ignored.", mName);
1690 } else {
1691 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1692 // the config update.
1693 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1694 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1695 return false;
1696 }
1697
1698 if ((work->input.ordinal.frameIndex -
1699 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001700 // Discard frames from previous generation.
1701 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001702 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001703 }
1704
Wonsik Kim524b0582019-03-12 11:28:57 -07001705 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001706 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001707 || !(work->worklets.front()->output.flags &
1708 C2FrameData::FLAG_INCOMPLETE))) {
1709 mPipelineWatcher.lock()->onWorkDone(
1710 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001711 }
1712
1713 // NOTE: MediaCodec usage supposedly have only one worklet
1714 if (work->worklets.size() != 1u) {
1715 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1716 mName, work->worklets.size());
1717 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1718 return false;
1719 }
1720
1721 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1722
1723 std::shared_ptr<C2Buffer> buffer;
1724 // NOTE: MediaCodec usage supposedly have only one output stream.
1725 if (worklet->output.buffers.size() > 1u) {
1726 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1727 mName, worklet->output.buffers.size());
1728 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1729 return false;
1730 } else if (worklet->output.buffers.size() == 1u) {
1731 buffer = worklet->output.buffers[0];
1732 if (!buffer) {
1733 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1734 }
1735 }
1736
Wonsik Kim3dedf682021-05-03 10:57:09 -07001737 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1738 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001739 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001740 while (!worklet->output.configUpdate.empty()) {
1741 std::unique_ptr<C2Param> param;
1742 worklet->output.configUpdate.back().swap(param);
1743 worklet->output.configUpdate.pop_back();
1744 switch (param->coreIndex().coreIndex()) {
1745 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1746 C2PortReorderBufferDepthTuning::output reorderDepth;
1747 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001748 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1749 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001750 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001751 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001752 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001753 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1754 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001755 }
1756 break;
1757 }
1758 case C2PortReorderKeySetting::CORE_INDEX: {
1759 C2PortReorderKeySetting::output reorderKey;
1760 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001761 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001762 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1763 mName, reorderKey.value);
1764 } else {
1765 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1766 }
1767 break;
1768 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001769 case C2PortActualDelayTuning::CORE_INDEX: {
1770 if (param->isGlobal()) {
1771 C2ActualPipelineDelayTuning pipelineDelay;
1772 if (pipelineDelay.updateFrom(*param)) {
1773 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1774 mName, pipelineDelay.value);
1775 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001776 (void)mPipelineWatcher.lock()->pipelineDelay(
1777 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001778 }
1779 }
1780 if (param->forInput()) {
1781 C2PortActualDelayTuning::input inputDelay;
1782 if (inputDelay.updateFrom(*param)) {
1783 ALOGV("[%s] onWorkDone: updating input delay %u",
1784 mName, inputDelay.value);
1785 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001786 (void)mPipelineWatcher.lock()->inputDelay(
1787 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001788 }
1789 }
1790 if (param->forOutput()) {
1791 C2PortActualDelayTuning::output outputDelay;
1792 if (outputDelay.updateFrom(*param)) {
1793 ALOGV("[%s] onWorkDone: updating output delay %u",
1794 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001795 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001796 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001797 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001798
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001799 }
1800 }
1801 break;
1802 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001803 case C2PortTunnelSystemTime::CORE_INDEX: {
1804 C2PortTunnelSystemTime::output frameRenderTime;
1805 if (frameRenderTime.updateFrom(*param)) {
1806 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1807 mName, (long long)frameRenderTime.value,
1808 (long long)worklet->output.ordinal.timestamp.peekll());
1809 mCCodecCallback->onOutputFramesRendered(
1810 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1811 }
1812 break;
1813 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001814 case C2StreamTunnelHoldRender::CORE_INDEX: {
1815 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1816 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1817 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1818 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1819 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1820 mCCodecCallback->onFirstTunnelFrameReady();
1821 break;
1822 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001823 default:
1824 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1825 mName, param->index());
1826 break;
1827 }
1828 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001829 if (newInputDelay || newPipelineDelay) {
1830 Mutexed<Input>::Locked input(mInput);
1831 size_t newNumSlots =
1832 newInputDelay.value_or(input->inputDelay) +
1833 newPipelineDelay.value_or(input->pipelineDelay) +
1834 kSmoothnessFactor;
1835 if (input->buffers->isArrayMode()) {
1836 if (input->numSlots >= newNumSlots) {
1837 input->numExtraSlots = 0;
1838 } else {
1839 input->numExtraSlots = newNumSlots - input->numSlots;
1840 }
1841 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1842 mName, input->numExtraSlots);
1843 } else {
1844 input->numSlots = newNumSlots;
1845 }
1846 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001847 size_t numOutputSlots = 0;
1848 uint32_t reorderDepth = 0;
1849 bool outputBuffersChanged = false;
1850 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
1851 Mutexed<Output>::Locked output(mOutput);
1852 if (!output->buffers) {
1853 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001854 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001855 numOutputSlots = output->numSlots;
1856 if (newReorderKey) {
1857 output->buffers->setReorderKey(newReorderKey.value());
1858 }
1859 if (newReorderDepth) {
1860 output->buffers->setReorderDepth(newReorderDepth.value());
1861 }
1862 reorderDepth = output->buffers->getReorderDepth();
1863 if (newOutputDelay) {
1864 output->outputDelay = newOutputDelay.value();
1865 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
1866 if (output->numSlots < numOutputSlots) {
1867 output->numSlots = numOutputSlots;
1868 if (output->buffers->isArrayMode()) {
1869 OutputBuffersArray *array =
1870 (OutputBuffersArray *)output->buffers.get();
1871 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1872 mName, numOutputSlots);
1873 array->grow(numOutputSlots);
1874 outputBuffersChanged = true;
1875 }
1876 }
1877 }
1878 numOutputSlots = output->numSlots;
1879 }
1880 if (outputBuffersChanged) {
1881 mCCodecCallback->onOutputBuffersChanged();
1882 }
1883 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07001884 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07001885 {
1886 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1887 maxDequeueCount = output->maxDequeueBuffers =
1888 numOutputSlots + reorderDepth + kRenderingDepth;
1889 if (output->surface) {
1890 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1891 }
1892 }
1893 if (maxDequeueCount > 0) {
1894 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001895 }
1896 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001897
Pawin Vongmasa36653902018-11-15 00:10:25 -08001898 int32_t flags = 0;
1899 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1900 flags |= MediaCodec::BUFFER_FLAG_EOS;
1901 ALOGV("[%s] onWorkDone: output EOS", mName);
1902 }
1903
Pawin Vongmasa36653902018-11-15 00:10:25 -08001904 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1905 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1906 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1907 // shall correspond to the client input timesamp (in customOrdinal). By using the
1908 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1909 // produces multiple output.
1910 c2_cntr64_t timestamp =
1911 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1912 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001913 if (mInputSurface != nullptr) {
1914 // When using input surface we need to restore the original input timestamp.
1915 timestamp = work->input.ordinal.customOrdinal;
1916 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001917 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1918 mName,
1919 work->input.ordinal.customOrdinal.peekll(),
1920 work->input.ordinal.timestamp.peekll(),
1921 worklet->output.ordinal.timestamp.peekll(),
1922 timestamp.peekll());
1923
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001924 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001925 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001926 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001927 if (output->buffers && outputFormat) {
1928 output->buffers->updateSkipCutBuffer(outputFormat);
1929 output->buffers->setFormat(outputFormat);
1930 }
1931 if (!notifyClient) {
1932 return false;
1933 }
1934 size_t index;
1935 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07001936 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001937 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1938 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1939 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1940
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001941 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001942 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001943 } else {
1944 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001945 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001946 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001947 return false;
1948 }
1949 }
1950
Wonsik Kimec585c32021-10-01 01:11:00 -07001951 bool drop = false;
1952 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
1953 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
1954 drop = true;
1955 }
1956
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001957 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07001958 if (mTunneled && drop && outputFormat) {
1959 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
1960 mName, work->input.ordinal.frameIndex.peekull());
1961 } else {
1962 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1963 mName, work->input.ordinal.frameIndex.peekull());
1964 notifyClient = false;
1965 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001966 }
1967
1968 if (buffer) {
1969 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1970 // TODO: properly translate these to metadata
1971 switch (info->coreIndex().coreIndex()) {
1972 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001973 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001974 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1975 }
1976 break;
1977 default:
1978 break;
1979 }
1980 }
1981 }
1982
1983 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001984 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07001985 if (!output->buffers) {
1986 return false;
1987 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001988 output->buffers->pushToStash(
1989 buffer,
1990 notifyClient,
1991 timestamp.peek(),
1992 flags,
1993 outputFormat,
1994 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001995 }
1996 sendOutputBuffers();
1997 return true;
1998}
1999
2000void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002001 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002002 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002003 sp<MediaCodecBuffer> outBuffer;
2004 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002005
2006 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002007 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002008 if (!output->buffers) {
2009 return;
2010 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002011 action = output->buffers->popFromStashAndRegister(
2012 &c2Buffer, &index, &outBuffer);
2013 switch (action) {
2014 case OutputBuffers::SKIP:
2015 return;
2016 case OutputBuffers::DISCARD:
2017 break;
2018 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00002019 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002020 mCallback->onOutputBufferAvailable(index, outBuffer);
2021 break;
2022 case OutputBuffers::REALLOCATE:
2023 if (!output->buffers->isArrayMode()) {
2024 output->buffers =
2025 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002026 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002027 static_cast<OutputBuffersArray*>(output->buffers.get())->
2028 realloc(c2Buffer);
2029 output.unlock();
2030 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002031 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002032 case OutputBuffers::RETRY:
2033 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2034 mName);
2035 return;
2036 default:
2037 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2038 "corrupted BufferAction value (%d) "
2039 "returned from popFromStashAndRegister.",
2040 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002041 return;
2042 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002043 }
2044}
2045
2046status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
2047 static std::atomic_uint32_t surfaceGeneration{0};
2048 uint32_t generation = (getpid() << 10) |
2049 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2050 & ((1 << 10) - 1));
2051
2052 sp<IGraphicBufferProducer> producer;
Sungtak Leedb14cba2021-04-10 00:50:23 -07002053 int maxDequeueCount = mOutputSurface.lock()->maxDequeueBuffers;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002054 if (newSurface) {
2055 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002056 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002057 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002058 producer = newSurface->getIGraphicBufferProducer();
2059 producer->setGenerationNumber(generation);
2060 } else {
2061 ALOGE("[%s] setting output surface to null", mName);
2062 return INVALID_OPERATION;
2063 }
2064
2065 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2066 C2BlockPool::local_id_t outputPoolId;
2067 {
2068 Mutexed<BlockPools>::Locked pools(mBlockPools);
2069 outputPoolId = pools->outputPoolId;
2070 outputPoolIntf = pools->outputPoolIntf;
2071 }
2072
2073 if (outputPoolIntf) {
2074 if (mComponent->setOutputSurface(
2075 outputPoolId,
2076 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002077 generation,
2078 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002079 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2080 return INVALID_OPERATION;
2081 }
2082 }
2083
2084 {
2085 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2086 output->surface = newSurface;
2087 output->generation = generation;
2088 }
2089
2090 return OK;
2091}
2092
Wonsik Kimab34ed62019-01-31 15:28:46 -08002093PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002094 // When client pushed EOS, we want all the work to be done quickly.
2095 // Otherwise, component may have stalled work due to input starvation up to
2096 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002097 size_t n = 0;
2098 if (!mInputMetEos) {
2099 size_t outputDelay = mOutput.lock()->outputDelay;
2100 Mutexed<Input>::Locked input(mInput);
2101 n = input->inputDelay + input->pipelineDelay + outputDelay;
2102 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002103 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002104}
2105
Pawin Vongmasa36653902018-11-15 00:10:25 -08002106void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2107 mMetaMode = mode;
2108}
2109
Wonsik Kim596187e2019-10-25 12:44:10 -07002110void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002111 if (mCrypto != nullptr) {
2112 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2113 mCrypto->unsetHeap(entry.second);
2114 }
2115 mHeapSeqNumMap.clear();
2116 if (mHeapSeqNum >= 0) {
2117 mCrypto->unsetHeap(mHeapSeqNum);
2118 mHeapSeqNum = -1;
2119 }
2120 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002121 mCrypto = crypto;
2122}
2123
2124void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2125 mDescrambler = descrambler;
2126}
2127
Pawin Vongmasa36653902018-11-15 00:10:25 -08002128status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2129 // C2_OK is always translated to OK.
2130 if (c2s == C2_OK) {
2131 return OK;
2132 }
2133
2134 // Operation-dependent translation
2135 // TODO: Add as necessary
2136 switch (c2op) {
2137 case C2_OPERATION_Component_start:
2138 switch (c2s) {
2139 case C2_NO_MEMORY:
2140 return NO_MEMORY;
2141 default:
2142 return UNKNOWN_ERROR;
2143 }
2144 default:
2145 break;
2146 }
2147
2148 // Backup operation-agnostic translation
2149 switch (c2s) {
2150 case C2_BAD_INDEX:
2151 return BAD_INDEX;
2152 case C2_BAD_VALUE:
2153 return BAD_VALUE;
2154 case C2_BLOCKING:
2155 return WOULD_BLOCK;
2156 case C2_DUPLICATE:
2157 return ALREADY_EXISTS;
2158 case C2_NO_INIT:
2159 return NO_INIT;
2160 case C2_NO_MEMORY:
2161 return NO_MEMORY;
2162 case C2_NOT_FOUND:
2163 return NAME_NOT_FOUND;
2164 case C2_TIMED_OUT:
2165 return TIMED_OUT;
2166 case C2_BAD_STATE:
2167 case C2_CANCELED:
2168 case C2_CANNOT_DO:
2169 case C2_CORRUPTED:
2170 case C2_OMITTED:
2171 case C2_REFUSED:
2172 return UNKNOWN_ERROR;
2173 default:
2174 return -static_cast<status_t>(c2s);
2175 }
2176}
2177
2178} // namespace android