blob: 0de0b7744f3bc5340ee4d8a33888a98ec9737863 [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
Pawin Vongmasa36653902018-11-15 00:10:25 -0800843 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
844 if (blocks.size() != 1u) {
845 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
846 return UNKNOWN_ERROR;
847 }
848 const C2ConstGraphicBlock &block = blocks.front();
849
850 // TODO: revisit this after C2Fence implementation.
851 android::IGraphicBufferProducer::QueueBufferInput qbi(
852 timestampNs,
853 false, // droppable
854 dataSpace,
855 Rect(blocks.front().crop().left,
856 blocks.front().crop().top,
857 blocks.front().crop().right(),
858 blocks.front().crop().bottom()),
859 videoScalingMode,
860 transform,
861 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800862 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800863 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800864 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800865 // If mastering max and min luminance fields are 0, do not use them.
866 // It indicates the value may not be present in the stream.
867 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
868 hdrStaticInfo->mastering.minLuminance > 0.0f) {
869 struct android_smpte2086_metadata smpte2086_meta = {
870 .displayPrimaryRed = {
871 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
872 },
873 .displayPrimaryGreen = {
874 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
875 },
876 .displayPrimaryBlue = {
877 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
878 },
879 .whitePoint = {
880 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
881 },
882 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
883 .minLuminance = hdrStaticInfo->mastering.minLuminance,
884 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800885 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800886 hdr.smpte2086 = smpte2086_meta;
887 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700888 // If the content light level fields are 0, do not use them, it
889 // indicates the value may not be present in the stream.
890 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
891 struct android_cta861_3_metadata cta861_meta = {
892 .maxContentLightLevel = hdrStaticInfo->maxCll,
893 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
894 };
895 hdr.validTypes |= HdrMetadata::CTA861_3;
896 hdr.cta8613 = cta861_meta;
897 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800898 }
899 if (hdr10PlusInfo) {
900 hdr.validTypes |= HdrMetadata::HDR10PLUS;
901 hdr.hdr10plus.assign(
902 hdr10PlusInfo->m.value,
903 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
904 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800905 qbi.setHdrMetadata(hdr);
906 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800907 // we don't have dirty regions
908 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800909 android::IGraphicBufferProducer::QueueBufferOutput qbo;
910 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
911 if (result != OK) {
912 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800913 if (result == NO_INIT) {
914 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
915 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800916 return result;
917 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800918
919 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
920 ALOGD("[%s] queue buffer successful", mName);
921 } else {
922 ALOGV("[%s] queue buffer successful", mName);
923 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800924
925 int64_t mediaTimeUs = 0;
926 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
927 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
928
929 return OK;
930}
931
932status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
933 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
934 bool released = false;
935 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700936 Mutexed<Input>::Locked input(mInput);
937 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800938 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800939 }
940 }
941 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700942 Mutexed<Output>::Locked output(mOutput);
943 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800944 released = true;
945 }
946 }
947 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800948 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800949 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800950 } else {
951 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
952 }
953 return OK;
954}
955
956void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
957 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700958 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800959
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700960 if (!input->buffers->isArrayMode()) {
961 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800962 }
963
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700964 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800965}
966
967void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
968 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700969 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800970
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700971 if (!output->buffers->isArrayMode()) {
972 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800973 }
974
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700975 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800976}
977
978status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800979 const sp<AMessage> &inputFormat,
980 const sp<AMessage> &outputFormat,
981 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800982 C2StreamBufferTypeSetting::input iStreamFormat(0u);
983 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -0800984 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800985 C2PortReorderBufferDepthTuning::output reorderDepth;
986 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800987 C2PortActualDelayTuning::input inputDelay(0);
988 C2PortActualDelayTuning::output outputDelay(0);
989 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -0700990 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -0800991
Pawin Vongmasa36653902018-11-15 00:10:25 -0800992 c2_status_t err = mComponent->query(
993 {
994 &iStreamFormat,
995 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -0800996 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800997 &reorderDepth,
998 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800999 &inputDelay,
1000 &pipelineDelay,
1001 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001002 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001003 },
1004 {},
1005 C2_DONT_BLOCK,
1006 nullptr);
1007 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001008 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001009 return UNKNOWN_ERROR;
1010 }
1011 } else if (err != C2_OK) {
1012 return UNKNOWN_ERROR;
1013 }
1014
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001015 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1016 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1017 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1018
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001019 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1020 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001021
Pawin Vongmasa36653902018-11-15 00:10:25 -08001022 // TODO: get this from input format
1023 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1024
Sungtak Lee04b30352020-07-27 13:57:25 -07001025 // secure mode is a static parameter (shall not change in the executing state)
1026 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1027
Pawin Vongmasa36653902018-11-15 00:10:25 -08001028 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001029 int poolMask = GetCodec2PoolMask();
1030 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001031
1032 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001033 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001034 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001035 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1036 API_REFLECTION |
1037 API_VALUES |
1038 API_CURRENT_VALUES |
1039 API_DEPENDENCY |
1040 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001041 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1042 C2StreamSampleRateInfo::input sampleRate(0u);
1043 C2StreamChannelCountInfo::input channelCount(0u);
1044 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001045 std::shared_ptr<C2BlockPool> pool;
1046 {
1047 Mutexed<BlockPools>::Locked pools(mBlockPools);
1048
1049 // set default allocator ID.
1050 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001051 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001052
1053 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1054 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1055 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001056 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001057 std::vector<C2Param *> stackParams({&featuresSetting});
1058 if (audioEncoder) {
1059 stackParams.push_back(&encoderFrameSize);
1060 stackParams.push_back(&sampleRate);
1061 stackParams.push_back(&channelCount);
1062 stackParams.push_back(&pcmEncoding);
1063 } else {
1064 encoderFrameSize.invalidate();
1065 sampleRate.invalidate();
1066 channelCount.invalidate();
1067 pcmEncoding.invalidate();
1068 }
1069 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001070 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1071 C2_DONT_BLOCK,
1072 &params);
1073 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1074 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1075 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001076 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001077 C2PortAllocatorsTuning::input *inputAllocators =
1078 C2PortAllocatorsTuning::input::From(params[0].get());
1079 if (inputAllocators && inputAllocators->flexCount() > 0) {
1080 std::shared_ptr<C2Allocator> allocator;
1081 // verify allocator IDs and resolve default allocator
1082 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1083 if (allocator) {
1084 pools->inputAllocatorId = allocator->getId();
1085 } else {
1086 ALOGD("[%s] component requested invalid input allocator ID %u",
1087 mName, inputAllocators->m.values[0]);
1088 }
1089 }
1090 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001091 if (featuresSetting) {
1092 apiFeatures = featuresSetting.value;
1093 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001094
1095 // TODO: use C2Component wrapper to associate this pool with ourselves
1096 if ((poolMask >> pools->inputAllocatorId) & 1) {
1097 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1098 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1099 mName, pools->inputAllocatorId,
1100 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1101 asString(err), err);
1102 } else {
1103 err = C2_NOT_FOUND;
1104 }
1105 if (err != C2_OK) {
1106 C2BlockPool::local_id_t inputPoolId =
1107 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1108 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1109 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1110 mName, (unsigned long long)inputPoolId,
1111 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1112 asString(err), err);
1113 if (err != C2_OK) {
1114 return NO_MEMORY;
1115 }
1116 }
1117 pools->inputPool = pool;
1118 }
1119
Wonsik Kim51051262018-11-28 13:59:05 -08001120 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001121 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001122 input->inputDelay = inputDelayValue;
1123 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001124 input->numSlots = numInputSlots;
1125 input->extraBuffers.flush();
1126 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001127 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001128 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1129 input->frameReassembler.init(
1130 pool,
1131 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1132 encoderFrameSize.value,
1133 sampleRate.value,
1134 channelCount.value,
1135 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1136 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001137 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1138 // For encrypted content, framework decrypts source buffer (ashmem) into
1139 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001140 if (!buffersBoundToCodec
1141 && !input->frameReassembler
1142 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001143 input->buffers.reset(new SlotInputBuffers(mName));
1144 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001145 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001146 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001147 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001148 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001149 // This is to ensure buffers do not get released prematurely.
1150 // TODO: handle this without going into array mode
1151 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001152 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001153 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001154 }
1155 } else {
1156 if (hasCryptoOrDescrambler()) {
1157 int32_t capacity = kLinearBufferSize;
1158 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1159 if ((size_t)capacity > kMaxLinearBufferSize) {
1160 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1161 capacity = kMaxLinearBufferSize;
1162 }
1163 if (mDealer == nullptr) {
1164 mDealer = new MemoryDealer(
1165 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001166 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001167 "EncryptedLinearInputBuffers");
1168 mDecryptDestination = mDealer->allocate((size_t)capacity);
1169 }
1170 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001171 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1172 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001173 } else {
1174 mHeapSeqNum = -1;
1175 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001176 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001177 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001178 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001179 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001180 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001181 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001182 }
1183 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001184 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001185
1186 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001187 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001188 } else {
1189 // TODO: error
1190 }
Wonsik Kim51051262018-11-28 13:59:05 -08001191
1192 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001193 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001194 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001195 }
1196
1197 if (outputFormat != nullptr) {
1198 sp<IGraphicBufferProducer> outputSurface;
1199 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001200 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001201 {
1202 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001203 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001204 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001205 outputSurface = output->surface ?
1206 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001207 if (outputSurface) {
1208 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1209 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001210 outputGeneration = output->generation;
1211 }
1212
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001213 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001214 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001215 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001216
1217 {
1218 Mutexed<BlockPools>::Locked pools(mBlockPools);
1219
David Stevensc3fbb282021-01-18 18:11:20 +09001220 prevOutputPoolId = pools->outputPoolId;
1221
Pawin Vongmasa36653902018-11-15 00:10:25 -08001222 // set default allocator ID.
1223 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001224 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001225
1226 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1227 // unsuccessful.
1228 std::vector<std::unique_ptr<C2Param>> params;
1229 err = mComponent->query({ },
1230 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1231 C2_DONT_BLOCK,
1232 &params);
1233 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1234 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1235 mName, params.size(), asString(err), err);
1236 } else if (err == C2_OK && params.size() == 1) {
1237 C2PortAllocatorsTuning::output *outputAllocators =
1238 C2PortAllocatorsTuning::output::From(params[0].get());
1239 if (outputAllocators && outputAllocators->flexCount() > 0) {
1240 std::shared_ptr<C2Allocator> allocator;
1241 // verify allocator IDs and resolve default allocator
1242 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1243 if (allocator) {
1244 pools->outputAllocatorId = allocator->getId();
1245 } else {
1246 ALOGD("[%s] component requested invalid output allocator ID %u",
1247 mName, outputAllocators->m.values[0]);
1248 }
1249 }
1250 }
1251
1252 // use bufferqueue if outputting to a surface.
1253 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1254 // if unsuccessful.
1255 if (outputSurface) {
1256 params.clear();
1257 err = mComponent->query({ },
1258 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1259 C2_DONT_BLOCK,
1260 &params);
1261 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1262 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1263 mName, params.size(), asString(err), err);
1264 } else if (err == C2_OK && params.size() == 1) {
1265 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1266 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1267 if (surfaceAllocator) {
1268 std::shared_ptr<C2Allocator> allocator;
1269 // verify allocator IDs and resolve default allocator
1270 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1271 if (allocator) {
1272 pools->outputAllocatorId = allocator->getId();
1273 } else {
1274 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1275 mName, surfaceAllocator->value);
1276 err = C2_BAD_VALUE;
1277 }
1278 }
1279 }
1280 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1281 && err != C2_OK
1282 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1283 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1284 }
1285 }
1286
1287 if ((poolMask >> pools->outputAllocatorId) & 1) {
1288 err = mComponent->createBlockPool(
1289 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1290 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1291 mName, pools->outputAllocatorId,
1292 (unsigned long long)pools->outputPoolId,
1293 asString(err));
1294 } else {
1295 err = C2_NOT_FOUND;
1296 }
1297 if (err != C2_OK) {
1298 // use basic pool instead
1299 pools->outputPoolId =
1300 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1301 }
1302
1303 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1304 // component.
1305 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1306 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1307
1308 std::vector<std::unique_ptr<C2SettingResult>> failures;
1309 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1310 ALOGD("[%s] Configured output block pool ids %llu => %s",
1311 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1312 outputPoolId_ = pools->outputPoolId;
1313 }
1314
David Stevensc3fbb282021-01-18 18:11:20 +09001315 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1316 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
1317 c2_status_t err = mComponent->destroyBlockPool(prevOutputPoolId);
1318 if (err != C2_OK) {
1319 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1320 (unsigned long long) prevOutputPoolId, asString(err), err);
1321 }
1322 }
1323
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001324 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001325 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001326 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001327 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001328 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001329 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001330 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001331 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001332 }
1333 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001334 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001335 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001336 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001337
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001338 output->buffers->clearStash();
1339 if (reorderDepth) {
1340 output->buffers->setReorderDepth(reorderDepth.value);
1341 }
1342 if (reorderKey) {
1343 output->buffers->setReorderKey(reorderKey.value);
1344 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001345
1346 // Try to set output surface to created block pool if given.
1347 if (outputSurface) {
1348 mComponent->setOutputSurface(
1349 outputPoolId_,
1350 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001351 outputGeneration,
1352 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001353 } else {
1354 // configure CPU read consumer usage
1355 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1356 std::vector<std::unique_ptr<C2SettingResult>> failures;
1357 err = mComponent->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
1358 // do not print error message for now as most components may not yet
1359 // support this setting
1360 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1361 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001362 }
1363
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001364 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001365 if (buffersBoundToCodec) {
1366 // WORKAROUND: if we're using early CSD workaround we convert to
1367 // array mode, to appease apps assuming the output
1368 // buffers to be of the same size.
1369 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1370 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001371
1372 int32_t channelCount;
1373 int32_t sampleRate;
1374 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1375 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1376 int32_t delay = 0;
1377 int32_t padding = 0;;
1378 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1379 delay = 0;
1380 }
1381 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1382 padding = 0;
1383 }
1384 if (delay || padding) {
1385 // We need write access to the buffers, and we're already in
1386 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001387 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001388 }
1389 }
1390 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001391
1392 int32_t tunneled = 0;
1393 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1394 tunneled = 0;
1395 }
1396 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001397 }
1398
1399 // Set up pipeline control. This has to be done after mInputBuffers and
1400 // mOutputBuffers are initialized to make sure that lingering callbacks
1401 // about buffers from the previous generation do not interfere with the
1402 // newly initialized pipeline capacity.
1403
Wonsik Kim62545252021-01-20 11:25:41 -08001404 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001405 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001406 watcher->inputDelay(inputDelayValue)
1407 .pipelineDelay(pipelineDelayValue)
1408 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001409 .smoothnessFactor(kSmoothnessFactor);
1410 watcher->flush();
1411 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001412
1413 mInputMetEos = false;
1414 mSync.start();
1415 return OK;
1416}
1417
1418status_t CCodecBufferChannel::requestInitialInputBuffers() {
1419 if (mInputSurface) {
1420 return OK;
1421 }
1422
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001423 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001424 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1425 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1426 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001427 return UNKNOWN_ERROR;
1428 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001429 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001430
1431 struct ClientInputBuffer {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001432 size_t index;
1433 sp<MediaCodecBuffer> buffer;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001434 size_t capacity;
1435 };
1436 std::list<ClientInputBuffer> clientInputBuffers;
1437
1438 {
1439 Mutexed<Input>::Locked input(mInput);
1440 while (clientInputBuffers.size() < numInputSlots) {
1441 ClientInputBuffer clientInputBuffer;
1442 if (!input->buffers->requestNewBuffer(&clientInputBuffer.index,
1443 &clientInputBuffer.buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001444 break;
1445 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001446 clientInputBuffer.capacity = clientInputBuffer.buffer->capacity();
1447 clientInputBuffers.emplace_back(std::move(clientInputBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001448 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001449 }
1450 if (clientInputBuffers.empty()) {
1451 ALOGW("[%s] start: cannot allocate memory at all", mName);
1452 return NO_MEMORY;
1453 } else if (clientInputBuffers.size() < numInputSlots) {
1454 ALOGD("[%s] start: cannot allocate memory for all slots, "
1455 "only %zu buffers allocated",
1456 mName, clientInputBuffers.size());
1457 } else {
1458 ALOGV("[%s] %zu initial input buffers available",
1459 mName, clientInputBuffers.size());
1460 }
1461 // Sort input buffers by their capacities in increasing order.
1462 clientInputBuffers.sort(
1463 [](const ClientInputBuffer& a, const ClientInputBuffer& b) {
1464 return a.capacity < b.capacity;
1465 });
1466
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001467 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1468 mFlushedConfigs.lock()->swap(flushedConfigs);
1469 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07001470 {
1471 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1472 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
1473 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
1474 watcher->onWorkQueued(
1475 work->input.ordinal.frameIndex.peeku(),
1476 std::vector(work->input.buffers),
1477 now);
1478 }
1479 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001480 err = mComponent->queue(&flushedConfigs);
1481 if (err != C2_OK) {
1482 ALOGW("[%s] Error while queueing a flushed config", mName);
1483 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001484 }
1485 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001486 if (oStreamFormat.value == C2BufferData::LINEAR &&
1487 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
1488 sp<MediaCodecBuffer> buffer = clientInputBuffers.front().buffer;
1489 // WORKAROUND: Some apps expect CSD available without queueing
1490 // any input. Queue an empty buffer to get the CSD.
1491 buffer->setRange(0, 0);
1492 buffer->meta()->clear();
1493 buffer->meta()->setInt64("timeUs", 0);
1494 if (queueInputBufferInternal(buffer) != OK) {
1495 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1496 mName);
1497 return UNKNOWN_ERROR;
1498 }
1499 clientInputBuffers.pop_front();
1500 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001501
1502 for (const ClientInputBuffer& clientInputBuffer: clientInputBuffers) {
1503 mCallback->onInputBufferAvailable(
1504 clientInputBuffer.index,
1505 clientInputBuffer.buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001506 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001507
Pawin Vongmasa36653902018-11-15 00:10:25 -08001508 return OK;
1509}
1510
1511void CCodecBufferChannel::stop() {
1512 mSync.stop();
1513 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001514}
1515
Wonsik Kim936a89c2020-05-08 16:07:50 -07001516void CCodecBufferChannel::reset() {
1517 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001518 if (mInputSurface != nullptr) {
1519 mInputSurface.reset();
1520 }
1521 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001522 {
1523 Mutexed<Input>::Locked input(mInput);
1524 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001525 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001526 }
1527 {
1528 Mutexed<Output>::Locked output(mOutput);
1529 output->buffers.reset();
1530 }
1531}
1532
1533void CCodecBufferChannel::release() {
1534 mComponent.reset();
1535 mInputAllocator.reset();
1536 mOutputSurface.lock()->surface.clear();
1537 {
1538 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1539 blockPools->inputPool.reset();
1540 blockPools->outputPoolIntf.reset();
1541 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001542 setCrypto(nullptr);
1543 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001544}
1545
Pawin Vongmasa36653902018-11-15 00:10:25 -08001546void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1547 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001548 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001549 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07001550 {
1551 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1552 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1553 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
1554 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1555 watcher->onWorkDone(frameIndex);
1556 continue;
1557 }
1558 if (work->input.buffers.empty()
1559 || work->input.buffers.front() == nullptr
1560 || work->input.buffers.front()->data().linearBlocks().empty()) {
1561 ALOGD("[%s] no linear codec config data found", mName);
1562 watcher->onWorkDone(frameIndex);
1563 continue;
1564 }
1565 std::unique_ptr<C2Work> copy(new C2Work);
1566 copy->input.flags = C2FrameData::flags_t(
1567 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1568 copy->input.ordinal = work->input.ordinal;
1569 copy->input.ordinal.frameIndex = mFrameIndex++;
1570 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
1571 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
1572 }
1573 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1574 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1575 }
1576 copy->input.infoBuffers.insert(
1577 copy->input.infoBuffers.begin(),
1578 work->input.infoBuffers.begin(),
1579 work->input.infoBuffers.end());
1580 copy->worklets.emplace_back(new C2Worklet);
1581 configs.push_back(std::move(copy));
1582 watcher->onWorkDone(frameIndex);
1583 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001584 }
1585 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001586 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001587 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001588 Mutexed<Input>::Locked input(mInput);
1589 input->buffers->flush();
1590 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001591 }
1592 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001593 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001594 if (output->buffers) {
1595 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001596 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001597 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001598 }
1599}
1600
1601void CCodecBufferChannel::onWorkDone(
1602 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001603 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001604 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001605 feedInputBufferIfAvailable();
1606 }
1607}
1608
1609void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001610 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001611 if (mInputSurface) {
1612 return;
1613 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001614 std::shared_ptr<C2Buffer> buffer =
1615 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001616 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001617 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001618 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001619 if (input->lastFlushIndex >= frameIndex) {
1620 ALOGD("[%s] Ignoring stale input buffer done callback: "
1621 "last flush index = %lld, frameIndex = %lld",
1622 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
1623 } else {
1624 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1625 if (!newInputSlotAvailable) {
1626 (void)input->extraBuffers.expireComponentBuffer(buffer);
1627 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001628 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001629 }
1630 if (newInputSlotAvailable) {
1631 feedInputBufferIfAvailable();
1632 }
1633}
1634
1635bool CCodecBufferChannel::handleWork(
1636 std::unique_ptr<C2Work> work,
1637 const sp<AMessage> &outputFormat,
1638 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001639 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001640 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001641 if (!output->buffers) {
1642 return false;
1643 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001644 }
1645
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001646 // Whether the output buffer should be reported to the client or not.
1647 bool notifyClient = false;
1648
1649 if (work->result == C2_OK){
1650 notifyClient = true;
1651 } else if (work->result == C2_NOT_FOUND) {
1652 ALOGD("[%s] flushed work; ignored.", mName);
1653 } else {
1654 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1655 // the config update.
1656 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1657 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1658 return false;
1659 }
1660
1661 if ((work->input.ordinal.frameIndex -
1662 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001663 // Discard frames from previous generation.
1664 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001665 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001666 }
1667
Wonsik Kim524b0582019-03-12 11:28:57 -07001668 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001669 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001670 || !(work->worklets.front()->output.flags &
1671 C2FrameData::FLAG_INCOMPLETE))) {
1672 mPipelineWatcher.lock()->onWorkDone(
1673 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001674 }
1675
1676 // NOTE: MediaCodec usage supposedly have only one worklet
1677 if (work->worklets.size() != 1u) {
1678 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1679 mName, work->worklets.size());
1680 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1681 return false;
1682 }
1683
1684 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1685
1686 std::shared_ptr<C2Buffer> buffer;
1687 // NOTE: MediaCodec usage supposedly have only one output stream.
1688 if (worklet->output.buffers.size() > 1u) {
1689 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1690 mName, worklet->output.buffers.size());
1691 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1692 return false;
1693 } else if (worklet->output.buffers.size() == 1u) {
1694 buffer = worklet->output.buffers[0];
1695 if (!buffer) {
1696 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1697 }
1698 }
1699
Wonsik Kim3dedf682021-05-03 10:57:09 -07001700 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1701 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001702 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001703 while (!worklet->output.configUpdate.empty()) {
1704 std::unique_ptr<C2Param> param;
1705 worklet->output.configUpdate.back().swap(param);
1706 worklet->output.configUpdate.pop_back();
1707 switch (param->coreIndex().coreIndex()) {
1708 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1709 C2PortReorderBufferDepthTuning::output reorderDepth;
1710 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001711 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1712 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001713 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001714 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001715 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001716 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1717 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001718 }
1719 break;
1720 }
1721 case C2PortReorderKeySetting::CORE_INDEX: {
1722 C2PortReorderKeySetting::output reorderKey;
1723 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001724 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001725 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1726 mName, reorderKey.value);
1727 } else {
1728 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1729 }
1730 break;
1731 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001732 case C2PortActualDelayTuning::CORE_INDEX: {
1733 if (param->isGlobal()) {
1734 C2ActualPipelineDelayTuning pipelineDelay;
1735 if (pipelineDelay.updateFrom(*param)) {
1736 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1737 mName, pipelineDelay.value);
1738 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001739 (void)mPipelineWatcher.lock()->pipelineDelay(
1740 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001741 }
1742 }
1743 if (param->forInput()) {
1744 C2PortActualDelayTuning::input inputDelay;
1745 if (inputDelay.updateFrom(*param)) {
1746 ALOGV("[%s] onWorkDone: updating input delay %u",
1747 mName, inputDelay.value);
1748 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001749 (void)mPipelineWatcher.lock()->inputDelay(
1750 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001751 }
1752 }
1753 if (param->forOutput()) {
1754 C2PortActualDelayTuning::output outputDelay;
1755 if (outputDelay.updateFrom(*param)) {
1756 ALOGV("[%s] onWorkDone: updating output delay %u",
1757 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001758 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001759 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001760 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001761
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001762 }
1763 }
1764 break;
1765 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001766 case C2PortTunnelSystemTime::CORE_INDEX: {
1767 C2PortTunnelSystemTime::output frameRenderTime;
1768 if (frameRenderTime.updateFrom(*param)) {
1769 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1770 mName, (long long)frameRenderTime.value,
1771 (long long)worklet->output.ordinal.timestamp.peekll());
1772 mCCodecCallback->onOutputFramesRendered(
1773 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1774 }
1775 break;
1776 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001777 case C2StreamTunnelHoldRender::CORE_INDEX: {
1778 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1779 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1780 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1781 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1782 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1783 mCCodecCallback->onFirstTunnelFrameReady();
1784 break;
1785 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001786 default:
1787 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1788 mName, param->index());
1789 break;
1790 }
1791 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001792 if (newInputDelay || newPipelineDelay) {
1793 Mutexed<Input>::Locked input(mInput);
1794 size_t newNumSlots =
1795 newInputDelay.value_or(input->inputDelay) +
1796 newPipelineDelay.value_or(input->pipelineDelay) +
1797 kSmoothnessFactor;
1798 if (input->buffers->isArrayMode()) {
1799 if (input->numSlots >= newNumSlots) {
1800 input->numExtraSlots = 0;
1801 } else {
1802 input->numExtraSlots = newNumSlots - input->numSlots;
1803 }
1804 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1805 mName, input->numExtraSlots);
1806 } else {
1807 input->numSlots = newNumSlots;
1808 }
1809 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001810 size_t numOutputSlots = 0;
1811 uint32_t reorderDepth = 0;
1812 bool outputBuffersChanged = false;
1813 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
1814 Mutexed<Output>::Locked output(mOutput);
1815 if (!output->buffers) {
1816 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001817 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001818 numOutputSlots = output->numSlots;
1819 if (newReorderKey) {
1820 output->buffers->setReorderKey(newReorderKey.value());
1821 }
1822 if (newReorderDepth) {
1823 output->buffers->setReorderDepth(newReorderDepth.value());
1824 }
1825 reorderDepth = output->buffers->getReorderDepth();
1826 if (newOutputDelay) {
1827 output->outputDelay = newOutputDelay.value();
1828 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
1829 if (output->numSlots < numOutputSlots) {
1830 output->numSlots = numOutputSlots;
1831 if (output->buffers->isArrayMode()) {
1832 OutputBuffersArray *array =
1833 (OutputBuffersArray *)output->buffers.get();
1834 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1835 mName, numOutputSlots);
1836 array->grow(numOutputSlots);
1837 outputBuffersChanged = true;
1838 }
1839 }
1840 }
1841 numOutputSlots = output->numSlots;
1842 }
1843 if (outputBuffersChanged) {
1844 mCCodecCallback->onOutputBuffersChanged();
1845 }
1846 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07001847 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07001848 {
1849 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1850 maxDequeueCount = output->maxDequeueBuffers =
1851 numOutputSlots + reorderDepth + kRenderingDepth;
1852 if (output->surface) {
1853 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1854 }
1855 }
1856 if (maxDequeueCount > 0) {
1857 mComponent->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001858 }
1859 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001860
Pawin Vongmasa36653902018-11-15 00:10:25 -08001861 int32_t flags = 0;
1862 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1863 flags |= MediaCodec::BUFFER_FLAG_EOS;
1864 ALOGV("[%s] onWorkDone: output EOS", mName);
1865 }
1866
Pawin Vongmasa36653902018-11-15 00:10:25 -08001867 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1868 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1869 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1870 // shall correspond to the client input timesamp (in customOrdinal). By using the
1871 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1872 // produces multiple output.
1873 c2_cntr64_t timestamp =
1874 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1875 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001876 if (mInputSurface != nullptr) {
1877 // When using input surface we need to restore the original input timestamp.
1878 timestamp = work->input.ordinal.customOrdinal;
1879 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001880 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1881 mName,
1882 work->input.ordinal.customOrdinal.peekll(),
1883 work->input.ordinal.timestamp.peekll(),
1884 worklet->output.ordinal.timestamp.peekll(),
1885 timestamp.peekll());
1886
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001887 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001888 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001889 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001890 if (output->buffers && outputFormat) {
1891 output->buffers->updateSkipCutBuffer(outputFormat);
1892 output->buffers->setFormat(outputFormat);
1893 }
1894 if (!notifyClient) {
1895 return false;
1896 }
1897 size_t index;
1898 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07001899 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001900 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1901 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1902 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1903
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001904 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001905 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001906 } else {
1907 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001908 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001909 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001910 return false;
1911 }
1912 }
1913
Wonsik Kimec585c32021-10-01 01:11:00 -07001914 bool drop = false;
1915 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
1916 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
1917 drop = true;
1918 }
1919
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001920 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07001921 if (mTunneled && drop && outputFormat) {
1922 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
1923 mName, work->input.ordinal.frameIndex.peekull());
1924 } else {
1925 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1926 mName, work->input.ordinal.frameIndex.peekull());
1927 notifyClient = false;
1928 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001929 }
1930
1931 if (buffer) {
1932 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1933 // TODO: properly translate these to metadata
1934 switch (info->coreIndex().coreIndex()) {
1935 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001936 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001937 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1938 }
1939 break;
1940 default:
1941 break;
1942 }
1943 }
1944 }
1945
1946 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001947 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07001948 if (!output->buffers) {
1949 return false;
1950 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001951 output->buffers->pushToStash(
1952 buffer,
1953 notifyClient,
1954 timestamp.peek(),
1955 flags,
1956 outputFormat,
1957 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001958 }
1959 sendOutputBuffers();
1960 return true;
1961}
1962
1963void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001964 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001965 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001966 sp<MediaCodecBuffer> outBuffer;
1967 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001968
1969 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001970 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001971 if (!output->buffers) {
1972 return;
1973 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001974 action = output->buffers->popFromStashAndRegister(
1975 &c2Buffer, &index, &outBuffer);
1976 switch (action) {
1977 case OutputBuffers::SKIP:
1978 return;
1979 case OutputBuffers::DISCARD:
1980 break;
1981 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00001982 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001983 mCallback->onOutputBufferAvailable(index, outBuffer);
1984 break;
1985 case OutputBuffers::REALLOCATE:
1986 if (!output->buffers->isArrayMode()) {
1987 output->buffers =
1988 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001989 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001990 static_cast<OutputBuffersArray*>(output->buffers.get())->
1991 realloc(c2Buffer);
1992 output.unlock();
1993 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07001994 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001995 case OutputBuffers::RETRY:
1996 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
1997 mName);
1998 return;
1999 default:
2000 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2001 "corrupted BufferAction value (%d) "
2002 "returned from popFromStashAndRegister.",
2003 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002004 return;
2005 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002006 }
2007}
2008
2009status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
2010 static std::atomic_uint32_t surfaceGeneration{0};
2011 uint32_t generation = (getpid() << 10) |
2012 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2013 & ((1 << 10) - 1));
2014
2015 sp<IGraphicBufferProducer> producer;
Sungtak Leedb14cba2021-04-10 00:50:23 -07002016 int maxDequeueCount = mOutputSurface.lock()->maxDequeueBuffers;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002017 if (newSurface) {
2018 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002019 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002020 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002021 producer = newSurface->getIGraphicBufferProducer();
2022 producer->setGenerationNumber(generation);
2023 } else {
2024 ALOGE("[%s] setting output surface to null", mName);
2025 return INVALID_OPERATION;
2026 }
2027
2028 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2029 C2BlockPool::local_id_t outputPoolId;
2030 {
2031 Mutexed<BlockPools>::Locked pools(mBlockPools);
2032 outputPoolId = pools->outputPoolId;
2033 outputPoolIntf = pools->outputPoolIntf;
2034 }
2035
2036 if (outputPoolIntf) {
2037 if (mComponent->setOutputSurface(
2038 outputPoolId,
2039 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002040 generation,
2041 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002042 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2043 return INVALID_OPERATION;
2044 }
2045 }
2046
2047 {
2048 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2049 output->surface = newSurface;
2050 output->generation = generation;
2051 }
2052
2053 return OK;
2054}
2055
Wonsik Kimab34ed62019-01-31 15:28:46 -08002056PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002057 // When client pushed EOS, we want all the work to be done quickly.
2058 // Otherwise, component may have stalled work due to input starvation up to
2059 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002060 size_t n = 0;
2061 if (!mInputMetEos) {
2062 size_t outputDelay = mOutput.lock()->outputDelay;
2063 Mutexed<Input>::Locked input(mInput);
2064 n = input->inputDelay + input->pipelineDelay + outputDelay;
2065 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002066 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002067}
2068
Pawin Vongmasa36653902018-11-15 00:10:25 -08002069void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2070 mMetaMode = mode;
2071}
2072
Wonsik Kim596187e2019-10-25 12:44:10 -07002073void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002074 if (mCrypto != nullptr) {
2075 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2076 mCrypto->unsetHeap(entry.second);
2077 }
2078 mHeapSeqNumMap.clear();
2079 if (mHeapSeqNum >= 0) {
2080 mCrypto->unsetHeap(mHeapSeqNum);
2081 mHeapSeqNum = -1;
2082 }
2083 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002084 mCrypto = crypto;
2085}
2086
2087void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2088 mDescrambler = descrambler;
2089}
2090
Pawin Vongmasa36653902018-11-15 00:10:25 -08002091status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2092 // C2_OK is always translated to OK.
2093 if (c2s == C2_OK) {
2094 return OK;
2095 }
2096
2097 // Operation-dependent translation
2098 // TODO: Add as necessary
2099 switch (c2op) {
2100 case C2_OPERATION_Component_start:
2101 switch (c2s) {
2102 case C2_NO_MEMORY:
2103 return NO_MEMORY;
2104 default:
2105 return UNKNOWN_ERROR;
2106 }
2107 default:
2108 break;
2109 }
2110
2111 // Backup operation-agnostic translation
2112 switch (c2s) {
2113 case C2_BAD_INDEX:
2114 return BAD_INDEX;
2115 case C2_BAD_VALUE:
2116 return BAD_VALUE;
2117 case C2_BLOCKING:
2118 return WOULD_BLOCK;
2119 case C2_DUPLICATE:
2120 return ALREADY_EXISTS;
2121 case C2_NO_INIT:
2122 return NO_INIT;
2123 case C2_NO_MEMORY:
2124 return NO_MEMORY;
2125 case C2_NOT_FOUND:
2126 return NAME_NOT_FOUND;
2127 case C2_TIMED_OUT:
2128 return TIMED_OUT;
2129 case C2_BAD_STATE:
2130 case C2_CANCELED:
2131 case C2_CANNOT_DO:
2132 case C2_CORRUPTED:
2133 case C2_OMITTED:
2134 case C2_REFUSED:
2135 return UNKNOWN_ERROR;
2136 default:
2137 return -static_cast<status_t>(c2s);
2138 }
2139}
2140
2141} // namespace android