blob: 99aa593c18fb2a4fe274e0f11b887768dab18101 [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 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800927 }
Wonsik Kima79c5522022-01-18 16:29:24 -0800928 if (hdrDynamicInfo
929 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800930 hdr.validTypes |= HdrMetadata::HDR10PLUS;
931 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -0800932 hdrDynamicInfo->m.data,
933 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800934 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800935 qbi.setHdrMetadata(hdr);
Wonsik Kima79c5522022-01-18 16:29:24 -0800936
937 SetHdrMetadataToGralloc4Handle(hdrStaticInfo, hdrDynamicInfo, block.handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800938 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800939 // we don't have dirty regions
940 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800941 android::IGraphicBufferProducer::QueueBufferOutput qbo;
942 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
943 if (result != OK) {
944 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800945 if (result == NO_INIT) {
946 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
947 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800948 return result;
949 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800950
951 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
952 ALOGD("[%s] queue buffer successful", mName);
953 } else {
954 ALOGV("[%s] queue buffer successful", mName);
955 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800956
957 int64_t mediaTimeUs = 0;
958 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
959 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
960
961 return OK;
962}
963
964status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
965 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
966 bool released = false;
967 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700968 Mutexed<Input>::Locked input(mInput);
969 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800970 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800971 }
972 }
973 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700974 Mutexed<Output>::Locked output(mOutput);
975 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800976 released = true;
977 }
978 }
979 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800980 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800981 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800982 } else {
983 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
984 }
985 return OK;
986}
987
988void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
989 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700990 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800991
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700992 if (!input->buffers->isArrayMode()) {
993 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800994 }
995
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700996 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800997}
998
999void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1000 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001001 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001002
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001003 if (!output->buffers->isArrayMode()) {
1004 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001005 }
1006
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001007 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001008}
1009
1010status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001011 const sp<AMessage> &inputFormat,
1012 const sp<AMessage> &outputFormat,
1013 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001014 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1015 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001016 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001017 C2PortReorderBufferDepthTuning::output reorderDepth;
1018 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001019 C2PortActualDelayTuning::input inputDelay(0);
1020 C2PortActualDelayTuning::output outputDelay(0);
1021 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001022 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001023
Pawin Vongmasa36653902018-11-15 00:10:25 -08001024 c2_status_t err = mComponent->query(
1025 {
1026 &iStreamFormat,
1027 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001028 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001029 &reorderDepth,
1030 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001031 &inputDelay,
1032 &pipelineDelay,
1033 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001034 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001035 },
1036 {},
1037 C2_DONT_BLOCK,
1038 nullptr);
1039 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001040 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001041 return UNKNOWN_ERROR;
1042 }
1043 } else if (err != C2_OK) {
1044 return UNKNOWN_ERROR;
1045 }
1046
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001047 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1048 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1049 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1050
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001051 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1052 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001053
Pawin Vongmasa36653902018-11-15 00:10:25 -08001054 // TODO: get this from input format
1055 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1056
Sungtak Lee04b30352020-07-27 13:57:25 -07001057 // secure mode is a static parameter (shall not change in the executing state)
1058 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1059
Pawin Vongmasa36653902018-11-15 00:10:25 -08001060 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001061 int poolMask = GetCodec2PoolMask();
1062 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001063
1064 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001065 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001066 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001067 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1068 API_REFLECTION |
1069 API_VALUES |
1070 API_CURRENT_VALUES |
1071 API_DEPENDENCY |
1072 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001073 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1074 C2StreamSampleRateInfo::input sampleRate(0u);
1075 C2StreamChannelCountInfo::input channelCount(0u);
1076 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001077 std::shared_ptr<C2BlockPool> pool;
1078 {
1079 Mutexed<BlockPools>::Locked pools(mBlockPools);
1080
1081 // set default allocator ID.
1082 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001083 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001084
1085 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1086 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1087 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001088 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001089 std::vector<C2Param *> stackParams({&featuresSetting});
1090 if (audioEncoder) {
1091 stackParams.push_back(&encoderFrameSize);
1092 stackParams.push_back(&sampleRate);
1093 stackParams.push_back(&channelCount);
1094 stackParams.push_back(&pcmEncoding);
1095 } else {
1096 encoderFrameSize.invalidate();
1097 sampleRate.invalidate();
1098 channelCount.invalidate();
1099 pcmEncoding.invalidate();
1100 }
1101 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001102 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1103 C2_DONT_BLOCK,
1104 &params);
1105 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1106 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1107 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001108 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001109 C2PortAllocatorsTuning::input *inputAllocators =
1110 C2PortAllocatorsTuning::input::From(params[0].get());
1111 if (inputAllocators && inputAllocators->flexCount() > 0) {
1112 std::shared_ptr<C2Allocator> allocator;
1113 // verify allocator IDs and resolve default allocator
1114 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1115 if (allocator) {
1116 pools->inputAllocatorId = allocator->getId();
1117 } else {
1118 ALOGD("[%s] component requested invalid input allocator ID %u",
1119 mName, inputAllocators->m.values[0]);
1120 }
1121 }
1122 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001123 if (featuresSetting) {
1124 apiFeatures = featuresSetting.value;
1125 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001126
1127 // TODO: use C2Component wrapper to associate this pool with ourselves
1128 if ((poolMask >> pools->inputAllocatorId) & 1) {
1129 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1130 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1131 mName, pools->inputAllocatorId,
1132 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1133 asString(err), err);
1134 } else {
1135 err = C2_NOT_FOUND;
1136 }
1137 if (err != C2_OK) {
1138 C2BlockPool::local_id_t inputPoolId =
1139 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1140 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1141 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1142 mName, (unsigned long long)inputPoolId,
1143 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1144 asString(err), err);
1145 if (err != C2_OK) {
1146 return NO_MEMORY;
1147 }
1148 }
1149 pools->inputPool = pool;
1150 }
1151
Wonsik Kim51051262018-11-28 13:59:05 -08001152 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001153 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001154 input->inputDelay = inputDelayValue;
1155 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001156 input->numSlots = numInputSlots;
1157 input->extraBuffers.flush();
1158 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001159 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001160 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1161 input->frameReassembler.init(
1162 pool,
1163 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1164 encoderFrameSize.value,
1165 sampleRate.value,
1166 channelCount.value,
1167 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1168 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001169 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1170 // For encrypted content, framework decrypts source buffer (ashmem) into
1171 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001172 if (!buffersBoundToCodec
1173 && !input->frameReassembler
1174 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001175 input->buffers.reset(new SlotInputBuffers(mName));
1176 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001177 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001178 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001179 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001180 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001181 // This is to ensure buffers do not get released prematurely.
1182 // TODO: handle this without going into array mode
1183 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001184 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001185 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001186 }
1187 } else {
1188 if (hasCryptoOrDescrambler()) {
1189 int32_t capacity = kLinearBufferSize;
1190 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1191 if ((size_t)capacity > kMaxLinearBufferSize) {
1192 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1193 capacity = kMaxLinearBufferSize;
1194 }
1195 if (mDealer == nullptr) {
1196 mDealer = new MemoryDealer(
1197 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001198 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001199 "EncryptedLinearInputBuffers");
1200 mDecryptDestination = mDealer->allocate((size_t)capacity);
1201 }
1202 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001203 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1204 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001205 } else {
1206 mHeapSeqNum = -1;
1207 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001208 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001209 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001210 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001211 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001212 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001213 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001214 }
1215 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001216 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001217
1218 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001219 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001220 } else {
1221 // TODO: error
1222 }
Wonsik Kim51051262018-11-28 13:59:05 -08001223
1224 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001225 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001226 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001227 }
1228
1229 if (outputFormat != nullptr) {
1230 sp<IGraphicBufferProducer> outputSurface;
1231 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001232 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001233 {
1234 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001235 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001236 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001237 outputSurface = output->surface ?
1238 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001239 if (outputSurface) {
1240 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1241 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001242 outputGeneration = output->generation;
1243 }
1244
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001245 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001246 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001247 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001248
1249 {
1250 Mutexed<BlockPools>::Locked pools(mBlockPools);
1251
David Stevensc3fbb282021-01-18 18:11:20 +09001252 prevOutputPoolId = pools->outputPoolId;
1253
Pawin Vongmasa36653902018-11-15 00:10:25 -08001254 // set default allocator ID.
1255 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001256 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001257
1258 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1259 // unsuccessful.
1260 std::vector<std::unique_ptr<C2Param>> params;
1261 err = mComponent->query({ },
1262 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1263 C2_DONT_BLOCK,
1264 &params);
1265 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1266 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1267 mName, params.size(), asString(err), err);
1268 } else if (err == C2_OK && params.size() == 1) {
1269 C2PortAllocatorsTuning::output *outputAllocators =
1270 C2PortAllocatorsTuning::output::From(params[0].get());
1271 if (outputAllocators && outputAllocators->flexCount() > 0) {
1272 std::shared_ptr<C2Allocator> allocator;
1273 // verify allocator IDs and resolve default allocator
1274 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1275 if (allocator) {
1276 pools->outputAllocatorId = allocator->getId();
1277 } else {
1278 ALOGD("[%s] component requested invalid output allocator ID %u",
1279 mName, outputAllocators->m.values[0]);
1280 }
1281 }
1282 }
1283
1284 // use bufferqueue if outputting to a surface.
1285 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1286 // if unsuccessful.
1287 if (outputSurface) {
1288 params.clear();
1289 err = mComponent->query({ },
1290 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1291 C2_DONT_BLOCK,
1292 &params);
1293 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1294 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1295 mName, params.size(), asString(err), err);
1296 } else if (err == C2_OK && params.size() == 1) {
1297 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1298 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1299 if (surfaceAllocator) {
1300 std::shared_ptr<C2Allocator> allocator;
1301 // verify allocator IDs and resolve default allocator
1302 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1303 if (allocator) {
1304 pools->outputAllocatorId = allocator->getId();
1305 } else {
1306 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1307 mName, surfaceAllocator->value);
1308 err = C2_BAD_VALUE;
1309 }
1310 }
1311 }
1312 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1313 && err != C2_OK
1314 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1315 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1316 }
1317 }
1318
1319 if ((poolMask >> pools->outputAllocatorId) & 1) {
1320 err = mComponent->createBlockPool(
1321 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1322 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1323 mName, pools->outputAllocatorId,
1324 (unsigned long long)pools->outputPoolId,
1325 asString(err));
1326 } else {
1327 err = C2_NOT_FOUND;
1328 }
1329 if (err != C2_OK) {
1330 // use basic pool instead
1331 pools->outputPoolId =
1332 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1333 }
1334
1335 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1336 // component.
1337 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1338 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1339
1340 std::vector<std::unique_ptr<C2SettingResult>> failures;
1341 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1342 ALOGD("[%s] Configured output block pool ids %llu => %s",
1343 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1344 outputPoolId_ = pools->outputPoolId;
1345 }
1346
David Stevensc3fbb282021-01-18 18:11:20 +09001347 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1348 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1349 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1350 if (err != C2_OK) {
1351 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1352 (unsigned long long) prevOutputPoolId, asString(err), err);
1353 }
1354 }
1355
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001356 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001357 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001358 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001359 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001360 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001361 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001362 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001363 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001364 }
1365 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001366 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001367 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001368 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001369
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001370 output->buffers->clearStash();
1371 if (reorderDepth) {
1372 output->buffers->setReorderDepth(reorderDepth.value);
1373 }
1374 if (reorderKey) {
1375 output->buffers->setReorderKey(reorderKey.value);
1376 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001377
1378 // Try to set output surface to created block pool if given.
1379 if (outputSurface) {
1380 mComponent->setOutputSurface(
1381 outputPoolId_,
1382 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001383 outputGeneration,
1384 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001385 } else {
1386 // configure CPU read consumer usage
1387 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1388 std::vector<std::unique_ptr<C2SettingResult>> failures;
1389 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1390 // do not print error message for now as most components may not yet
1391 // support this setting
1392 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1393 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 }
1395
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001396 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001397 if (buffersBoundToCodec) {
1398 // WORKAROUND: if we're using early CSD workaround we convert to
1399 // array mode, to appease apps assuming the output
1400 // buffers to be of the same size.
1401 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1402 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001403
1404 int32_t channelCount;
1405 int32_t sampleRate;
1406 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1407 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1408 int32_t delay = 0;
1409 int32_t padding = 0;;
1410 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1411 delay = 0;
1412 }
1413 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1414 padding = 0;
1415 }
1416 if (delay || padding) {
1417 // We need write access to the buffers, and we're already in
1418 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001419 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001420 }
1421 }
1422 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001423
1424 int32_t tunneled = 0;
1425 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1426 tunneled = 0;
1427 }
1428 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001429 }
1430
1431 // Set up pipeline control. This has to be done after mInputBuffers and
1432 // mOutputBuffers are initialized to make sure that lingering callbacks
1433 // about buffers from the previous generation do not interfere with the
1434 // newly initialized pipeline capacity.
1435
Wonsik Kim62545252021-01-20 11:25:41 -08001436 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001437 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001438 watcher->inputDelay(inputDelayValue)
1439 .pipelineDelay(pipelineDelayValue)
1440 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001441 .smoothnessFactor(kSmoothnessFactor);
1442 watcher->flush();
1443 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001444
1445 mInputMetEos = false;
1446 mSync.start();
1447 return OK;
1448}
1449
1450status_t CCodecBufferChannel::requestInitialInputBuffers() {
1451 if (mInputSurface) {
1452 return OK;
1453 }
1454
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001455 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001456 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1457 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1458 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001459 return UNKNOWN_ERROR;
1460 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001461 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001462
1463 struct ClientInputBuffer {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001464 size_t index;
1465 sp<MediaCodecBuffer> buffer;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001466 size_t capacity;
1467 };
1468 std::list<ClientInputBuffer> clientInputBuffers;
1469
1470 {
1471 Mutexed<Input>::Locked input(mInput);
1472 while (clientInputBuffers.size() < numInputSlots) {
1473 ClientInputBuffer clientInputBuffer;
1474 if (!input->buffers->requestNewBuffer(&clientInputBuffer.index,
1475 &clientInputBuffer.buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001476 break;
1477 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001478 clientInputBuffer.capacity = clientInputBuffer.buffer->capacity();
1479 clientInputBuffers.emplace_back(std::move(clientInputBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001480 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001481 }
1482 if (clientInputBuffers.empty()) {
1483 ALOGW("[%s] start: cannot allocate memory at all", mName);
1484 return NO_MEMORY;
1485 } else if (clientInputBuffers.size() < numInputSlots) {
1486 ALOGD("[%s] start: cannot allocate memory for all slots, "
1487 "only %zu buffers allocated",
1488 mName, clientInputBuffers.size());
1489 } else {
1490 ALOGV("[%s] %zu initial input buffers available",
1491 mName, clientInputBuffers.size());
1492 }
1493 // Sort input buffers by their capacities in increasing order.
1494 clientInputBuffers.sort(
1495 [](const ClientInputBuffer& a, const ClientInputBuffer& b) {
1496 return a.capacity < b.capacity;
1497 });
1498
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001499 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1500 mFlushedConfigs.lock()->swap(flushedConfigs);
1501 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001502 {
1503 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1504 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1505 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1506 watcher->onWorkQueued(
1507 work->input.ordinal.frameIndex.peeku(),
1508 std::vector(work->input.buffers),
1509 now);
1510 }
1511 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001512 err = mComponent->queue(&flushedConfigs);
1513 if (err != C2_OK) {
1514 ALOGW("[%s] Error while queueing a flushed config", mName);
1515 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001516 }
1517 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001518 if (oStreamFormat.value == C2BufferData::LINEAR &&
1519 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
1520 sp<MediaCodecBuffer> buffer = clientInputBuffers.front().buffer;
1521 // WORKAROUND: Some apps expect CSD available without queueing
1522 // any input. Queue an empty buffer to get the CSD.
1523 buffer->setRange(0, 0);
1524 buffer->meta()->clear();
1525 buffer->meta()->setInt64("timeUs", 0);
1526 if (queueInputBufferInternal(buffer) != OK) {
1527 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1528 mName);
1529 return UNKNOWN_ERROR;
1530 }
1531 clientInputBuffers.pop_front();
1532 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001533
1534 for (const ClientInputBuffer& clientInputBuffer: clientInputBuffers) {
1535 mCallback->onInputBufferAvailable(
1536 clientInputBuffer.index,
1537 clientInputBuffer.buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001538 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001539
Pawin Vongmasa36653902018-11-15 00:10:25 -08001540 return OK;
1541}
1542
1543void CCodecBufferChannel::stop() {
1544 mSync.stop();
1545 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001546}
1547
Wonsik Kim936a89c2020-05-08 16:07:50 -07001548void CCodecBufferChannel::reset() {
1549 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001550 if (mInputSurface != nullptr) {
1551 mInputSurface.reset();
1552 }
1553 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001554 {
1555 Mutexed<Input>::Locked input(mInput);
1556 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001557 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001558 }
1559 {
1560 Mutexed<Output>::Locked output(mOutput);
1561 output->buffers.reset();
1562 }
1563}
1564
1565void CCodecBufferChannel::release() {
1566 mComponent.reset();
1567 mInputAllocator.reset();
1568 mOutputSurface.lock()->surface.clear();
1569 {
1570 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1571 blockPools->inputPool.reset();
1572 blockPools->outputPoolIntf.reset();
1573 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001574 setCrypto(nullptr);
1575 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001576}
1577
Pawin Vongmasa36653902018-11-15 00:10:25 -08001578void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1579 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001580 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001581 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001582 {
1583 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1584 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1585 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1586 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1587 watcher->onWorkDone(frameIndex);
1588 continue;
1589 }
1590 if (work->input.buffers.empty()
1591 || work->input.buffers.front() == nullptr
1592 || work->input.buffers.front()->data().linearBlocks().empty()) {
1593 ALOGD("[%s] no linear codec config data found", mName);
1594 watcher->onWorkDone(frameIndex);
1595 continue;
1596 }
1597 std::unique_ptr<C2Work> copy(new C2Work);
1598 copy->input.flags = C2FrameData::flags_t(
1599 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1600 copy->input.ordinal = work->input.ordinal;
1601 copy->input.ordinal.frameIndex = mFrameIndex++;
1602 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1603 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1604 }
1605 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1606 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1607 }
1608 copy->input.infoBuffers.insert(
1609 copy->input.infoBuffers.begin(),
1610 work->input.infoBuffers.begin(),
1611 work->input.infoBuffers.end());
1612 copy->worklets.emplace_back(new C2Worklet);
1613 configs.push_back(std::move(copy));
1614 watcher->onWorkDone(frameIndex);
1615 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001616 }
1617 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001618 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001619 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001620 Mutexed<Input>::Locked input(mInput);
1621 input->buffers->flush();
1622 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001623 }
1624 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001625 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001626 if (output->buffers) {
1627 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001628 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001629 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001630 }
1631}
1632
1633void CCodecBufferChannel::onWorkDone(
1634 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001635 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001636 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001637 feedInputBufferIfAvailable();
1638 }
1639}
1640
1641void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001642 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001643 if (mInputSurface) {
1644 return;
1645 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001646 std::shared_ptr<C2Buffer> buffer =
1647 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001648 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001649 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001650 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001651 if (input->lastFlushIndex >= frameIndex) {
1652 ALOGD("[%s] Ignoring stale input buffer done callback: "
1653 "last flush index = %lld, frameIndex = %lld",
1654 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1655 } else {
1656 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1657 if (!newInputSlotAvailable) {
1658 (void)input->extraBuffers.expireComponentBuffer(buffer);
1659 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001660 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001661 }
1662 if (newInputSlotAvailable) {
1663 feedInputBufferIfAvailable();
1664 }
1665}
1666
1667bool CCodecBufferChannel::handleWork(
1668 std::unique_ptr<C2Work> work,
1669 const sp<AMessage> &outputFormat,
1670 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001671 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001672 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001673 if (!output->buffers) {
1674 return false;
1675 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001676 }
1677
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001678 // Whether the output buffer should be reported to the client or not.
1679 bool notifyClient = false;
1680
1681 if (work->result == C2_OK){
1682 notifyClient = true;
1683 } else if (work->result == C2_NOT_FOUND) {
1684 ALOGD("[%s] flushed work; ignored.", mName);
1685 } else {
1686 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1687 // the config update.
1688 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1689 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1690 return false;
1691 }
1692
1693 if ((work->input.ordinal.frameIndex -
1694 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001695 // Discard frames from previous generation.
1696 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001697 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001698 }
1699
Wonsik Kim524b0582019-03-12 11:28:57 -07001700 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001701 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001702 || !(work->worklets.front()->output.flags &
1703 C2FrameData::FLAG_INCOMPLETE))) {
1704 mPipelineWatcher.lock()->onWorkDone(
1705 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001706 }
1707
1708 // NOTE: MediaCodec usage supposedly have only one worklet
1709 if (work->worklets.size() != 1u) {
1710 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1711 mName, work->worklets.size());
1712 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1713 return false;
1714 }
1715
1716 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1717
1718 std::shared_ptr<C2Buffer> buffer;
1719 // NOTE: MediaCodec usage supposedly have only one output stream.
1720 if (worklet->output.buffers.size() > 1u) {
1721 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1722 mName, worklet->output.buffers.size());
1723 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1724 return false;
1725 } else if (worklet->output.buffers.size() == 1u) {
1726 buffer = worklet->output.buffers[0];
1727 if (!buffer) {
1728 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1729 }
1730 }
1731
Wonsik Kim3dedf682021-05-03 10:57:09 -07001732 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1733 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001734 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001735 while (!worklet->output.configUpdate.empty()) {
1736 std::unique_ptr<C2Param> param;
1737 worklet->output.configUpdate.back().swap(param);
1738 worklet->output.configUpdate.pop_back();
1739 switch (param->coreIndex().coreIndex()) {
1740 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1741 C2PortReorderBufferDepthTuning::output reorderDepth;
1742 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001743 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1744 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001745 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001746 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001747 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001748 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1749 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001750 }
1751 break;
1752 }
1753 case C2PortReorderKeySetting::CORE_INDEX: {
1754 C2PortReorderKeySetting::output reorderKey;
1755 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001756 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001757 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1758 mName, reorderKey.value);
1759 } else {
1760 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1761 }
1762 break;
1763 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001764 case C2PortActualDelayTuning::CORE_INDEX: {
1765 if (param->isGlobal()) {
1766 C2ActualPipelineDelayTuning pipelineDelay;
1767 if (pipelineDelay.updateFrom(*param)) {
1768 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1769 mName, pipelineDelay.value);
1770 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001771 (void)mPipelineWatcher.lock()->pipelineDelay(
1772 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001773 }
1774 }
1775 if (param->forInput()) {
1776 C2PortActualDelayTuning::input inputDelay;
1777 if (inputDelay.updateFrom(*param)) {
1778 ALOGV("[%s] onWorkDone: updating input delay %u",
1779 mName, inputDelay.value);
1780 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001781 (void)mPipelineWatcher.lock()->inputDelay(
1782 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001783 }
1784 }
1785 if (param->forOutput()) {
1786 C2PortActualDelayTuning::output outputDelay;
1787 if (outputDelay.updateFrom(*param)) {
1788 ALOGV("[%s] onWorkDone: updating output delay %u",
1789 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001790 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001791 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001792 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001793
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001794 }
1795 }
1796 break;
1797 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001798 case C2PortTunnelSystemTime::CORE_INDEX: {
1799 C2PortTunnelSystemTime::output frameRenderTime;
1800 if (frameRenderTime.updateFrom(*param)) {
1801 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1802 mName, (long long)frameRenderTime.value,
1803 (long long)worklet->output.ordinal.timestamp.peekll());
1804 mCCodecCallback->onOutputFramesRendered(
1805 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1806 }
1807 break;
1808 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001809 case C2StreamTunnelHoldRender::CORE_INDEX: {
1810 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1811 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1812 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1813 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1814 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1815 mCCodecCallback->onFirstTunnelFrameReady();
1816 break;
1817 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001818 default:
1819 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1820 mName, param->index());
1821 break;
1822 }
1823 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001824 if (newInputDelay || newPipelineDelay) {
1825 Mutexed<Input>::Locked input(mInput);
1826 size_t newNumSlots =
1827 newInputDelay.value_or(input->inputDelay) +
1828 newPipelineDelay.value_or(input->pipelineDelay) +
1829 kSmoothnessFactor;
1830 if (input->buffers->isArrayMode()) {
1831 if (input->numSlots >= newNumSlots) {
1832 input->numExtraSlots = 0;
1833 } else {
1834 input->numExtraSlots = newNumSlots - input->numSlots;
1835 }
1836 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1837 mName, input->numExtraSlots);
1838 } else {
1839 input->numSlots = newNumSlots;
1840 }
1841 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001842 size_t numOutputSlots = 0;
1843 uint32_t reorderDepth = 0;
1844 bool outputBuffersChanged = false;
1845 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
1846 Mutexed<Output>::Locked output(mOutput);
1847 if (!output->buffers) {
1848 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001849 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001850 numOutputSlots = output->numSlots;
1851 if (newReorderKey) {
1852 output->buffers->setReorderKey(newReorderKey.value());
1853 }
1854 if (newReorderDepth) {
1855 output->buffers->setReorderDepth(newReorderDepth.value());
1856 }
1857 reorderDepth = output->buffers->getReorderDepth();
1858 if (newOutputDelay) {
1859 output->outputDelay = newOutputDelay.value();
1860 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
1861 if (output->numSlots < numOutputSlots) {
1862 output->numSlots = numOutputSlots;
1863 if (output->buffers->isArrayMode()) {
1864 OutputBuffersArray *array =
1865 (OutputBuffersArray *)output->buffers.get();
1866 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1867 mName, numOutputSlots);
1868 array->grow(numOutputSlots);
1869 outputBuffersChanged = true;
1870 }
1871 }
1872 }
1873 numOutputSlots = output->numSlots;
1874 }
1875 if (outputBuffersChanged) {
1876 mCCodecCallback->onOutputBuffersChanged();
1877 }
1878 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07001879 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07001880 {
1881 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1882 maxDequeueCount = output->maxDequeueBuffers =
1883 numOutputSlots + reorderDepth + kRenderingDepth;
1884 if (output->surface) {
1885 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1886 }
1887 }
1888 if (maxDequeueCount > 0) {
1889 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001890 }
1891 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001892
Pawin Vongmasa36653902018-11-15 00:10:25 -08001893 int32_t flags = 0;
1894 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1895 flags |= MediaCodec::BUFFER_FLAG_EOS;
1896 ALOGV("[%s] onWorkDone: output EOS", mName);
1897 }
1898
Pawin Vongmasa36653902018-11-15 00:10:25 -08001899 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1900 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1901 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1902 // shall correspond to the client input timesamp (in customOrdinal). By using the
1903 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1904 // produces multiple output.
1905 c2_cntr64_t timestamp =
1906 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1907 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001908 if (mInputSurface != nullptr) {
1909 // When using input surface we need to restore the original input timestamp.
1910 timestamp = work->input.ordinal.customOrdinal;
1911 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001912 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1913 mName,
1914 work->input.ordinal.customOrdinal.peekll(),
1915 work->input.ordinal.timestamp.peekll(),
1916 worklet->output.ordinal.timestamp.peekll(),
1917 timestamp.peekll());
1918
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001919 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001920 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001921 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001922 if (output->buffers && outputFormat) {
1923 output->buffers->updateSkipCutBuffer(outputFormat);
1924 output->buffers->setFormat(outputFormat);
1925 }
1926 if (!notifyClient) {
1927 return false;
1928 }
1929 size_t index;
1930 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07001931 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001932 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1933 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1934 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1935
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001936 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001937 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001938 } else {
1939 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001940 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001941 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001942 return false;
1943 }
1944 }
1945
Wonsik Kimec585c32021-10-01 01:11:00 -07001946 bool drop = false;
1947 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
1948 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
1949 drop = true;
1950 }
1951
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001952 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07001953 if (mTunneled && drop && outputFormat) {
1954 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
1955 mName, work->input.ordinal.frameIndex.peekull());
1956 } else {
1957 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1958 mName, work->input.ordinal.frameIndex.peekull());
1959 notifyClient = false;
1960 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001961 }
1962
1963 if (buffer) {
1964 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1965 // TODO: properly translate these to metadata
1966 switch (info->coreIndex().coreIndex()) {
1967 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001968 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001969 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1970 }
1971 break;
1972 default:
1973 break;
1974 }
1975 }
1976 }
1977
1978 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001979 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07001980 if (!output->buffers) {
1981 return false;
1982 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001983 output->buffers->pushToStash(
1984 buffer,
1985 notifyClient,
1986 timestamp.peek(),
1987 flags,
1988 outputFormat,
1989 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001990 }
1991 sendOutputBuffers();
1992 return true;
1993}
1994
1995void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001996 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001997 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001998 sp<MediaCodecBuffer> outBuffer;
1999 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002000
2001 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002002 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002003 if (!output->buffers) {
2004 return;
2005 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002006 action = output->buffers->popFromStashAndRegister(
2007 &c2Buffer, &index, &outBuffer);
2008 switch (action) {
2009 case OutputBuffers::SKIP:
2010 return;
2011 case OutputBuffers::DISCARD:
2012 break;
2013 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00002014 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002015 mCallback->onOutputBufferAvailable(index, outBuffer);
2016 break;
2017 case OutputBuffers::REALLOCATE:
2018 if (!output->buffers->isArrayMode()) {
2019 output->buffers =
2020 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002021 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002022 static_cast<OutputBuffersArray*>(output->buffers.get())->
2023 realloc(c2Buffer);
2024 output.unlock();
2025 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002026 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002027 case OutputBuffers::RETRY:
2028 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2029 mName);
2030 return;
2031 default:
2032 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2033 "corrupted BufferAction value (%d) "
2034 "returned from popFromStashAndRegister.",
2035 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002036 return;
2037 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002038 }
2039}
2040
2041status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
2042 static std::atomic_uint32_t surfaceGeneration{0};
2043 uint32_t generation = (getpid() << 10) |
2044 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2045 & ((1 << 10) - 1));
2046
2047 sp<IGraphicBufferProducer> producer;
Sungtak Leedb14cba2021-04-10 00:50:23 -07002048 int maxDequeueCount = mOutputSurface.lock()->maxDequeueBuffers;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002049 if (newSurface) {
2050 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002051 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002052 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002053 producer = newSurface->getIGraphicBufferProducer();
2054 producer->setGenerationNumber(generation);
2055 } else {
2056 ALOGE("[%s] setting output surface to null", mName);
2057 return INVALID_OPERATION;
2058 }
2059
2060 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2061 C2BlockPool::local_id_t outputPoolId;
2062 {
2063 Mutexed<BlockPools>::Locked pools(mBlockPools);
2064 outputPoolId = pools->outputPoolId;
2065 outputPoolIntf = pools->outputPoolIntf;
2066 }
2067
2068 if (outputPoolIntf) {
2069 if (mComponent->setOutputSurface(
2070 outputPoolId,
2071 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002072 generation,
2073 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002074 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2075 return INVALID_OPERATION;
2076 }
2077 }
2078
2079 {
2080 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2081 output->surface = newSurface;
2082 output->generation = generation;
2083 }
2084
2085 return OK;
2086}
2087
Wonsik Kimab34ed62019-01-31 15:28:46 -08002088PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002089 // When client pushed EOS, we want all the work to be done quickly.
2090 // Otherwise, component may have stalled work due to input starvation up to
2091 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002092 size_t n = 0;
2093 if (!mInputMetEos) {
2094 size_t outputDelay = mOutput.lock()->outputDelay;
2095 Mutexed<Input>::Locked input(mInput);
2096 n = input->inputDelay + input->pipelineDelay + outputDelay;
2097 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002098 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002099}
2100
Pawin Vongmasa36653902018-11-15 00:10:25 -08002101void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2102 mMetaMode = mode;
2103}
2104
Wonsik Kim596187e2019-10-25 12:44:10 -07002105void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002106 if (mCrypto != nullptr) {
2107 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2108 mCrypto->unsetHeap(entry.second);
2109 }
2110 mHeapSeqNumMap.clear();
2111 if (mHeapSeqNum >= 0) {
2112 mCrypto->unsetHeap(mHeapSeqNum);
2113 mHeapSeqNum = -1;
2114 }
2115 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002116 mCrypto = crypto;
2117}
2118
2119void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2120 mDescrambler = descrambler;
2121}
2122
Pawin Vongmasa36653902018-11-15 00:10:25 -08002123status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2124 // C2_OK is always translated to OK.
2125 if (c2s == C2_OK) {
2126 return OK;
2127 }
2128
2129 // Operation-dependent translation
2130 // TODO: Add as necessary
2131 switch (c2op) {
2132 case C2_OPERATION_Component_start:
2133 switch (c2s) {
2134 case C2_NO_MEMORY:
2135 return NO_MEMORY;
2136 default:
2137 return UNKNOWN_ERROR;
2138 }
2139 default:
2140 break;
2141 }
2142
2143 // Backup operation-agnostic translation
2144 switch (c2s) {
2145 case C2_BAD_INDEX:
2146 return BAD_INDEX;
2147 case C2_BAD_VALUE:
2148 return BAD_VALUE;
2149 case C2_BLOCKING:
2150 return WOULD_BLOCK;
2151 case C2_DUPLICATE:
2152 return ALREADY_EXISTS;
2153 case C2_NO_INIT:
2154 return NO_INIT;
2155 case C2_NO_MEMORY:
2156 return NO_MEMORY;
2157 case C2_NOT_FOUND:
2158 return NAME_NOT_FOUND;
2159 case C2_TIMED_OUT:
2160 return TIMED_OUT;
2161 case C2_BAD_STATE:
2162 case C2_CANCELED:
2163 case C2_CANNOT_DO:
2164 case C2_CORRUPTED:
2165 case C2_OMITTED:
2166 case C2_REFUSED:
2167 return UNKNOWN_ERROR;
2168 default:
2169 return -static_cast<status_t>(c2s);
2170 }
2171}
2172
2173} // namespace android