blob: 00dd0e51e77ba911c2eabb4911bceffd1f4d6afa [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>
22#include <list>
Pawin Vongmasa36653902018-11-15 00:10:25 -080023#include <numeric>
24
25#include <C2AllocatorGralloc.h>
26#include <C2PlatformSupport.h>
27#include <C2BlockInternal.h>
28#include <C2Config.h>
29#include <C2Debug.h>
30
31#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070032#include <android/hardware/drm/1.0/types.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080033#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080034#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080035#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080036#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070037#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080038#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070039#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080040#include <media/openmax/OMX_Core.h>
41#include <media/stagefright/foundation/ABuffer.h>
42#include <media/stagefright/foundation/ALookup.h>
43#include <media/stagefright/foundation/AMessage.h>
44#include <media/stagefright/foundation/AUtils.h>
45#include <media/stagefright/foundation/hexdump.h>
46#include <media/stagefright/MediaCodec.h>
47#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070048#include <media/stagefright/SkipCutBuffer.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080049#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070050#include <mediadrm/ICrypto.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080051#include <system/window.h>
52
53#include "CCodecBufferChannel.h"
54#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080055
56namespace android {
57
58using android::base::StringPrintf;
59using hardware::hidl_handle;
60using hardware::hidl_string;
61using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070062using hardware::fromHeap;
63using hardware::HidlMemory;
64
Pawin Vongmasa36653902018-11-15 00:10:25 -080065using namespace hardware::cas::V1_0;
66using namespace hardware::cas::native::V1_0;
67
68using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070069using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080070
Pawin Vongmasa36653902018-11-15 00:10:25 -080071namespace {
72
Wonsik Kim469c8342019-04-11 16:46:09 -070073constexpr size_t kSmoothnessFactor = 4;
74constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080075
Sungtak Leeab6f2f32019-02-15 14:43:51 -080076// This is for keeping IGBP's buffer dropping logic in legacy mode other
77// than making it non-blocking. Do not change this value.
78const static size_t kDequeueTimeoutNs = 0;
79
Pawin Vongmasa36653902018-11-15 00:10:25 -080080} // namespace
81
82CCodecBufferChannel::QueueGuard::QueueGuard(
83 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
84 Mutex::Autolock l(mSync.mGuardLock);
85 // At this point it's guaranteed that mSync is not under state transition,
86 // as we are holding its mutex.
87
88 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
89 if (count->value == -1) {
90 mRunning = false;
91 } else {
92 ++count->value;
93 mRunning = true;
94 }
95}
96
97CCodecBufferChannel::QueueGuard::~QueueGuard() {
98 if (mRunning) {
99 // We are not holding mGuardLock at this point so that QueueSync::stop() can
100 // keep holding the lock until mCount reaches zero.
101 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
102 --count->value;
103 count->cond.broadcast();
104 }
105}
106
107void CCodecBufferChannel::QueueSync::start() {
108 Mutex::Autolock l(mGuardLock);
109 // If stopped, it goes to running state; otherwise no-op.
110 Mutexed<Counter>::Locked count(mCount);
111 if (count->value == -1) {
112 count->value = 0;
113 }
114}
115
116void CCodecBufferChannel::QueueSync::stop() {
117 Mutex::Autolock l(mGuardLock);
118 Mutexed<Counter>::Locked count(mCount);
119 if (count->value == -1) {
120 // no-op
121 return;
122 }
123 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
124 // mCount can only decrement. In other words, threads that acquired the lock
125 // are allowed to finish execution but additional threads trying to acquire
126 // the lock at this point will block, and then get QueueGuard at STOPPED
127 // state.
128 while (count->value != 0) {
129 count.waitForCondition(count->cond);
130 }
131 count->value = -1;
132}
133
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700134// Input
135
136CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
137
Pawin Vongmasa36653902018-11-15 00:10:25 -0800138// CCodecBufferChannel
139
140CCodecBufferChannel::CCodecBufferChannel(
141 const std::shared_ptr<CCodecCallback> &callback)
142 : mHeapSeqNum(-1),
143 mCCodecCallback(callback),
144 mFrameIndex(0u),
145 mFirstValidFrameIndex(0u),
146 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700147 mInputMetEos(false),
148 mSendEncryptedInfoBuffer(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700149 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700150 {
151 Mutexed<Input>::Locked input(mInput);
152 input->buffers.reset(new DummyInputBuffers(""));
153 input->extraBuffers.flush();
154 input->inputDelay = 0u;
155 input->pipelineDelay = 0u;
156 input->numSlots = kSmoothnessFactor;
157 input->numExtraSlots = 0u;
158 }
159 {
160 Mutexed<Output>::Locked output(mOutput);
161 output->outputDelay = 0u;
162 output->numSlots = kSmoothnessFactor;
163 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800164}
165
166CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800167 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800168 mCrypto->unsetHeap(mHeapSeqNum);
169 }
170}
171
172void CCodecBufferChannel::setComponent(
173 const std::shared_ptr<Codec2Client::Component> &component) {
174 mComponent = component;
175 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
176 mName = mComponentName.c_str();
177}
178
179status_t CCodecBufferChannel::setInputSurface(
180 const std::shared_ptr<InputSurfaceWrapper> &surface) {
181 ALOGV("[%s] setInputSurface", mName);
182 mInputSurface = surface;
183 return mInputSurface->connect(mComponent);
184}
185
186status_t CCodecBufferChannel::signalEndOfInputStream() {
187 if (mInputSurface == nullptr) {
188 return INVALID_OPERATION;
189 }
190 return mInputSurface->signalEndOfInputStream();
191}
192
Sungtak Lee04b30352020-07-27 13:57:25 -0700193status_t CCodecBufferChannel::queueInputBufferInternal(
194 sp<MediaCodecBuffer> buffer,
195 std::shared_ptr<C2LinearBlock> encryptedBlock,
196 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800197 int64_t timeUs;
198 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
199
200 if (mInputMetEos) {
201 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
202 return OK;
203 }
204
205 int32_t flags = 0;
206 int32_t tmp = 0;
207 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200208 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800209 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
210 eos = true;
211 mInputMetEos = true;
212 ALOGV("[%s] input EOS", mName);
213 }
214 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
215 flags |= C2FrameData::FLAG_CODEC_CONFIG;
216 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200217 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
218 tunnelFirstFrame = true;
219 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800220 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800221 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800222 std::unique_ptr<C2Work> work(new C2Work);
223 work->input.ordinal.timestamp = timeUs;
224 work->input.ordinal.frameIndex = mFrameIndex++;
225 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
226 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
227 // Keep client timestamp in customOrdinal
228 work->input.ordinal.customOrdinal = timeUs;
229 work->input.buffers.clear();
230
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700231 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800232 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800233
Pawin Vongmasa36653902018-11-15 00:10:25 -0800234 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700235 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800236 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700237 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800238 return -ENOENT;
239 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700240 // TODO: we want to delay copying buffers.
241 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
242 copy = input->buffers->cloneAndReleaseBuffer(buffer);
243 if (copy != nullptr) {
244 (void)input->extraBuffers.assignSlot(copy);
245 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
246 return UNKNOWN_ERROR;
247 }
248 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
249 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
250 mName, released ? "" : "not ");
251 buffer.clear();
252 } else {
253 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
254 "buffer starvation on component.", mName);
255 }
256 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800257 if (input->frameReassembler) {
258 usesFrameReassembler = true;
259 input->frameReassembler.process(buffer, &items);
260 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900261 int32_t cvo = 0;
262 if (buffer->meta()->findInt32("cvo", &cvo)) {
263 int32_t rotation = cvo % 360;
264 // change rotation to counter-clock wise.
265 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
266
267 Mutexed<OutputSurface>::Locked output(mOutputSurface);
268 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
269 output->rotation[frameIndex] = rotation;
270 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800271 work->input.buffers.push_back(c2buffer);
272 if (encryptedBlock) {
273 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
274 kParamIndexEncryptedBuffer,
275 encryptedBlock->share(0, blockSize, C2Fence())));
276 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700277 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800278 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700279 Mutexed<Input>::Locked input(mInput);
280 if (input->frameReassembler) {
281 usesFrameReassembler = true;
282 // drain any pending items with eos
283 input->frameReassembler.process(buffer, &items);
284 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800285 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800286 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800287 if (usesFrameReassembler) {
288 if (!items.empty()) {
289 items.front()->input.configUpdate = std::move(mParamsToBeSet);
290 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
291 }
292 } else {
293 work->input.flags = (C2FrameData::flags_t)flags;
294 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800295
Wonsik Kime1104ca2020-11-24 15:01:33 -0800296 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200297 if (tunnelFirstFrame) {
298 C2StreamTunnelHoldRender::input tunnelHoldRender{
299 0u /* stream */,
300 C2_TRUE /* value */
301 };
302 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
303 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800304 work->worklets.clear();
305 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800306
Wonsik Kime1104ca2020-11-24 15:01:33 -0800307 items.push_back(std::move(work));
308
309 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800310 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800311 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800312 work.reset(new C2Work);
313 work->input.ordinal.timestamp = timeUs;
314 work->input.ordinal.frameIndex = mFrameIndex++;
315 // WORKAROUND: keep client timestamp in customOrdinal
316 work->input.ordinal.customOrdinal = timeUs;
317 work->input.buffers.clear();
318 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800319 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800320 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800321 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800322 c2_status_t err = C2_OK;
323 if (!items.empty()) {
324 {
325 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
326 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
327 for (const std::unique_ptr<C2Work> &work : items) {
328 watcher->onWorkQueued(
329 work->input.ordinal.frameIndex.peeku(),
330 std::vector(work->input.buffers),
331 now);
332 }
333 }
334 err = mComponent->queue(&items);
335 }
336 if (err != C2_OK) {
337 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
338 for (const std::unique_ptr<C2Work> &work : items) {
339 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
340 }
341 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700342 Mutexed<Input>::Locked input(mInput);
343 bool released = false;
344 if (buffer) {
345 released = input->buffers->releaseBuffer(buffer, nullptr, true);
346 } else if (copy) {
347 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
348 }
349 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
350 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800351 }
352
353 feedInputBufferIfAvailableInternal();
354 return err;
355}
356
357status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
358 QueueGuard guard(mSync);
359 if (!guard.isRunning()) {
360 ALOGD("[%s] setParameters is only supported in the running state.", mName);
361 return -ENOSYS;
362 }
363 mParamsToBeSet.insert(mParamsToBeSet.end(),
364 std::make_move_iterator(params.begin()),
365 std::make_move_iterator(params.end()));
366 params.clear();
367 return OK;
368}
369
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800370status_t CCodecBufferChannel::attachBuffer(
371 const std::shared_ptr<C2Buffer> &c2Buffer,
372 const sp<MediaCodecBuffer> &buffer) {
373 if (!buffer->copy(c2Buffer)) {
374 return -ENOSYS;
375 }
376 return OK;
377}
378
379void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
380 if (!mDecryptDestination || mDecryptDestination->size() < size) {
381 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
382 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
383 mCrypto->unsetHeap(mHeapSeqNum);
384 }
385 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
386 if (mCrypto) {
387 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
388 }
389 }
390}
391
392int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
393 CHECK(mCrypto);
394 auto it = mHeapSeqNumMap.find(memory);
395 int32_t heapSeqNum = -1;
396 if (it == mHeapSeqNumMap.end()) {
397 heapSeqNum = mCrypto->setHeap(memory);
398 mHeapSeqNumMap.emplace(memory, heapSeqNum);
399 } else {
400 heapSeqNum = it->second;
401 }
402 return heapSeqNum;
403}
404
405status_t CCodecBufferChannel::attachEncryptedBuffer(
406 const sp<hardware::HidlMemory> &memory,
407 bool secure,
408 const uint8_t *key,
409 const uint8_t *iv,
410 CryptoPlugin::Mode mode,
411 CryptoPlugin::Pattern pattern,
412 size_t offset,
413 const CryptoPlugin::SubSample *subSamples,
414 size_t numSubSamples,
415 const sp<MediaCodecBuffer> &buffer) {
416 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
417 static const C2MemoryUsage kDefaultReadWriteUsage{
418 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
419
420 size_t size = 0;
421 for (size_t i = 0; i < numSubSamples; ++i) {
422 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
423 }
424 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
425 std::shared_ptr<C2LinearBlock> block;
426 c2_status_t err = pool->fetchLinearBlock(
427 size,
428 secure ? kSecureUsage : kDefaultReadWriteUsage,
429 &block);
430 if (err != C2_OK) {
431 return NO_MEMORY;
432 }
433 if (!secure) {
434 ensureDecryptDestination(size);
435 }
436 ssize_t result = -1;
437 ssize_t codecDataOffset = 0;
438 if (mCrypto) {
439 AString errorDetailMsg;
440 int32_t heapSeqNum = getHeapSeqNum(memory);
441 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
442 hardware::drm::V1_0::DestinationBuffer dst;
443 if (secure) {
444 dst.type = DrmBufferType::NATIVE_HANDLE;
445 dst.secureMemory = hardware::hidl_handle(block->handle());
446 } else {
447 dst.type = DrmBufferType::SHARED_MEMORY;
448 IMemoryToSharedBuffer(
449 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
450 }
451 result = mCrypto->decrypt(
452 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
453 dst, &errorDetailMsg);
454 if (result < 0) {
455 return result;
456 }
457 if (dst.type == DrmBufferType::SHARED_MEMORY) {
458 C2WriteView view = block->map().get();
459 if (view.error() != C2_OK) {
460 return false;
461 }
462 if (view.size() < result) {
463 return false;
464 }
465 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
466 }
467 } else {
468 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
469 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
470 hidl_vec<SubSample> hidlSubSamples;
471 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
472
473 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
474 hardware::cas::native::V1_0::DestinationBuffer dst;
475 if (secure) {
476 dst.type = BufferType::NATIVE_HANDLE;
477 dst.secureMemory = hardware::hidl_handle(block->handle());
478 } else {
479 dst.type = BufferType::SHARED_MEMORY;
480 dst.nonsecureMemory = src;
481 }
482
483 CasStatus status = CasStatus::OK;
484 hidl_string detailedError;
485 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
486
487 if (key != nullptr) {
488 sctrl = (ScramblingControl)key[0];
489 // Adjust for the PES offset
490 codecDataOffset = key[2] | (key[3] << 8);
491 }
492
493 auto returnVoid = mDescrambler->descramble(
494 sctrl,
495 hidlSubSamples,
496 src,
497 0,
498 dst,
499 0,
500 [&status, &result, &detailedError] (
501 CasStatus _status, uint32_t _bytesWritten,
502 const hidl_string& _detailedError) {
503 status = _status;
504 result = (ssize_t)_bytesWritten;
505 detailedError = _detailedError;
506 });
507
508 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
509 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
510 mName, returnVoid.description().c_str(), status, result);
511 return UNKNOWN_ERROR;
512 }
513
514 if (result < codecDataOffset) {
515 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
516 return BAD_VALUE;
517 }
518 }
519 if (!secure) {
520 C2WriteView view = block->map().get();
521 if (view.error() != C2_OK) {
522 return UNKNOWN_ERROR;
523 }
524 if (view.size() < result) {
525 return UNKNOWN_ERROR;
526 }
527 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
528 }
529 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
530 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
531 if (!buffer->copy(c2Buffer)) {
532 return -ENOSYS;
533 }
534 return OK;
535}
536
Pawin Vongmasa36653902018-11-15 00:10:25 -0800537status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
538 QueueGuard guard(mSync);
539 if (!guard.isRunning()) {
540 ALOGD("[%s] No more buffers should be queued at current state.", mName);
541 return -ENOSYS;
542 }
543 return queueInputBufferInternal(buffer);
544}
545
546status_t CCodecBufferChannel::queueSecureInputBuffer(
547 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
548 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
549 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
550 AString *errorDetailMsg) {
551 QueueGuard guard(mSync);
552 if (!guard.isRunning()) {
553 ALOGD("[%s] No more buffers should be queued at current state.", mName);
554 return -ENOSYS;
555 }
556
557 if (!hasCryptoOrDescrambler()) {
558 return -ENOSYS;
559 }
560 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
561
Sungtak Lee04b30352020-07-27 13:57:25 -0700562 std::shared_ptr<C2LinearBlock> block;
563 size_t allocSize = buffer->size();
564 size_t bufferSize = 0;
565 c2_status_t blockRes = C2_OK;
566 bool copied = false;
567 if (mSendEncryptedInfoBuffer) {
568 static const C2MemoryUsage kDefaultReadWriteUsage{
569 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
570 constexpr int kAllocGranule0 = 1024 * 64;
571 constexpr int kAllocGranule1 = 1024 * 1024;
572 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
573 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
574 if (allocSize <= kAllocGranule1) {
575 bufferSize = align(allocSize, kAllocGranule0);
576 } else {
577 bufferSize = align(allocSize, kAllocGranule1);
578 }
579 blockRes = pool->fetchLinearBlock(
580 bufferSize, kDefaultReadWriteUsage, &block);
581
582 if (blockRes == C2_OK) {
583 C2WriteView view = block->map().get();
584 if (view.error() == C2_OK && view.size() == bufferSize) {
585 copied = true;
586 // TODO: only copy clear sections
587 memcpy(view.data(), buffer->data(), allocSize);
588 }
589 }
590 }
591
592 if (!copied) {
593 block.reset();
594 }
595
Pawin Vongmasa36653902018-11-15 00:10:25 -0800596 ssize_t result = -1;
597 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700598 if (numSubSamples == 1
599 && subSamples[0].mNumBytesOfClearData == 0
600 && subSamples[0].mNumBytesOfEncryptedData == 0) {
601 // We don't need to go through crypto or descrambler if the input is empty.
602 result = 0;
603 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700604 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800605 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700606 destination.type = DrmBufferType::NATIVE_HANDLE;
607 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800608 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700609 destination.type = DrmBufferType::SHARED_MEMORY;
610 IMemoryToSharedBuffer(
611 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800612 }
Robert Shih895fba92019-07-16 16:29:44 -0700613 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800614 encryptedBuffer->fillSourceBuffer(&source);
615 result = mCrypto->decrypt(
616 key, iv, mode, pattern, source, buffer->offset(),
617 subSamples, numSubSamples, destination, errorDetailMsg);
618 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700619 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800620 return result;
621 }
Robert Shih895fba92019-07-16 16:29:44 -0700622 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800623 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
624 }
625 } else {
626 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
627 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
628 hidl_vec<SubSample> hidlSubSamples;
629 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
630
631 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
632 encryptedBuffer->fillSourceBuffer(&srcBuffer);
633
634 DestinationBuffer dstBuffer;
635 if (secure) {
636 dstBuffer.type = BufferType::NATIVE_HANDLE;
637 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
638 } else {
639 dstBuffer.type = BufferType::SHARED_MEMORY;
640 dstBuffer.nonsecureMemory = srcBuffer;
641 }
642
643 CasStatus status = CasStatus::OK;
644 hidl_string detailedError;
645 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
646
647 if (key != nullptr) {
648 sctrl = (ScramblingControl)key[0];
649 // Adjust for the PES offset
650 codecDataOffset = key[2] | (key[3] << 8);
651 }
652
653 auto returnVoid = mDescrambler->descramble(
654 sctrl,
655 hidlSubSamples,
656 srcBuffer,
657 0,
658 dstBuffer,
659 0,
660 [&status, &result, &detailedError] (
661 CasStatus _status, uint32_t _bytesWritten,
662 const hidl_string& _detailedError) {
663 status = _status;
664 result = (ssize_t)_bytesWritten;
665 detailedError = _detailedError;
666 });
667
668 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
669 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
670 mName, returnVoid.description().c_str(), status, result);
671 return UNKNOWN_ERROR;
672 }
673
674 if (result < codecDataOffset) {
675 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
676 return BAD_VALUE;
677 }
678
679 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
680
681 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
682 encryptedBuffer->copyDecryptedContentFromMemory(result);
683 }
684 }
685
686 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700687
688 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800689}
690
691void CCodecBufferChannel::feedInputBufferIfAvailable() {
692 QueueGuard guard(mSync);
693 if (!guard.isRunning()) {
694 ALOGV("[%s] We're not running --- no input buffer reported", mName);
695 return;
696 }
697 feedInputBufferIfAvailableInternal();
698}
699
700void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900701 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800702 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700703 }
704 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700705 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700706 if (!output->buffers ||
707 output->buffers->hasPending() ||
Wonsik Kim0487b782020-10-28 11:45:50 -0700708 output->buffers->numActiveSlots() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800709 return;
710 }
711 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700712 size_t numActiveSlots = 0;
713 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800714 sp<MediaCodecBuffer> inBuffer;
715 size_t index;
716 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700717 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700718 numActiveSlots = input->buffers->numActiveSlots();
719 if (numActiveSlots >= input->numSlots) {
720 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800721 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700722 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800723 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800724 break;
725 }
726 }
727 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
728 mCallback->onInputBufferAvailable(index, inBuffer);
729 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700730 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800731}
732
733status_t CCodecBufferChannel::renderOutputBuffer(
734 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800735 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800736 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800737 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800738 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700739 Mutexed<Output>::Locked output(mOutput);
740 if (output->buffers) {
741 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800742 }
743 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800744 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
745 // set to true.
746 sendOutputBuffers();
747 // input buffer feeding may have been gated by pending output buffers
748 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800749 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800750 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700751 std::call_once(mRenderWarningFlag, [this] {
752 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
753 "timestamp or render=true with non-video buffers. Apps should "
754 "call releaseOutputBuffer() with render=false for those.",
755 mName);
756 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800757 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800758 return INVALID_OPERATION;
759 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800760
761#if 0
762 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
763 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
764 for (const std::shared_ptr<const C2Info> &info : infoParams) {
765 AString res;
766 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
767 if (ix) res.append(", ");
768 res.append(*((int32_t*)info.get() + (ix / 4)));
769 }
770 ALOGV(" [%s]", res.c_str());
771 }
772#endif
773 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
774 std::static_pointer_cast<const C2StreamRotationInfo::output>(
775 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
776 bool flip = rotation && (rotation->flip & 1);
777 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900778
779 {
780 Mutexed<OutputSurface>::Locked output(mOutputSurface);
781 if (output->surface == nullptr) {
782 ALOGI("[%s] cannot render buffer without surface", mName);
783 return OK;
784 }
785 int64_t frameIndex;
786 buffer->meta()->findInt64("frameIndex", &frameIndex);
787 if (output->rotation.count(frameIndex) != 0) {
788 auto it = output->rotation.find(frameIndex);
789 quarters = (it->second / 90) & 3;
790 output->rotation.erase(it);
791 }
792 }
793
Pawin Vongmasa36653902018-11-15 00:10:25 -0800794 uint32_t transform = 0;
795 switch (quarters) {
796 case 0: // no rotation
797 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
798 break;
799 case 1: // 90 degrees counter-clockwise
800 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
801 : HAL_TRANSFORM_ROT_270;
802 break;
803 case 2: // 180 degrees
804 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
805 break;
806 case 3: // 90 degrees clockwise
807 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
808 : HAL_TRANSFORM_ROT_90;
809 break;
810 }
811
812 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
813 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
814 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
815 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
816 if (surfaceScaling) {
817 videoScalingMode = surfaceScaling->value;
818 }
819
820 // Use dataspace from format as it has the default aspects already applied
821 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
822 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
823
824 // HDR static info
825 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
826 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
827 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
828
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800829 // HDR10 plus info
830 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
831 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
832 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800833 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
834 hdr10PlusInfo.reset();
835 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800836
Pawin Vongmasa36653902018-11-15 00:10:25 -0800837 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
838 if (blocks.size() != 1u) {
839 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
840 return UNKNOWN_ERROR;
841 }
842 const C2ConstGraphicBlock &block = blocks.front();
843
844 // TODO: revisit this after C2Fence implementation.
845 android::IGraphicBufferProducer::QueueBufferInput qbi(
846 timestampNs,
847 false, // droppable
848 dataSpace,
849 Rect(blocks.front().crop().left,
850 blocks.front().crop().top,
851 blocks.front().crop().right(),
852 blocks.front().crop().bottom()),
853 videoScalingMode,
854 transform,
855 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800856 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800857 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800858 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800859 // If mastering max and min luminance fields are 0, do not use them.
860 // It indicates the value may not be present in the stream.
861 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
862 hdrStaticInfo->mastering.minLuminance > 0.0f) {
863 struct android_smpte2086_metadata smpte2086_meta = {
864 .displayPrimaryRed = {
865 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
866 },
867 .displayPrimaryGreen = {
868 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
869 },
870 .displayPrimaryBlue = {
871 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
872 },
873 .whitePoint = {
874 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
875 },
876 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
877 .minLuminance = hdrStaticInfo->mastering.minLuminance,
878 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800879 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800880 hdr.smpte2086 = smpte2086_meta;
881 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700882 // If the content light level fields are 0, do not use them, it
883 // indicates the value may not be present in the stream.
884 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
885 struct android_cta861_3_metadata cta861_meta = {
886 .maxContentLightLevel = hdrStaticInfo->maxCll,
887 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
888 };
889 hdr.validTypes |= HdrMetadata::CTA861_3;
890 hdr.cta8613 = cta861_meta;
891 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800892 }
893 if (hdr10PlusInfo) {
894 hdr.validTypes |= HdrMetadata::HDR10PLUS;
895 hdr.hdr10plus.assign(
896 hdr10PlusInfo->m.value,
897 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
898 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800899 qbi.setHdrMetadata(hdr);
900 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800901 // we don't have dirty regions
902 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800903 android::IGraphicBufferProducer::QueueBufferOutput qbo;
904 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
905 if (result != OK) {
906 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800907 if (result == NO_INIT) {
908 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
909 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800910 return result;
911 }
Josh Hou8eddf4b2021-02-02 16:26:53 +0800912
913 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
914 ALOGD("[%s] queue buffer successful", mName);
915 } else {
916 ALOGV("[%s] queue buffer successful", mName);
917 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800918
919 int64_t mediaTimeUs = 0;
920 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
921 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
922
923 return OK;
924}
925
926status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
927 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
928 bool released = false;
929 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700930 Mutexed<Input>::Locked input(mInput);
931 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800932 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800933 }
934 }
935 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700936 Mutexed<Output>::Locked output(mOutput);
937 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800938 released = true;
939 }
940 }
941 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800942 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800943 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800944 } else {
945 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
946 }
947 return OK;
948}
949
950void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
951 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700952 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800953
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700954 if (!input->buffers->isArrayMode()) {
955 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800956 }
957
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700958 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800959}
960
961void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
962 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700963 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800964
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700965 if (!output->buffers->isArrayMode()) {
966 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800967 }
968
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700969 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800970}
971
972status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800973 const sp<AMessage> &inputFormat,
974 const sp<AMessage> &outputFormat,
975 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800976 C2StreamBufferTypeSetting::input iStreamFormat(0u);
977 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -0800978 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800979 C2PortReorderBufferDepthTuning::output reorderDepth;
980 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800981 C2PortActualDelayTuning::input inputDelay(0);
982 C2PortActualDelayTuning::output outputDelay(0);
983 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -0700984 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -0800985
Pawin Vongmasa36653902018-11-15 00:10:25 -0800986 c2_status_t err = mComponent->query(
987 {
988 &iStreamFormat,
989 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -0800990 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800991 &reorderDepth,
992 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800993 &inputDelay,
994 &pipelineDelay,
995 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -0700996 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800997 },
998 {},
999 C2_DONT_BLOCK,
1000 nullptr);
1001 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001002 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001003 return UNKNOWN_ERROR;
1004 }
1005 } else if (err != C2_OK) {
1006 return UNKNOWN_ERROR;
1007 }
1008
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001009 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1010 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1011 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1012
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001013 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1014 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001015
Pawin Vongmasa36653902018-11-15 00:10:25 -08001016 // TODO: get this from input format
1017 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1018
Sungtak Lee04b30352020-07-27 13:57:25 -07001019 // secure mode is a static parameter (shall not change in the executing state)
1020 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1021
Pawin Vongmasa36653902018-11-15 00:10:25 -08001022 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001023 int poolMask = GetCodec2PoolMask();
1024 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001025
1026 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001027 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001028 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001029 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1030 API_REFLECTION |
1031 API_VALUES |
1032 API_CURRENT_VALUES |
1033 API_DEPENDENCY |
1034 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001035 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1036 C2StreamSampleRateInfo::input sampleRate(0u);
1037 C2StreamChannelCountInfo::input channelCount(0u);
1038 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001039 std::shared_ptr<C2BlockPool> pool;
1040 {
1041 Mutexed<BlockPools>::Locked pools(mBlockPools);
1042
1043 // set default allocator ID.
1044 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001045 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001046
1047 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1048 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1049 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001050 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001051 std::vector<C2Param *> stackParams({&featuresSetting});
1052 if (audioEncoder) {
1053 stackParams.push_back(&encoderFrameSize);
1054 stackParams.push_back(&sampleRate);
1055 stackParams.push_back(&channelCount);
1056 stackParams.push_back(&pcmEncoding);
1057 } else {
1058 encoderFrameSize.invalidate();
1059 sampleRate.invalidate();
1060 channelCount.invalidate();
1061 pcmEncoding.invalidate();
1062 }
1063 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001064 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1065 C2_DONT_BLOCK,
1066 &params);
1067 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1068 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1069 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001070 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001071 C2PortAllocatorsTuning::input *inputAllocators =
1072 C2PortAllocatorsTuning::input::From(params[0].get());
1073 if (inputAllocators && inputAllocators->flexCount() > 0) {
1074 std::shared_ptr<C2Allocator> allocator;
1075 // verify allocator IDs and resolve default allocator
1076 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1077 if (allocator) {
1078 pools->inputAllocatorId = allocator->getId();
1079 } else {
1080 ALOGD("[%s] component requested invalid input allocator ID %u",
1081 mName, inputAllocators->m.values[0]);
1082 }
1083 }
1084 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001085 if (featuresSetting) {
1086 apiFeatures = featuresSetting.value;
1087 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001088
1089 // TODO: use C2Component wrapper to associate this pool with ourselves
1090 if ((poolMask >> pools->inputAllocatorId) & 1) {
1091 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1092 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1093 mName, pools->inputAllocatorId,
1094 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1095 asString(err), err);
1096 } else {
1097 err = C2_NOT_FOUND;
1098 }
1099 if (err != C2_OK) {
1100 C2BlockPool::local_id_t inputPoolId =
1101 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1102 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1103 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1104 mName, (unsigned long long)inputPoolId,
1105 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1106 asString(err), err);
1107 if (err != C2_OK) {
1108 return NO_MEMORY;
1109 }
1110 }
1111 pools->inputPool = pool;
1112 }
1113
Wonsik Kim51051262018-11-28 13:59:05 -08001114 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001115 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001116 input->inputDelay = inputDelayValue;
1117 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001118 input->numSlots = numInputSlots;
1119 input->extraBuffers.flush();
1120 input->numExtraSlots = 0u;
Wonsik Kime1104ca2020-11-24 15:01:33 -08001121 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1122 input->frameReassembler.init(
1123 pool,
1124 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1125 encoderFrameSize.value,
1126 sampleRate.value,
1127 channelCount.value,
1128 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1129 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001130 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1131 // For encrypted content, framework decrypts source buffer (ashmem) into
1132 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001133 if (!buffersBoundToCodec
1134 && !input->frameReassembler
1135 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001136 input->buffers.reset(new SlotInputBuffers(mName));
1137 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001138 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001139 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001140 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001141 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001142 // This is to ensure buffers do not get released prematurely.
1143 // TODO: handle this without going into array mode
1144 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001145 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001146 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001147 }
1148 } else {
1149 if (hasCryptoOrDescrambler()) {
1150 int32_t capacity = kLinearBufferSize;
1151 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1152 if ((size_t)capacity > kMaxLinearBufferSize) {
1153 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1154 capacity = kMaxLinearBufferSize;
1155 }
1156 if (mDealer == nullptr) {
1157 mDealer = new MemoryDealer(
1158 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001159 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001160 "EncryptedLinearInputBuffers");
1161 mDecryptDestination = mDealer->allocate((size_t)capacity);
1162 }
1163 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001164 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1165 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001166 } else {
1167 mHeapSeqNum = -1;
1168 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001169 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001170 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001171 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001172 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001173 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001174 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001175 }
1176 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001177 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001178
1179 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001180 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001181 } else {
1182 // TODO: error
1183 }
Wonsik Kim51051262018-11-28 13:59:05 -08001184
1185 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001186 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001187 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001188 }
1189
1190 if (outputFormat != nullptr) {
1191 sp<IGraphicBufferProducer> outputSurface;
1192 uint32_t outputGeneration;
1193 {
1194 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001195 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001196 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001197 outputSurface = output->surface ?
1198 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001199 if (outputSurface) {
1200 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1201 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001202 outputGeneration = output->generation;
1203 }
1204
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001205 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001206 C2BlockPool::local_id_t outputPoolId_;
1207
1208 {
1209 Mutexed<BlockPools>::Locked pools(mBlockPools);
1210
1211 // set default allocator ID.
1212 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001213 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001214
1215 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1216 // unsuccessful.
1217 std::vector<std::unique_ptr<C2Param>> params;
1218 err = mComponent->query({ },
1219 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1220 C2_DONT_BLOCK,
1221 &params);
1222 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1223 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1224 mName, params.size(), asString(err), err);
1225 } else if (err == C2_OK && params.size() == 1) {
1226 C2PortAllocatorsTuning::output *outputAllocators =
1227 C2PortAllocatorsTuning::output::From(params[0].get());
1228 if (outputAllocators && outputAllocators->flexCount() > 0) {
1229 std::shared_ptr<C2Allocator> allocator;
1230 // verify allocator IDs and resolve default allocator
1231 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1232 if (allocator) {
1233 pools->outputAllocatorId = allocator->getId();
1234 } else {
1235 ALOGD("[%s] component requested invalid output allocator ID %u",
1236 mName, outputAllocators->m.values[0]);
1237 }
1238 }
1239 }
1240
1241 // use bufferqueue if outputting to a surface.
1242 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1243 // if unsuccessful.
1244 if (outputSurface) {
1245 params.clear();
1246 err = mComponent->query({ },
1247 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1248 C2_DONT_BLOCK,
1249 &params);
1250 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1251 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1252 mName, params.size(), asString(err), err);
1253 } else if (err == C2_OK && params.size() == 1) {
1254 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1255 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1256 if (surfaceAllocator) {
1257 std::shared_ptr<C2Allocator> allocator;
1258 // verify allocator IDs and resolve default allocator
1259 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1260 if (allocator) {
1261 pools->outputAllocatorId = allocator->getId();
1262 } else {
1263 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1264 mName, surfaceAllocator->value);
1265 err = C2_BAD_VALUE;
1266 }
1267 }
1268 }
1269 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1270 && err != C2_OK
1271 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1272 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1273 }
1274 }
1275
1276 if ((poolMask >> pools->outputAllocatorId) & 1) {
1277 err = mComponent->createBlockPool(
1278 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1279 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1280 mName, pools->outputAllocatorId,
1281 (unsigned long long)pools->outputPoolId,
1282 asString(err));
1283 } else {
1284 err = C2_NOT_FOUND;
1285 }
1286 if (err != C2_OK) {
1287 // use basic pool instead
1288 pools->outputPoolId =
1289 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1290 }
1291
1292 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1293 // component.
1294 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1295 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1296
1297 std::vector<std::unique_ptr<C2SettingResult>> failures;
1298 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1299 ALOGD("[%s] Configured output block pool ids %llu => %s",
1300 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1301 outputPoolId_ = pools->outputPoolId;
1302 }
1303
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001304 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001305 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001306 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001307 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001308 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001309 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001310 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001311 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001312 }
1313 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001314 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001315 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001316 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001317
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001318 output->buffers->clearStash();
1319 if (reorderDepth) {
1320 output->buffers->setReorderDepth(reorderDepth.value);
1321 }
1322 if (reorderKey) {
1323 output->buffers->setReorderKey(reorderKey.value);
1324 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001325
1326 // Try to set output surface to created block pool if given.
1327 if (outputSurface) {
1328 mComponent->setOutputSurface(
1329 outputPoolId_,
1330 outputSurface,
1331 outputGeneration);
1332 }
1333
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001334 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001335 if (buffersBoundToCodec) {
1336 // WORKAROUND: if we're using early CSD workaround we convert to
1337 // array mode, to appease apps assuming the output
1338 // buffers to be of the same size.
1339 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1340 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001341
1342 int32_t channelCount;
1343 int32_t sampleRate;
1344 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1345 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1346 int32_t delay = 0;
1347 int32_t padding = 0;;
1348 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1349 delay = 0;
1350 }
1351 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1352 padding = 0;
1353 }
1354 if (delay || padding) {
1355 // We need write access to the buffers, and we're already in
1356 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001357 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001358 }
1359 }
1360 }
1361 }
1362
1363 // Set up pipeline control. This has to be done after mInputBuffers and
1364 // mOutputBuffers are initialized to make sure that lingering callbacks
1365 // about buffers from the previous generation do not interfere with the
1366 // newly initialized pipeline capacity.
1367
Wonsik Kim62545252021-01-20 11:25:41 -08001368 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001369 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001370 watcher->inputDelay(inputDelayValue)
1371 .pipelineDelay(pipelineDelayValue)
1372 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001373 .smoothnessFactor(kSmoothnessFactor);
1374 watcher->flush();
1375 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001376
1377 mInputMetEos = false;
1378 mSync.start();
1379 return OK;
1380}
1381
1382status_t CCodecBufferChannel::requestInitialInputBuffers() {
1383 if (mInputSurface) {
1384 return OK;
1385 }
1386
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001387 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001388 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1389 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1390 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001391 return UNKNOWN_ERROR;
1392 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001393 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001394
1395 struct ClientInputBuffer {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001396 size_t index;
1397 sp<MediaCodecBuffer> buffer;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001398 size_t capacity;
1399 };
1400 std::list<ClientInputBuffer> clientInputBuffers;
1401
1402 {
1403 Mutexed<Input>::Locked input(mInput);
1404 while (clientInputBuffers.size() < numInputSlots) {
1405 ClientInputBuffer clientInputBuffer;
1406 if (!input->buffers->requestNewBuffer(&clientInputBuffer.index,
1407 &clientInputBuffer.buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001408 break;
1409 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001410 clientInputBuffer.capacity = clientInputBuffer.buffer->capacity();
1411 clientInputBuffers.emplace_back(std::move(clientInputBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001412 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001413 }
1414 if (clientInputBuffers.empty()) {
1415 ALOGW("[%s] start: cannot allocate memory at all", mName);
1416 return NO_MEMORY;
1417 } else if (clientInputBuffers.size() < numInputSlots) {
1418 ALOGD("[%s] start: cannot allocate memory for all slots, "
1419 "only %zu buffers allocated",
1420 mName, clientInputBuffers.size());
1421 } else {
1422 ALOGV("[%s] %zu initial input buffers available",
1423 mName, clientInputBuffers.size());
1424 }
1425 // Sort input buffers by their capacities in increasing order.
1426 clientInputBuffers.sort(
1427 [](const ClientInputBuffer& a, const ClientInputBuffer& b) {
1428 return a.capacity < b.capacity;
1429 });
1430
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001431 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1432 mFlushedConfigs.lock()->swap(flushedConfigs);
1433 if (!flushedConfigs.empty()) {
1434 err = mComponent->queue(&flushedConfigs);
1435 if (err != C2_OK) {
1436 ALOGW("[%s] Error while queueing a flushed config", mName);
1437 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001438 }
1439 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001440 if (oStreamFormat.value == C2BufferData::LINEAR &&
1441 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
1442 sp<MediaCodecBuffer> buffer = clientInputBuffers.front().buffer;
1443 // WORKAROUND: Some apps expect CSD available without queueing
1444 // any input. Queue an empty buffer to get the CSD.
1445 buffer->setRange(0, 0);
1446 buffer->meta()->clear();
1447 buffer->meta()->setInt64("timeUs", 0);
1448 if (queueInputBufferInternal(buffer) != OK) {
1449 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1450 mName);
1451 return UNKNOWN_ERROR;
1452 }
1453 clientInputBuffers.pop_front();
1454 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001455
1456 for (const ClientInputBuffer& clientInputBuffer: clientInputBuffers) {
1457 mCallback->onInputBufferAvailable(
1458 clientInputBuffer.index,
1459 clientInputBuffer.buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001460 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001461
Pawin Vongmasa36653902018-11-15 00:10:25 -08001462 return OK;
1463}
1464
1465void CCodecBufferChannel::stop() {
1466 mSync.stop();
1467 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001468}
1469
Wonsik Kim936a89c2020-05-08 16:07:50 -07001470void CCodecBufferChannel::reset() {
1471 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08001472 if (mInputSurface != nullptr) {
1473 mInputSurface.reset();
1474 }
1475 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001476 {
1477 Mutexed<Input>::Locked input(mInput);
1478 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001479 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001480 }
1481 {
1482 Mutexed<Output>::Locked output(mOutput);
1483 output->buffers.reset();
1484 }
1485}
1486
1487void CCodecBufferChannel::release() {
1488 mComponent.reset();
1489 mInputAllocator.reset();
1490 mOutputSurface.lock()->surface.clear();
1491 {
1492 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1493 blockPools->inputPool.reset();
1494 blockPools->outputPoolIntf.reset();
1495 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001496 setCrypto(nullptr);
1497 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001498}
1499
1500
Pawin Vongmasa36653902018-11-15 00:10:25 -08001501void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1502 ALOGV("[%s] flush", mName);
Wonsik Kim62545252021-01-20 11:25:41 -08001503 std::vector<uint64_t> indices;
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001504 std::list<std::unique_ptr<C2Work>> configs;
1505 for (const std::unique_ptr<C2Work> &work : flushedWork) {
Wonsik Kim62545252021-01-20 11:25:41 -08001506 indices.push_back(work->input.ordinal.frameIndex.peeku());
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001507 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1508 continue;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001509 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001510 if (work->input.buffers.empty()
1511 || work->input.buffers.front() == nullptr
1512 || work->input.buffers.front()->data().linearBlocks().empty()) {
1513 ALOGD("[%s] no linear codec config data found", mName);
1514 continue;
1515 }
1516 std::unique_ptr<C2Work> copy(new C2Work);
1517 copy->input.flags = C2FrameData::flags_t(work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1518 copy->input.ordinal = work->input.ordinal;
Wonsik Kim62545252021-01-20 11:25:41 -08001519 copy->input.ordinal.frameIndex = mFrameIndex++;
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001520 copy->input.buffers.insert(
1521 copy->input.buffers.begin(),
1522 work->input.buffers.begin(),
1523 work->input.buffers.end());
1524 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1525 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1526 }
1527 copy->input.infoBuffers.insert(
1528 copy->input.infoBuffers.begin(),
1529 work->input.infoBuffers.begin(),
1530 work->input.infoBuffers.end());
1531 copy->worklets.emplace_back(new C2Worklet);
1532 configs.push_back(std::move(copy));
1533 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001534 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001535 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001536 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001537 Mutexed<Input>::Locked input(mInput);
1538 input->buffers->flush();
1539 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001540 }
1541 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001542 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001543 if (output->buffers) {
1544 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001545 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001546 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001547 }
Wonsik Kim62545252021-01-20 11:25:41 -08001548 {
1549 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
1550 for (uint64_t index : indices) {
1551 watcher->onWorkDone(index);
1552 }
1553 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001554}
1555
1556void CCodecBufferChannel::onWorkDone(
1557 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001558 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001559 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001560 feedInputBufferIfAvailable();
1561 }
1562}
1563
1564void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001565 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001566 if (mInputSurface) {
1567 return;
1568 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001569 std::shared_ptr<C2Buffer> buffer =
1570 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001571 bool newInputSlotAvailable;
1572 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001573 Mutexed<Input>::Locked input(mInput);
1574 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1575 if (!newInputSlotAvailable) {
1576 (void)input->extraBuffers.expireComponentBuffer(buffer);
1577 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001578 }
1579 if (newInputSlotAvailable) {
1580 feedInputBufferIfAvailable();
1581 }
1582}
1583
1584bool CCodecBufferChannel::handleWork(
1585 std::unique_ptr<C2Work> work,
1586 const sp<AMessage> &outputFormat,
1587 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001588 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001589 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001590 if (!output->buffers) {
1591 return false;
1592 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001593 }
1594
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001595 // Whether the output buffer should be reported to the client or not.
1596 bool notifyClient = false;
1597
1598 if (work->result == C2_OK){
1599 notifyClient = true;
1600 } else if (work->result == C2_NOT_FOUND) {
1601 ALOGD("[%s] flushed work; ignored.", mName);
1602 } else {
1603 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1604 // the config update.
1605 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1606 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1607 return false;
1608 }
1609
1610 if ((work->input.ordinal.frameIndex -
1611 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001612 // Discard frames from previous generation.
1613 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001614 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001615 }
1616
Wonsik Kim524b0582019-03-12 11:28:57 -07001617 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001618 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001619 || !(work->worklets.front()->output.flags &
1620 C2FrameData::FLAG_INCOMPLETE))) {
1621 mPipelineWatcher.lock()->onWorkDone(
1622 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001623 }
1624
1625 // NOTE: MediaCodec usage supposedly have only one worklet
1626 if (work->worklets.size() != 1u) {
1627 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1628 mName, work->worklets.size());
1629 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1630 return false;
1631 }
1632
1633 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1634
1635 std::shared_ptr<C2Buffer> buffer;
1636 // NOTE: MediaCodec usage supposedly have only one output stream.
1637 if (worklet->output.buffers.size() > 1u) {
1638 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1639 mName, worklet->output.buffers.size());
1640 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1641 return false;
1642 } else if (worklet->output.buffers.size() == 1u) {
1643 buffer = worklet->output.buffers[0];
1644 if (!buffer) {
1645 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1646 }
1647 }
1648
Wonsik Kim3dedf682021-05-03 10:57:09 -07001649 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
1650 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001651 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001652 while (!worklet->output.configUpdate.empty()) {
1653 std::unique_ptr<C2Param> param;
1654 worklet->output.configUpdate.back().swap(param);
1655 worklet->output.configUpdate.pop_back();
1656 switch (param->coreIndex().coreIndex()) {
1657 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1658 C2PortReorderBufferDepthTuning::output reorderDepth;
1659 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001660 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1661 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001662 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001663 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001664 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001665 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1666 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001667 }
1668 break;
1669 }
1670 case C2PortReorderKeySetting::CORE_INDEX: {
1671 C2PortReorderKeySetting::output reorderKey;
1672 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07001673 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001674 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1675 mName, reorderKey.value);
1676 } else {
1677 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1678 }
1679 break;
1680 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001681 case C2PortActualDelayTuning::CORE_INDEX: {
1682 if (param->isGlobal()) {
1683 C2ActualPipelineDelayTuning pipelineDelay;
1684 if (pipelineDelay.updateFrom(*param)) {
1685 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1686 mName, pipelineDelay.value);
1687 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001688 (void)mPipelineWatcher.lock()->pipelineDelay(
1689 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001690 }
1691 }
1692 if (param->forInput()) {
1693 C2PortActualDelayTuning::input inputDelay;
1694 if (inputDelay.updateFrom(*param)) {
1695 ALOGV("[%s] onWorkDone: updating input delay %u",
1696 mName, inputDelay.value);
1697 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001698 (void)mPipelineWatcher.lock()->inputDelay(
1699 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001700 }
1701 }
1702 if (param->forOutput()) {
1703 C2PortActualDelayTuning::output outputDelay;
1704 if (outputDelay.updateFrom(*param)) {
1705 ALOGV("[%s] onWorkDone: updating output delay %u",
1706 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001707 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07001708 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001709 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001710
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001711 }
1712 }
1713 break;
1714 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08001715 case C2PortTunnelSystemTime::CORE_INDEX: {
1716 C2PortTunnelSystemTime::output frameRenderTime;
1717 if (frameRenderTime.updateFrom(*param)) {
1718 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
1719 mName, (long long)frameRenderTime.value,
1720 (long long)worklet->output.ordinal.timestamp.peekll());
1721 mCCodecCallback->onOutputFramesRendered(
1722 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
1723 }
1724 break;
1725 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02001726 case C2StreamTunnelHoldRender::CORE_INDEX: {
1727 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
1728 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
1729 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
1730 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
1731 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
1732 mCCodecCallback->onFirstTunnelFrameReady();
1733 break;
1734 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001735 default:
1736 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1737 mName, param->index());
1738 break;
1739 }
1740 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001741 if (newInputDelay || newPipelineDelay) {
1742 Mutexed<Input>::Locked input(mInput);
1743 size_t newNumSlots =
1744 newInputDelay.value_or(input->inputDelay) +
1745 newPipelineDelay.value_or(input->pipelineDelay) +
1746 kSmoothnessFactor;
1747 if (input->buffers->isArrayMode()) {
1748 if (input->numSlots >= newNumSlots) {
1749 input->numExtraSlots = 0;
1750 } else {
1751 input->numExtraSlots = newNumSlots - input->numSlots;
1752 }
1753 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1754 mName, input->numExtraSlots);
1755 } else {
1756 input->numSlots = newNumSlots;
1757 }
1758 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001759 size_t numOutputSlots = 0;
1760 uint32_t reorderDepth = 0;
1761 bool outputBuffersChanged = false;
1762 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
1763 Mutexed<Output>::Locked output(mOutput);
1764 if (!output->buffers) {
1765 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001766 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07001767 numOutputSlots = output->numSlots;
1768 if (newReorderKey) {
1769 output->buffers->setReorderKey(newReorderKey.value());
1770 }
1771 if (newReorderDepth) {
1772 output->buffers->setReorderDepth(newReorderDepth.value());
1773 }
1774 reorderDepth = output->buffers->getReorderDepth();
1775 if (newOutputDelay) {
1776 output->outputDelay = newOutputDelay.value();
1777 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
1778 if (output->numSlots < numOutputSlots) {
1779 output->numSlots = numOutputSlots;
1780 if (output->buffers->isArrayMode()) {
1781 OutputBuffersArray *array =
1782 (OutputBuffersArray *)output->buffers.get();
1783 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1784 mName, numOutputSlots);
1785 array->grow(numOutputSlots);
1786 outputBuffersChanged = true;
1787 }
1788 }
1789 }
1790 numOutputSlots = output->numSlots;
1791 }
1792 if (outputBuffersChanged) {
1793 mCCodecCallback->onOutputBuffersChanged();
1794 }
1795 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim315e40a2020-09-09 14:11:50 -07001796 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1797 output->maxDequeueBuffers = numOutputSlots + reorderDepth + kRenderingDepth;
1798 if (output->surface) {
1799 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1800 }
1801 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001802
Pawin Vongmasa36653902018-11-15 00:10:25 -08001803 int32_t flags = 0;
1804 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1805 flags |= MediaCodec::BUFFER_FLAG_EOS;
1806 ALOGV("[%s] onWorkDone: output EOS", mName);
1807 }
1808
Pawin Vongmasa36653902018-11-15 00:10:25 -08001809 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1810 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1811 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1812 // shall correspond to the client input timesamp (in customOrdinal). By using the
1813 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1814 // produces multiple output.
1815 c2_cntr64_t timestamp =
1816 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1817 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001818 if (mInputSurface != nullptr) {
1819 // When using input surface we need to restore the original input timestamp.
1820 timestamp = work->input.ordinal.customOrdinal;
1821 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001822 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1823 mName,
1824 work->input.ordinal.customOrdinal.peekll(),
1825 work->input.ordinal.timestamp.peekll(),
1826 worklet->output.ordinal.timestamp.peekll(),
1827 timestamp.peekll());
1828
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001829 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001830 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001831 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001832 if (output->buffers && outputFormat) {
1833 output->buffers->updateSkipCutBuffer(outputFormat);
1834 output->buffers->setFormat(outputFormat);
1835 }
1836 if (!notifyClient) {
1837 return false;
1838 }
1839 size_t index;
1840 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07001841 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001842 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1843 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1844 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1845
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001846 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001847 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001848 } else {
1849 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001850 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001851 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001852 return false;
1853 }
1854 }
1855
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001856 if (notifyClient && !buffer && !flags) {
Wonsik Kim35bf5732020-05-14 17:40:29 +00001857 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001858 mName, work->input.ordinal.frameIndex.peekull());
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001859 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001860 }
1861
1862 if (buffer) {
1863 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1864 // TODO: properly translate these to metadata
1865 switch (info->coreIndex().coreIndex()) {
1866 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001867 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001868 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1869 }
1870 break;
1871 default:
1872 break;
1873 }
1874 }
1875 }
1876
1877 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001878 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07001879 if (!output->buffers) {
1880 return false;
1881 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001882 output->buffers->pushToStash(
1883 buffer,
1884 notifyClient,
1885 timestamp.peek(),
1886 flags,
1887 outputFormat,
1888 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001889 }
1890 sendOutputBuffers();
1891 return true;
1892}
1893
1894void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001895 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001896 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001897 sp<MediaCodecBuffer> outBuffer;
1898 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001899
1900 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001901 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001902 if (!output->buffers) {
1903 return;
1904 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001905 action = output->buffers->popFromStashAndRegister(
1906 &c2Buffer, &index, &outBuffer);
1907 switch (action) {
1908 case OutputBuffers::SKIP:
1909 return;
1910 case OutputBuffers::DISCARD:
1911 break;
1912 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00001913 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001914 mCallback->onOutputBufferAvailable(index, outBuffer);
1915 break;
1916 case OutputBuffers::REALLOCATE:
1917 if (!output->buffers->isArrayMode()) {
1918 output->buffers =
1919 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001920 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001921 static_cast<OutputBuffersArray*>(output->buffers.get())->
1922 realloc(c2Buffer);
1923 output.unlock();
1924 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07001925 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001926 case OutputBuffers::RETRY:
1927 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
1928 mName);
1929 return;
1930 default:
1931 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
1932 "corrupted BufferAction value (%d) "
1933 "returned from popFromStashAndRegister.",
1934 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001935 return;
1936 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001937 }
1938}
1939
1940status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1941 static std::atomic_uint32_t surfaceGeneration{0};
1942 uint32_t generation = (getpid() << 10) |
1943 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1944 & ((1 << 10) - 1));
1945
1946 sp<IGraphicBufferProducer> producer;
1947 if (newSurface) {
1948 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001949 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Lee08515812019-06-05 11:16:32 -07001950 newSurface->setMaxDequeuedBufferCount(mOutputSurface.lock()->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001951 producer = newSurface->getIGraphicBufferProducer();
1952 producer->setGenerationNumber(generation);
1953 } else {
1954 ALOGE("[%s] setting output surface to null", mName);
1955 return INVALID_OPERATION;
1956 }
1957
1958 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1959 C2BlockPool::local_id_t outputPoolId;
1960 {
1961 Mutexed<BlockPools>::Locked pools(mBlockPools);
1962 outputPoolId = pools->outputPoolId;
1963 outputPoolIntf = pools->outputPoolIntf;
1964 }
1965
1966 if (outputPoolIntf) {
1967 if (mComponent->setOutputSurface(
1968 outputPoolId,
1969 producer,
1970 generation) != C2_OK) {
1971 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1972 return INVALID_OPERATION;
1973 }
1974 }
1975
1976 {
1977 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1978 output->surface = newSurface;
1979 output->generation = generation;
1980 }
1981
1982 return OK;
1983}
1984
Wonsik Kimab34ed62019-01-31 15:28:46 -08001985PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001986 // When client pushed EOS, we want all the work to be done quickly.
1987 // Otherwise, component may have stalled work due to input starvation up to
1988 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001989 size_t n = 0;
1990 if (!mInputMetEos) {
1991 size_t outputDelay = mOutput.lock()->outputDelay;
1992 Mutexed<Input>::Locked input(mInput);
1993 n = input->inputDelay + input->pipelineDelay + outputDelay;
1994 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001995 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001996}
1997
Pawin Vongmasa36653902018-11-15 00:10:25 -08001998void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1999 mMetaMode = mode;
2000}
2001
Wonsik Kim596187e2019-10-25 12:44:10 -07002002void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002003 if (mCrypto != nullptr) {
2004 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2005 mCrypto->unsetHeap(entry.second);
2006 }
2007 mHeapSeqNumMap.clear();
2008 if (mHeapSeqNum >= 0) {
2009 mCrypto->unsetHeap(mHeapSeqNum);
2010 mHeapSeqNum = -1;
2011 }
2012 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002013 mCrypto = crypto;
2014}
2015
2016void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2017 mDescrambler = descrambler;
2018}
2019
Pawin Vongmasa36653902018-11-15 00:10:25 -08002020status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2021 // C2_OK is always translated to OK.
2022 if (c2s == C2_OK) {
2023 return OK;
2024 }
2025
2026 // Operation-dependent translation
2027 // TODO: Add as necessary
2028 switch (c2op) {
2029 case C2_OPERATION_Component_start:
2030 switch (c2s) {
2031 case C2_NO_MEMORY:
2032 return NO_MEMORY;
2033 default:
2034 return UNKNOWN_ERROR;
2035 }
2036 default:
2037 break;
2038 }
2039
2040 // Backup operation-agnostic translation
2041 switch (c2s) {
2042 case C2_BAD_INDEX:
2043 return BAD_INDEX;
2044 case C2_BAD_VALUE:
2045 return BAD_VALUE;
2046 case C2_BLOCKING:
2047 return WOULD_BLOCK;
2048 case C2_DUPLICATE:
2049 return ALREADY_EXISTS;
2050 case C2_NO_INIT:
2051 return NO_INIT;
2052 case C2_NO_MEMORY:
2053 return NO_MEMORY;
2054 case C2_NOT_FOUND:
2055 return NAME_NOT_FOUND;
2056 case C2_TIMED_OUT:
2057 return TIMED_OUT;
2058 case C2_BAD_STATE:
2059 case C2_CANCELED:
2060 case C2_CANNOT_DO:
2061 case C2_CORRUPTED:
2062 case C2_OMITTED:
2063 case C2_REFUSED:
2064 return UNKNOWN_ERROR;
2065 default:
2066 return -static_cast<status_t>(c2s);
2067 }
2068}
2069
2070} // namespace android