blob: ba1d1782d0de194de329a25a10d36f72ef6d81eb [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>
Pawin Vongmasa36653902018-11-15 00:10:25 -080033#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080034#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080035#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070036#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080037#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070038#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080039#include <media/openmax/OMX_Core.h>
40#include <media/stagefright/foundation/ABuffer.h>
41#include <media/stagefright/foundation/ALookup.h>
42#include <media/stagefright/foundation/AMessage.h>
43#include <media/stagefright/foundation/AUtils.h>
44#include <media/stagefright/foundation/hexdump.h>
45#include <media/stagefright/MediaCodec.h>
46#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070047#include <media/stagefright/SkipCutBuffer.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080048#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070049#include <mediadrm/ICrypto.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080050#include <system/window.h>
51
52#include "CCodecBufferChannel.h"
53#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080054
55namespace android {
56
57using android::base::StringPrintf;
58using hardware::hidl_handle;
59using hardware::hidl_string;
60using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070061using hardware::fromHeap;
62using hardware::HidlMemory;
63
Pawin Vongmasa36653902018-11-15 00:10:25 -080064using namespace hardware::cas::V1_0;
65using namespace hardware::cas::native::V1_0;
66
67using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070068using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080069
Pawin Vongmasa36653902018-11-15 00:10:25 -080070namespace {
71
Wonsik Kim469c8342019-04-11 16:46:09 -070072constexpr size_t kSmoothnessFactor = 4;
73constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080074
Sungtak Leeab6f2f32019-02-15 14:43:51 -080075// This is for keeping IGBP's buffer dropping logic in legacy mode other
76// than making it non-blocking. Do not change this value.
77const static size_t kDequeueTimeoutNs = 0;
78
Pawin Vongmasa36653902018-11-15 00:10:25 -080079} // namespace
80
81CCodecBufferChannel::QueueGuard::QueueGuard(
82 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
83 Mutex::Autolock l(mSync.mGuardLock);
84 // At this point it's guaranteed that mSync is not under state transition,
85 // as we are holding its mutex.
86
87 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
88 if (count->value == -1) {
89 mRunning = false;
90 } else {
91 ++count->value;
92 mRunning = true;
93 }
94}
95
96CCodecBufferChannel::QueueGuard::~QueueGuard() {
97 if (mRunning) {
98 // We are not holding mGuardLock at this point so that QueueSync::stop() can
99 // keep holding the lock until mCount reaches zero.
100 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
101 --count->value;
102 count->cond.broadcast();
103 }
104}
105
106void CCodecBufferChannel::QueueSync::start() {
107 Mutex::Autolock l(mGuardLock);
108 // If stopped, it goes to running state; otherwise no-op.
109 Mutexed<Counter>::Locked count(mCount);
110 if (count->value == -1) {
111 count->value = 0;
112 }
113}
114
115void CCodecBufferChannel::QueueSync::stop() {
116 Mutex::Autolock l(mGuardLock);
117 Mutexed<Counter>::Locked count(mCount);
118 if (count->value == -1) {
119 // no-op
120 return;
121 }
122 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
123 // mCount can only decrement. In other words, threads that acquired the lock
124 // are allowed to finish execution but additional threads trying to acquire
125 // the lock at this point will block, and then get QueueGuard at STOPPED
126 // state.
127 while (count->value != 0) {
128 count.waitForCondition(count->cond);
129 }
130 count->value = -1;
131}
132
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700133// Input
134
135CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
136
Pawin Vongmasa36653902018-11-15 00:10:25 -0800137// CCodecBufferChannel
138
139CCodecBufferChannel::CCodecBufferChannel(
140 const std::shared_ptr<CCodecCallback> &callback)
141 : mHeapSeqNum(-1),
142 mCCodecCallback(callback),
143 mFrameIndex(0u),
144 mFirstValidFrameIndex(0u),
145 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700146 mInputMetEos(false),
147 mSendEncryptedInfoBuffer(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700148 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700149 {
150 Mutexed<Input>::Locked input(mInput);
151 input->buffers.reset(new DummyInputBuffers(""));
152 input->extraBuffers.flush();
153 input->inputDelay = 0u;
154 input->pipelineDelay = 0u;
155 input->numSlots = kSmoothnessFactor;
156 input->numExtraSlots = 0u;
157 }
158 {
159 Mutexed<Output>::Locked output(mOutput);
160 output->outputDelay = 0u;
161 output->numSlots = kSmoothnessFactor;
162 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800163}
164
165CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800166 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800167 mCrypto->unsetHeap(mHeapSeqNum);
168 }
169}
170
171void CCodecBufferChannel::setComponent(
172 const std::shared_ptr<Codec2Client::Component> &component) {
173 mComponent = component;
174 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
175 mName = mComponentName.c_str();
176}
177
178status_t CCodecBufferChannel::setInputSurface(
179 const std::shared_ptr<InputSurfaceWrapper> &surface) {
180 ALOGV("[%s] setInputSurface", mName);
181 mInputSurface = surface;
182 return mInputSurface->connect(mComponent);
183}
184
185status_t CCodecBufferChannel::signalEndOfInputStream() {
186 if (mInputSurface == nullptr) {
187 return INVALID_OPERATION;
188 }
189 return mInputSurface->signalEndOfInputStream();
190}
191
Sungtak Lee04b30352020-07-27 13:57:25 -0700192status_t CCodecBufferChannel::queueInputBufferInternal(
193 sp<MediaCodecBuffer> buffer,
194 std::shared_ptr<C2LinearBlock> encryptedBlock,
195 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800196 int64_t timeUs;
197 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
198
199 if (mInputMetEos) {
200 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
201 return OK;
202 }
203
204 int32_t flags = 0;
205 int32_t tmp = 0;
206 bool eos = false;
207 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
208 eos = true;
209 mInputMetEos = true;
210 ALOGV("[%s] input EOS", mName);
211 }
212 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
213 flags |= C2FrameData::FLAG_CODEC_CONFIG;
214 }
215 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800216 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800217 std::unique_ptr<C2Work> work(new C2Work);
218 work->input.ordinal.timestamp = timeUs;
219 work->input.ordinal.frameIndex = mFrameIndex++;
220 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
221 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
222 // Keep client timestamp in customOrdinal
223 work->input.ordinal.customOrdinal = timeUs;
224 work->input.buffers.clear();
225
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700226 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800227 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800228
Pawin Vongmasa36653902018-11-15 00:10:25 -0800229 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700230 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800231 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700232 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800233 return -ENOENT;
234 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700235 // TODO: we want to delay copying buffers.
236 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
237 copy = input->buffers->cloneAndReleaseBuffer(buffer);
238 if (copy != nullptr) {
239 (void)input->extraBuffers.assignSlot(copy);
240 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
241 return UNKNOWN_ERROR;
242 }
243 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
244 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
245 mName, released ? "" : "not ");
246 buffer.clear();
247 } else {
248 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
249 "buffer starvation on component.", mName);
250 }
251 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800252 if (input->frameReassembler) {
253 usesFrameReassembler = true;
254 input->frameReassembler.process(buffer, &items);
255 } else {
256 work->input.buffers.push_back(c2buffer);
257 if (encryptedBlock) {
258 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
259 kParamIndexEncryptedBuffer,
260 encryptedBlock->share(0, blockSize, C2Fence())));
261 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700262 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800263 } else if (eos) {
264 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800265 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800266 if (usesFrameReassembler) {
267 if (!items.empty()) {
268 items.front()->input.configUpdate = std::move(mParamsToBeSet);
269 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
270 }
271 } else {
272 work->input.flags = (C2FrameData::flags_t)flags;
273 // TODO: fill info's
Pawin Vongmasa36653902018-11-15 00:10:25 -0800274
Wonsik Kime1104ca2020-11-24 15:01:33 -0800275 work->input.configUpdate = std::move(mParamsToBeSet);
276 work->worklets.clear();
277 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800278
Wonsik Kime1104ca2020-11-24 15:01:33 -0800279 items.push_back(std::move(work));
280
281 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800282 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800283 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800284 work.reset(new C2Work);
285 work->input.ordinal.timestamp = timeUs;
286 work->input.ordinal.frameIndex = mFrameIndex++;
287 // WORKAROUND: keep client timestamp in customOrdinal
288 work->input.ordinal.customOrdinal = timeUs;
289 work->input.buffers.clear();
290 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800291 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800292 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800293 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800294 c2_status_t err = C2_OK;
295 if (!items.empty()) {
296 {
297 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
298 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
299 for (const std::unique_ptr<C2Work> &work : items) {
300 watcher->onWorkQueued(
301 work->input.ordinal.frameIndex.peeku(),
302 std::vector(work->input.buffers),
303 now);
304 }
305 }
306 err = mComponent->queue(&items);
307 }
308 if (err != C2_OK) {
309 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
310 for (const std::unique_ptr<C2Work> &work : items) {
311 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
312 }
313 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700314 Mutexed<Input>::Locked input(mInput);
315 bool released = false;
316 if (buffer) {
317 released = input->buffers->releaseBuffer(buffer, nullptr, true);
318 } else if (copy) {
319 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
320 }
321 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
322 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800323 }
324
325 feedInputBufferIfAvailableInternal();
326 return err;
327}
328
329status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
330 QueueGuard guard(mSync);
331 if (!guard.isRunning()) {
332 ALOGD("[%s] setParameters is only supported in the running state.", mName);
333 return -ENOSYS;
334 }
335 mParamsToBeSet.insert(mParamsToBeSet.end(),
336 std::make_move_iterator(params.begin()),
337 std::make_move_iterator(params.end()));
338 params.clear();
339 return OK;
340}
341
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800342status_t CCodecBufferChannel::attachBuffer(
343 const std::shared_ptr<C2Buffer> &c2Buffer,
344 const sp<MediaCodecBuffer> &buffer) {
345 if (!buffer->copy(c2Buffer)) {
346 return -ENOSYS;
347 }
348 return OK;
349}
350
351void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
352 if (!mDecryptDestination || mDecryptDestination->size() < size) {
353 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
354 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
355 mCrypto->unsetHeap(mHeapSeqNum);
356 }
357 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
358 if (mCrypto) {
359 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
360 }
361 }
362}
363
364int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
365 CHECK(mCrypto);
366 auto it = mHeapSeqNumMap.find(memory);
367 int32_t heapSeqNum = -1;
368 if (it == mHeapSeqNumMap.end()) {
369 heapSeqNum = mCrypto->setHeap(memory);
370 mHeapSeqNumMap.emplace(memory, heapSeqNum);
371 } else {
372 heapSeqNum = it->second;
373 }
374 return heapSeqNum;
375}
376
377status_t CCodecBufferChannel::attachEncryptedBuffer(
378 const sp<hardware::HidlMemory> &memory,
379 bool secure,
380 const uint8_t *key,
381 const uint8_t *iv,
382 CryptoPlugin::Mode mode,
383 CryptoPlugin::Pattern pattern,
384 size_t offset,
385 const CryptoPlugin::SubSample *subSamples,
386 size_t numSubSamples,
387 const sp<MediaCodecBuffer> &buffer) {
388 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
389 static const C2MemoryUsage kDefaultReadWriteUsage{
390 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
391
392 size_t size = 0;
393 for (size_t i = 0; i < numSubSamples; ++i) {
394 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
395 }
396 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
397 std::shared_ptr<C2LinearBlock> block;
398 c2_status_t err = pool->fetchLinearBlock(
399 size,
400 secure ? kSecureUsage : kDefaultReadWriteUsage,
401 &block);
402 if (err != C2_OK) {
403 return NO_MEMORY;
404 }
405 if (!secure) {
406 ensureDecryptDestination(size);
407 }
408 ssize_t result = -1;
409 ssize_t codecDataOffset = 0;
410 if (mCrypto) {
411 AString errorDetailMsg;
412 int32_t heapSeqNum = getHeapSeqNum(memory);
413 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
414 hardware::drm::V1_0::DestinationBuffer dst;
415 if (secure) {
416 dst.type = DrmBufferType::NATIVE_HANDLE;
417 dst.secureMemory = hardware::hidl_handle(block->handle());
418 } else {
419 dst.type = DrmBufferType::SHARED_MEMORY;
420 IMemoryToSharedBuffer(
421 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
422 }
423 result = mCrypto->decrypt(
424 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
425 dst, &errorDetailMsg);
426 if (result < 0) {
427 return result;
428 }
429 if (dst.type == DrmBufferType::SHARED_MEMORY) {
430 C2WriteView view = block->map().get();
431 if (view.error() != C2_OK) {
432 return false;
433 }
434 if (view.size() < result) {
435 return false;
436 }
437 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
438 }
439 } else {
440 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
441 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
442 hidl_vec<SubSample> hidlSubSamples;
443 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
444
445 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
446 hardware::cas::native::V1_0::DestinationBuffer dst;
447 if (secure) {
448 dst.type = BufferType::NATIVE_HANDLE;
449 dst.secureMemory = hardware::hidl_handle(block->handle());
450 } else {
451 dst.type = BufferType::SHARED_MEMORY;
452 dst.nonsecureMemory = src;
453 }
454
455 CasStatus status = CasStatus::OK;
456 hidl_string detailedError;
457 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
458
459 if (key != nullptr) {
460 sctrl = (ScramblingControl)key[0];
461 // Adjust for the PES offset
462 codecDataOffset = key[2] | (key[3] << 8);
463 }
464
465 auto returnVoid = mDescrambler->descramble(
466 sctrl,
467 hidlSubSamples,
468 src,
469 0,
470 dst,
471 0,
472 [&status, &result, &detailedError] (
473 CasStatus _status, uint32_t _bytesWritten,
474 const hidl_string& _detailedError) {
475 status = _status;
476 result = (ssize_t)_bytesWritten;
477 detailedError = _detailedError;
478 });
479
480 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
481 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
482 mName, returnVoid.description().c_str(), status, result);
483 return UNKNOWN_ERROR;
484 }
485
486 if (result < codecDataOffset) {
487 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
488 return BAD_VALUE;
489 }
490 }
491 if (!secure) {
492 C2WriteView view = block->map().get();
493 if (view.error() != C2_OK) {
494 return UNKNOWN_ERROR;
495 }
496 if (view.size() < result) {
497 return UNKNOWN_ERROR;
498 }
499 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
500 }
501 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
502 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
503 if (!buffer->copy(c2Buffer)) {
504 return -ENOSYS;
505 }
506 return OK;
507}
508
Pawin Vongmasa36653902018-11-15 00:10:25 -0800509status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
510 QueueGuard guard(mSync);
511 if (!guard.isRunning()) {
512 ALOGD("[%s] No more buffers should be queued at current state.", mName);
513 return -ENOSYS;
514 }
515 return queueInputBufferInternal(buffer);
516}
517
518status_t CCodecBufferChannel::queueSecureInputBuffer(
519 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
520 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
521 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
522 AString *errorDetailMsg) {
523 QueueGuard guard(mSync);
524 if (!guard.isRunning()) {
525 ALOGD("[%s] No more buffers should be queued at current state.", mName);
526 return -ENOSYS;
527 }
528
529 if (!hasCryptoOrDescrambler()) {
530 return -ENOSYS;
531 }
532 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
533
Sungtak Lee04b30352020-07-27 13:57:25 -0700534 std::shared_ptr<C2LinearBlock> block;
535 size_t allocSize = buffer->size();
536 size_t bufferSize = 0;
537 c2_status_t blockRes = C2_OK;
538 bool copied = false;
539 if (mSendEncryptedInfoBuffer) {
540 static const C2MemoryUsage kDefaultReadWriteUsage{
541 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
542 constexpr int kAllocGranule0 = 1024 * 64;
543 constexpr int kAllocGranule1 = 1024 * 1024;
544 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
545 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
546 if (allocSize <= kAllocGranule1) {
547 bufferSize = align(allocSize, kAllocGranule0);
548 } else {
549 bufferSize = align(allocSize, kAllocGranule1);
550 }
551 blockRes = pool->fetchLinearBlock(
552 bufferSize, kDefaultReadWriteUsage, &block);
553
554 if (blockRes == C2_OK) {
555 C2WriteView view = block->map().get();
556 if (view.error() == C2_OK && view.size() == bufferSize) {
557 copied = true;
558 // TODO: only copy clear sections
559 memcpy(view.data(), buffer->data(), allocSize);
560 }
561 }
562 }
563
564 if (!copied) {
565 block.reset();
566 }
567
Pawin Vongmasa36653902018-11-15 00:10:25 -0800568 ssize_t result = -1;
569 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700570 if (numSubSamples == 1
571 && subSamples[0].mNumBytesOfClearData == 0
572 && subSamples[0].mNumBytesOfEncryptedData == 0) {
573 // We don't need to go through crypto or descrambler if the input is empty.
574 result = 0;
575 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700576 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800577 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700578 destination.type = DrmBufferType::NATIVE_HANDLE;
579 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800580 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700581 destination.type = DrmBufferType::SHARED_MEMORY;
582 IMemoryToSharedBuffer(
583 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800584 }
Robert Shih895fba92019-07-16 16:29:44 -0700585 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800586 encryptedBuffer->fillSourceBuffer(&source);
587 result = mCrypto->decrypt(
588 key, iv, mode, pattern, source, buffer->offset(),
589 subSamples, numSubSamples, destination, errorDetailMsg);
590 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700591 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800592 return result;
593 }
Robert Shih895fba92019-07-16 16:29:44 -0700594 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800595 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
596 }
597 } else {
598 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
599 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
600 hidl_vec<SubSample> hidlSubSamples;
601 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
602
603 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
604 encryptedBuffer->fillSourceBuffer(&srcBuffer);
605
606 DestinationBuffer dstBuffer;
607 if (secure) {
608 dstBuffer.type = BufferType::NATIVE_HANDLE;
609 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
610 } else {
611 dstBuffer.type = BufferType::SHARED_MEMORY;
612 dstBuffer.nonsecureMemory = srcBuffer;
613 }
614
615 CasStatus status = CasStatus::OK;
616 hidl_string detailedError;
617 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
618
619 if (key != nullptr) {
620 sctrl = (ScramblingControl)key[0];
621 // Adjust for the PES offset
622 codecDataOffset = key[2] | (key[3] << 8);
623 }
624
625 auto returnVoid = mDescrambler->descramble(
626 sctrl,
627 hidlSubSamples,
628 srcBuffer,
629 0,
630 dstBuffer,
631 0,
632 [&status, &result, &detailedError] (
633 CasStatus _status, uint32_t _bytesWritten,
634 const hidl_string& _detailedError) {
635 status = _status;
636 result = (ssize_t)_bytesWritten;
637 detailedError = _detailedError;
638 });
639
640 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
641 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
642 mName, returnVoid.description().c_str(), status, result);
643 return UNKNOWN_ERROR;
644 }
645
646 if (result < codecDataOffset) {
647 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
648 return BAD_VALUE;
649 }
650
651 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
652
653 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
654 encryptedBuffer->copyDecryptedContentFromMemory(result);
655 }
656 }
657
658 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700659
660 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800661}
662
663void CCodecBufferChannel::feedInputBufferIfAvailable() {
664 QueueGuard guard(mSync);
665 if (!guard.isRunning()) {
666 ALOGV("[%s] We're not running --- no input buffer reported", mName);
667 return;
668 }
669 feedInputBufferIfAvailableInternal();
670}
671
672void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900673 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800674 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700675 }
676 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700677 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700678 if (!output->buffers ||
679 output->buffers->hasPending() ||
Wonsik Kim0487b782020-10-28 11:45:50 -0700680 output->buffers->numActiveSlots() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800681 return;
682 }
683 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700684 size_t numActiveSlots = 0;
685 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800686 sp<MediaCodecBuffer> inBuffer;
687 size_t index;
688 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700689 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -0700690 numActiveSlots = input->buffers->numActiveSlots();
691 if (numActiveSlots >= input->numSlots) {
692 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800693 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700694 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800695 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800696 break;
697 }
698 }
699 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
700 mCallback->onInputBufferAvailable(index, inBuffer);
701 }
Wonsik Kim0487b782020-10-28 11:45:50 -0700702 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800703}
704
705status_t CCodecBufferChannel::renderOutputBuffer(
706 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800707 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800708 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800709 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800710 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700711 Mutexed<Output>::Locked output(mOutput);
712 if (output->buffers) {
713 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800714 }
715 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800716 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
717 // set to true.
718 sendOutputBuffers();
719 // input buffer feeding may have been gated by pending output buffers
720 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800721 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800722 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700723 std::call_once(mRenderWarningFlag, [this] {
724 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
725 "timestamp or render=true with non-video buffers. Apps should "
726 "call releaseOutputBuffer() with render=false for those.",
727 mName);
728 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800729 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800730 return INVALID_OPERATION;
731 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800732
733#if 0
734 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
735 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
736 for (const std::shared_ptr<const C2Info> &info : infoParams) {
737 AString res;
738 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
739 if (ix) res.append(", ");
740 res.append(*((int32_t*)info.get() + (ix / 4)));
741 }
742 ALOGV(" [%s]", res.c_str());
743 }
744#endif
745 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
746 std::static_pointer_cast<const C2StreamRotationInfo::output>(
747 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
748 bool flip = rotation && (rotation->flip & 1);
749 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
750 uint32_t transform = 0;
751 switch (quarters) {
752 case 0: // no rotation
753 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
754 break;
755 case 1: // 90 degrees counter-clockwise
756 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
757 : HAL_TRANSFORM_ROT_270;
758 break;
759 case 2: // 180 degrees
760 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
761 break;
762 case 3: // 90 degrees clockwise
763 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
764 : HAL_TRANSFORM_ROT_90;
765 break;
766 }
767
768 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
769 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
770 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
771 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
772 if (surfaceScaling) {
773 videoScalingMode = surfaceScaling->value;
774 }
775
776 // Use dataspace from format as it has the default aspects already applied
777 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
778 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
779
780 // HDR static info
781 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
782 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
783 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
784
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800785 // HDR10 plus info
786 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
787 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
788 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800789 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
790 hdr10PlusInfo.reset();
791 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800792
Pawin Vongmasa36653902018-11-15 00:10:25 -0800793 {
794 Mutexed<OutputSurface>::Locked output(mOutputSurface);
795 if (output->surface == nullptr) {
796 ALOGI("[%s] cannot render buffer without surface", mName);
797 return OK;
798 }
799 }
800
801 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
802 if (blocks.size() != 1u) {
803 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
804 return UNKNOWN_ERROR;
805 }
806 const C2ConstGraphicBlock &block = blocks.front();
807
808 // TODO: revisit this after C2Fence implementation.
809 android::IGraphicBufferProducer::QueueBufferInput qbi(
810 timestampNs,
811 false, // droppable
812 dataSpace,
813 Rect(blocks.front().crop().left,
814 blocks.front().crop().top,
815 blocks.front().crop().right(),
816 blocks.front().crop().bottom()),
817 videoScalingMode,
818 transform,
819 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800820 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800821 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800822 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800823 // If mastering max and min luminance fields are 0, do not use them.
824 // It indicates the value may not be present in the stream.
825 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
826 hdrStaticInfo->mastering.minLuminance > 0.0f) {
827 struct android_smpte2086_metadata smpte2086_meta = {
828 .displayPrimaryRed = {
829 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
830 },
831 .displayPrimaryGreen = {
832 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
833 },
834 .displayPrimaryBlue = {
835 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
836 },
837 .whitePoint = {
838 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
839 },
840 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
841 .minLuminance = hdrStaticInfo->mastering.minLuminance,
842 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800843 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800844 hdr.smpte2086 = smpte2086_meta;
845 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700846 // If the content light level fields are 0, do not use them, it
847 // indicates the value may not be present in the stream.
848 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
849 struct android_cta861_3_metadata cta861_meta = {
850 .maxContentLightLevel = hdrStaticInfo->maxCll,
851 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
852 };
853 hdr.validTypes |= HdrMetadata::CTA861_3;
854 hdr.cta8613 = cta861_meta;
855 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800856 }
857 if (hdr10PlusInfo) {
858 hdr.validTypes |= HdrMetadata::HDR10PLUS;
859 hdr.hdr10plus.assign(
860 hdr10PlusInfo->m.value,
861 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
862 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800863 qbi.setHdrMetadata(hdr);
864 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800865 // we don't have dirty regions
866 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800867 android::IGraphicBufferProducer::QueueBufferOutput qbo;
868 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
869 if (result != OK) {
870 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800871 if (result == NO_INIT) {
872 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
873 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800874 return result;
875 }
876 ALOGV("[%s] queue buffer successful", mName);
877
878 int64_t mediaTimeUs = 0;
879 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
880 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
881
882 return OK;
883}
884
885status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
886 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
887 bool released = false;
888 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700889 Mutexed<Input>::Locked input(mInput);
890 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800891 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800892 }
893 }
894 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700895 Mutexed<Output>::Locked output(mOutput);
896 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800897 released = true;
898 }
899 }
900 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800901 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800902 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800903 } else {
904 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
905 }
906 return OK;
907}
908
909void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
910 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700911 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800912
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700913 if (!input->buffers->isArrayMode()) {
914 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800915 }
916
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700917 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800918}
919
920void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
921 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700922 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800923
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700924 if (!output->buffers->isArrayMode()) {
925 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800926 }
927
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700928 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800929}
930
931status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800932 const sp<AMessage> &inputFormat,
933 const sp<AMessage> &outputFormat,
934 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800935 C2StreamBufferTypeSetting::input iStreamFormat(0u);
936 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -0800937 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800938 C2PortReorderBufferDepthTuning::output reorderDepth;
939 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800940 C2PortActualDelayTuning::input inputDelay(0);
941 C2PortActualDelayTuning::output outputDelay(0);
942 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -0700943 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -0800944
Pawin Vongmasa36653902018-11-15 00:10:25 -0800945 c2_status_t err = mComponent->query(
946 {
947 &iStreamFormat,
948 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -0800949 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800950 &reorderDepth,
951 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800952 &inputDelay,
953 &pipelineDelay,
954 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -0700955 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800956 },
957 {},
958 C2_DONT_BLOCK,
959 nullptr);
960 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -0800961 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800962 return UNKNOWN_ERROR;
963 }
964 } else if (err != C2_OK) {
965 return UNKNOWN_ERROR;
966 }
967
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800968 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
969 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
970 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
971
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700972 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
973 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800974
Pawin Vongmasa36653902018-11-15 00:10:25 -0800975 // TODO: get this from input format
976 bool secure = mComponent->getName().find(".secure") != std::string::npos;
977
Sungtak Lee04b30352020-07-27 13:57:25 -0700978 // secure mode is a static parameter (shall not change in the executing state)
979 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
980
Pawin Vongmasa36653902018-11-15 00:10:25 -0800981 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +0800982 int poolMask = GetCodec2PoolMask();
983 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800984
985 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800986 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -0800987 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -0700988 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
989 API_REFLECTION |
990 API_VALUES |
991 API_CURRENT_VALUES |
992 API_DEPENDENCY |
993 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -0800994 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
995 C2StreamSampleRateInfo::input sampleRate(0u);
996 C2StreamChannelCountInfo::input channelCount(0u);
997 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800998 std::shared_ptr<C2BlockPool> pool;
999 {
1000 Mutexed<BlockPools>::Locked pools(mBlockPools);
1001
1002 // set default allocator ID.
1003 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001004 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001005
1006 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1007 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1008 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001009 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001010 std::vector<C2Param *> stackParams({&featuresSetting});
1011 if (audioEncoder) {
1012 stackParams.push_back(&encoderFrameSize);
1013 stackParams.push_back(&sampleRate);
1014 stackParams.push_back(&channelCount);
1015 stackParams.push_back(&pcmEncoding);
1016 } else {
1017 encoderFrameSize.invalidate();
1018 sampleRate.invalidate();
1019 channelCount.invalidate();
1020 pcmEncoding.invalidate();
1021 }
1022 err = mComponent->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001023 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1024 C2_DONT_BLOCK,
1025 &params);
1026 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1027 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1028 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001029 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001030 C2PortAllocatorsTuning::input *inputAllocators =
1031 C2PortAllocatorsTuning::input::From(params[0].get());
1032 if (inputAllocators && inputAllocators->flexCount() > 0) {
1033 std::shared_ptr<C2Allocator> allocator;
1034 // verify allocator IDs and resolve default allocator
1035 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1036 if (allocator) {
1037 pools->inputAllocatorId = allocator->getId();
1038 } else {
1039 ALOGD("[%s] component requested invalid input allocator ID %u",
1040 mName, inputAllocators->m.values[0]);
1041 }
1042 }
1043 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001044 if (featuresSetting) {
1045 apiFeatures = featuresSetting.value;
1046 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001047
1048 // TODO: use C2Component wrapper to associate this pool with ourselves
1049 if ((poolMask >> pools->inputAllocatorId) & 1) {
1050 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1051 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1052 mName, pools->inputAllocatorId,
1053 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1054 asString(err), err);
1055 } else {
1056 err = C2_NOT_FOUND;
1057 }
1058 if (err != C2_OK) {
1059 C2BlockPool::local_id_t inputPoolId =
1060 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1061 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1062 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1063 mName, (unsigned long long)inputPoolId,
1064 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1065 asString(err), err);
1066 if (err != C2_OK) {
1067 return NO_MEMORY;
1068 }
1069 }
1070 pools->inputPool = pool;
1071 }
1072
Wonsik Kim51051262018-11-28 13:59:05 -08001073 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001074 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001075 input->inputDelay = inputDelayValue;
1076 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001077 input->numSlots = numInputSlots;
1078 input->extraBuffers.flush();
1079 input->numExtraSlots = 0u;
Wonsik Kime1104ca2020-11-24 15:01:33 -08001080 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1081 input->frameReassembler.init(
1082 pool,
1083 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1084 encoderFrameSize.value,
1085 sampleRate.value,
1086 channelCount.value,
1087 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1088 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001089 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1090 // For encrypted content, framework decrypts source buffer (ashmem) into
1091 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001092 if (!buffersBoundToCodec
1093 && !input->frameReassembler
1094 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001095 input->buffers.reset(new SlotInputBuffers(mName));
1096 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001097 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001098 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001099 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001100 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001101 // This is to ensure buffers do not get released prematurely.
1102 // TODO: handle this without going into array mode
1103 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001104 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001105 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001106 }
1107 } else {
1108 if (hasCryptoOrDescrambler()) {
1109 int32_t capacity = kLinearBufferSize;
1110 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1111 if ((size_t)capacity > kMaxLinearBufferSize) {
1112 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1113 capacity = kMaxLinearBufferSize;
1114 }
1115 if (mDealer == nullptr) {
1116 mDealer = new MemoryDealer(
1117 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001118 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001119 "EncryptedLinearInputBuffers");
1120 mDecryptDestination = mDealer->allocate((size_t)capacity);
1121 }
1122 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001123 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1124 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001125 } else {
1126 mHeapSeqNum = -1;
1127 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001128 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001129 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001130 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001131 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001132 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001133 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001134 }
1135 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001136 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001137
1138 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001139 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001140 } else {
1141 // TODO: error
1142 }
Wonsik Kim51051262018-11-28 13:59:05 -08001143
1144 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001145 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001146 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001147 }
1148
1149 if (outputFormat != nullptr) {
1150 sp<IGraphicBufferProducer> outputSurface;
1151 uint32_t outputGeneration;
1152 {
1153 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001154 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001155 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001156 outputSurface = output->surface ?
1157 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001158 if (outputSurface) {
1159 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1160 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001161 outputGeneration = output->generation;
1162 }
1163
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001164 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001165 C2BlockPool::local_id_t outputPoolId_;
1166
1167 {
1168 Mutexed<BlockPools>::Locked pools(mBlockPools);
1169
1170 // set default allocator ID.
1171 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001172 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001173
1174 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1175 // unsuccessful.
1176 std::vector<std::unique_ptr<C2Param>> params;
1177 err = mComponent->query({ },
1178 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1179 C2_DONT_BLOCK,
1180 &params);
1181 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1182 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1183 mName, params.size(), asString(err), err);
1184 } else if (err == C2_OK && params.size() == 1) {
1185 C2PortAllocatorsTuning::output *outputAllocators =
1186 C2PortAllocatorsTuning::output::From(params[0].get());
1187 if (outputAllocators && outputAllocators->flexCount() > 0) {
1188 std::shared_ptr<C2Allocator> allocator;
1189 // verify allocator IDs and resolve default allocator
1190 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1191 if (allocator) {
1192 pools->outputAllocatorId = allocator->getId();
1193 } else {
1194 ALOGD("[%s] component requested invalid output allocator ID %u",
1195 mName, outputAllocators->m.values[0]);
1196 }
1197 }
1198 }
1199
1200 // use bufferqueue if outputting to a surface.
1201 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1202 // if unsuccessful.
1203 if (outputSurface) {
1204 params.clear();
1205 err = mComponent->query({ },
1206 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1207 C2_DONT_BLOCK,
1208 &params);
1209 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1210 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1211 mName, params.size(), asString(err), err);
1212 } else if (err == C2_OK && params.size() == 1) {
1213 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1214 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1215 if (surfaceAllocator) {
1216 std::shared_ptr<C2Allocator> allocator;
1217 // verify allocator IDs and resolve default allocator
1218 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1219 if (allocator) {
1220 pools->outputAllocatorId = allocator->getId();
1221 } else {
1222 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1223 mName, surfaceAllocator->value);
1224 err = C2_BAD_VALUE;
1225 }
1226 }
1227 }
1228 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1229 && err != C2_OK
1230 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1231 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1232 }
1233 }
1234
1235 if ((poolMask >> pools->outputAllocatorId) & 1) {
1236 err = mComponent->createBlockPool(
1237 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1238 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1239 mName, pools->outputAllocatorId,
1240 (unsigned long long)pools->outputPoolId,
1241 asString(err));
1242 } else {
1243 err = C2_NOT_FOUND;
1244 }
1245 if (err != C2_OK) {
1246 // use basic pool instead
1247 pools->outputPoolId =
1248 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1249 }
1250
1251 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1252 // component.
1253 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1254 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1255
1256 std::vector<std::unique_ptr<C2SettingResult>> failures;
1257 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1258 ALOGD("[%s] Configured output block pool ids %llu => %s",
1259 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1260 outputPoolId_ = pools->outputPoolId;
1261 }
1262
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001263 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001264 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001265 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001266 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001267 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001268 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001269 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001270 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001271 }
1272 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001273 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001274 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001275 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001276
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001277 output->buffers->clearStash();
1278 if (reorderDepth) {
1279 output->buffers->setReorderDepth(reorderDepth.value);
1280 }
1281 if (reorderKey) {
1282 output->buffers->setReorderKey(reorderKey.value);
1283 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001284
1285 // Try to set output surface to created block pool if given.
1286 if (outputSurface) {
1287 mComponent->setOutputSurface(
1288 outputPoolId_,
1289 outputSurface,
1290 outputGeneration);
1291 }
1292
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001293 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001294 if (buffersBoundToCodec) {
1295 // WORKAROUND: if we're using early CSD workaround we convert to
1296 // array mode, to appease apps assuming the output
1297 // buffers to be of the same size.
1298 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1299 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001300
1301 int32_t channelCount;
1302 int32_t sampleRate;
1303 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1304 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1305 int32_t delay = 0;
1306 int32_t padding = 0;;
1307 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1308 delay = 0;
1309 }
1310 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1311 padding = 0;
1312 }
1313 if (delay || padding) {
1314 // We need write access to the buffers, and we're already in
1315 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001316 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001317 }
1318 }
1319 }
1320 }
1321
1322 // Set up pipeline control. This has to be done after mInputBuffers and
1323 // mOutputBuffers are initialized to make sure that lingering callbacks
1324 // about buffers from the previous generation do not interfere with the
1325 // newly initialized pipeline capacity.
1326
Wonsik Kimab34ed62019-01-31 15:28:46 -08001327 {
1328 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001329 watcher->inputDelay(inputDelayValue)
1330 .pipelineDelay(pipelineDelayValue)
1331 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001332 .smoothnessFactor(kSmoothnessFactor);
1333 watcher->flush();
1334 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001335
1336 mInputMetEos = false;
1337 mSync.start();
1338 return OK;
1339}
1340
1341status_t CCodecBufferChannel::requestInitialInputBuffers() {
1342 if (mInputSurface) {
1343 return OK;
1344 }
1345
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001346 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001347 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1348 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1349 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001350 return UNKNOWN_ERROR;
1351 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001352 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001353
1354 struct ClientInputBuffer {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001355 size_t index;
1356 sp<MediaCodecBuffer> buffer;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001357 size_t capacity;
1358 };
1359 std::list<ClientInputBuffer> clientInputBuffers;
1360
1361 {
1362 Mutexed<Input>::Locked input(mInput);
1363 while (clientInputBuffers.size() < numInputSlots) {
1364 ClientInputBuffer clientInputBuffer;
1365 if (!input->buffers->requestNewBuffer(&clientInputBuffer.index,
1366 &clientInputBuffer.buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001367 break;
1368 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001369 clientInputBuffer.capacity = clientInputBuffer.buffer->capacity();
1370 clientInputBuffers.emplace_back(std::move(clientInputBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001371 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001372 }
1373 if (clientInputBuffers.empty()) {
1374 ALOGW("[%s] start: cannot allocate memory at all", mName);
1375 return NO_MEMORY;
1376 } else if (clientInputBuffers.size() < numInputSlots) {
1377 ALOGD("[%s] start: cannot allocate memory for all slots, "
1378 "only %zu buffers allocated",
1379 mName, clientInputBuffers.size());
1380 } else {
1381 ALOGV("[%s] %zu initial input buffers available",
1382 mName, clientInputBuffers.size());
1383 }
1384 // Sort input buffers by their capacities in increasing order.
1385 clientInputBuffers.sort(
1386 [](const ClientInputBuffer& a, const ClientInputBuffer& b) {
1387 return a.capacity < b.capacity;
1388 });
1389
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001390 std::list<std::unique_ptr<C2Work>> flushedConfigs;
1391 mFlushedConfigs.lock()->swap(flushedConfigs);
1392 if (!flushedConfigs.empty()) {
1393 err = mComponent->queue(&flushedConfigs);
1394 if (err != C2_OK) {
1395 ALOGW("[%s] Error while queueing a flushed config", mName);
1396 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001397 }
1398 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001399 if (oStreamFormat.value == C2BufferData::LINEAR &&
1400 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
1401 sp<MediaCodecBuffer> buffer = clientInputBuffers.front().buffer;
1402 // WORKAROUND: Some apps expect CSD available without queueing
1403 // any input. Queue an empty buffer to get the CSD.
1404 buffer->setRange(0, 0);
1405 buffer->meta()->clear();
1406 buffer->meta()->setInt64("timeUs", 0);
1407 if (queueInputBufferInternal(buffer) != OK) {
1408 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1409 mName);
1410 return UNKNOWN_ERROR;
1411 }
1412 clientInputBuffers.pop_front();
1413 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001414
1415 for (const ClientInputBuffer& clientInputBuffer: clientInputBuffers) {
1416 mCallback->onInputBufferAvailable(
1417 clientInputBuffer.index,
1418 clientInputBuffer.buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001419 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001420
Pawin Vongmasa36653902018-11-15 00:10:25 -08001421 return OK;
1422}
1423
1424void CCodecBufferChannel::stop() {
1425 mSync.stop();
1426 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1427 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001428 mInputSurface.reset();
1429 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001430 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001431}
1432
Wonsik Kim936a89c2020-05-08 16:07:50 -07001433void CCodecBufferChannel::reset() {
1434 stop();
1435 {
1436 Mutexed<Input>::Locked input(mInput);
1437 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001438 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001439 }
1440 {
1441 Mutexed<Output>::Locked output(mOutput);
1442 output->buffers.reset();
1443 }
1444}
1445
1446void CCodecBufferChannel::release() {
1447 mComponent.reset();
1448 mInputAllocator.reset();
1449 mOutputSurface.lock()->surface.clear();
1450 {
1451 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1452 blockPools->inputPool.reset();
1453 blockPools->outputPoolIntf.reset();
1454 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001455 setCrypto(nullptr);
1456 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001457}
1458
1459
Pawin Vongmasa36653902018-11-15 00:10:25 -08001460void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1461 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001462 std::list<std::unique_ptr<C2Work>> configs;
1463 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1464 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1465 continue;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001466 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001467 if (work->input.buffers.empty()
1468 || work->input.buffers.front() == nullptr
1469 || work->input.buffers.front()->data().linearBlocks().empty()) {
1470 ALOGD("[%s] no linear codec config data found", mName);
1471 continue;
1472 }
1473 std::unique_ptr<C2Work> copy(new C2Work);
1474 copy->input.flags = C2FrameData::flags_t(work->input.flags | C2FrameData::FLAG_DROP_FRAME);
1475 copy->input.ordinal = work->input.ordinal;
1476 copy->input.buffers.insert(
1477 copy->input.buffers.begin(),
1478 work->input.buffers.begin(),
1479 work->input.buffers.end());
1480 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
1481 copy->input.configUpdate.push_back(C2Param::Copy(*param));
1482 }
1483 copy->input.infoBuffers.insert(
1484 copy->input.infoBuffers.begin(),
1485 work->input.infoBuffers.begin(),
1486 work->input.infoBuffers.end());
1487 copy->worklets.emplace_back(new C2Worklet);
1488 configs.push_back(std::move(copy));
1489 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001490 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08001491 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001492 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001493 Mutexed<Input>::Locked input(mInput);
1494 input->buffers->flush();
1495 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001496 }
1497 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001498 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001499 if (output->buffers) {
1500 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001501 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001502 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001503 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001504 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001505}
1506
1507void CCodecBufferChannel::onWorkDone(
1508 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001509 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001510 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001511 feedInputBufferIfAvailable();
1512 }
1513}
1514
1515void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001516 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001517 if (mInputSurface) {
1518 return;
1519 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001520 std::shared_ptr<C2Buffer> buffer =
1521 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001522 bool newInputSlotAvailable;
1523 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001524 Mutexed<Input>::Locked input(mInput);
1525 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1526 if (!newInputSlotAvailable) {
1527 (void)input->extraBuffers.expireComponentBuffer(buffer);
1528 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001529 }
1530 if (newInputSlotAvailable) {
1531 feedInputBufferIfAvailable();
1532 }
1533}
1534
1535bool CCodecBufferChannel::handleWork(
1536 std::unique_ptr<C2Work> work,
1537 const sp<AMessage> &outputFormat,
1538 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001539 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001540 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001541 if (!output->buffers) {
1542 return false;
1543 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001544 }
1545
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001546 // Whether the output buffer should be reported to the client or not.
1547 bool notifyClient = false;
1548
1549 if (work->result == C2_OK){
1550 notifyClient = true;
1551 } else if (work->result == C2_NOT_FOUND) {
1552 ALOGD("[%s] flushed work; ignored.", mName);
1553 } else {
1554 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1555 // the config update.
1556 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1557 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1558 return false;
1559 }
1560
1561 if ((work->input.ordinal.frameIndex -
1562 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001563 // Discard frames from previous generation.
1564 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001565 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001566 }
1567
Wonsik Kim524b0582019-03-12 11:28:57 -07001568 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001569 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001570 || !(work->worklets.front()->output.flags &
1571 C2FrameData::FLAG_INCOMPLETE))) {
1572 mPipelineWatcher.lock()->onWorkDone(
1573 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001574 }
1575
1576 // NOTE: MediaCodec usage supposedly have only one worklet
1577 if (work->worklets.size() != 1u) {
1578 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1579 mName, work->worklets.size());
1580 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1581 return false;
1582 }
1583
1584 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1585
1586 std::shared_ptr<C2Buffer> buffer;
1587 // NOTE: MediaCodec usage supposedly have only one output stream.
1588 if (worklet->output.buffers.size() > 1u) {
1589 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1590 mName, worklet->output.buffers.size());
1591 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1592 return false;
1593 } else if (worklet->output.buffers.size() == 1u) {
1594 buffer = worklet->output.buffers[0];
1595 if (!buffer) {
1596 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1597 }
1598 }
1599
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001600 std::optional<uint32_t> newInputDelay, newPipelineDelay;
Wonsik Kim315e40a2020-09-09 14:11:50 -07001601 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001602 while (!worklet->output.configUpdate.empty()) {
1603 std::unique_ptr<C2Param> param;
1604 worklet->output.configUpdate.back().swap(param);
1605 worklet->output.configUpdate.pop_back();
1606 switch (param->coreIndex().coreIndex()) {
1607 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1608 C2PortReorderBufferDepthTuning::output reorderDepth;
1609 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001610 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1611 mName, reorderDepth.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001612 mOutput.lock()->buffers->setReorderDepth(reorderDepth.value);
1613 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001614 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001615 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1616 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001617 }
1618 break;
1619 }
1620 case C2PortReorderKeySetting::CORE_INDEX: {
1621 C2PortReorderKeySetting::output reorderKey;
1622 if (reorderKey.updateFrom(*param)) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001623 mOutput.lock()->buffers->setReorderKey(reorderKey.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001624 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1625 mName, reorderKey.value);
1626 } else {
1627 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1628 }
1629 break;
1630 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001631 case C2PortActualDelayTuning::CORE_INDEX: {
1632 if (param->isGlobal()) {
1633 C2ActualPipelineDelayTuning pipelineDelay;
1634 if (pipelineDelay.updateFrom(*param)) {
1635 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1636 mName, pipelineDelay.value);
1637 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001638 (void)mPipelineWatcher.lock()->pipelineDelay(
1639 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001640 }
1641 }
1642 if (param->forInput()) {
1643 C2PortActualDelayTuning::input inputDelay;
1644 if (inputDelay.updateFrom(*param)) {
1645 ALOGV("[%s] onWorkDone: updating input delay %u",
1646 mName, inputDelay.value);
1647 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001648 (void)mPipelineWatcher.lock()->inputDelay(
1649 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001650 }
1651 }
1652 if (param->forOutput()) {
1653 C2PortActualDelayTuning::output outputDelay;
1654 if (outputDelay.updateFrom(*param)) {
1655 ALOGV("[%s] onWorkDone: updating output delay %u",
1656 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07001657 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
1658 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001659
1660 bool outputBuffersChanged = false;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001661 size_t numOutputSlots = 0;
1662 {
1663 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001664 if (!output->buffers) {
1665 return false;
1666 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001667 output->outputDelay = outputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001668 numOutputSlots = outputDelay.value +
1669 kSmoothnessFactor;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001670 if (output->numSlots < numOutputSlots) {
1671 output->numSlots = numOutputSlots;
1672 if (output->buffers->isArrayMode()) {
1673 OutputBuffersArray *array =
1674 (OutputBuffersArray *)output->buffers.get();
1675 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1676 mName, numOutputSlots);
1677 array->grow(numOutputSlots);
1678 outputBuffersChanged = true;
1679 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001680 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001681 numOutputSlots = output->numSlots;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001682 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001683
1684 if (outputBuffersChanged) {
1685 mCCodecCallback->onOutputBuffersChanged();
1686 }
1687 }
1688 }
1689 break;
1690 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001691 default:
1692 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1693 mName, param->index());
1694 break;
1695 }
1696 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001697 if (newInputDelay || newPipelineDelay) {
1698 Mutexed<Input>::Locked input(mInput);
1699 size_t newNumSlots =
1700 newInputDelay.value_or(input->inputDelay) +
1701 newPipelineDelay.value_or(input->pipelineDelay) +
1702 kSmoothnessFactor;
1703 if (input->buffers->isArrayMode()) {
1704 if (input->numSlots >= newNumSlots) {
1705 input->numExtraSlots = 0;
1706 } else {
1707 input->numExtraSlots = newNumSlots - input->numSlots;
1708 }
1709 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1710 mName, input->numExtraSlots);
1711 } else {
1712 input->numSlots = newNumSlots;
1713 }
1714 }
Wonsik Kim315e40a2020-09-09 14:11:50 -07001715 if (needMaxDequeueBufferCountUpdate) {
1716 size_t numOutputSlots = 0;
1717 uint32_t reorderDepth = 0;
1718 {
1719 Mutexed<Output>::Locked output(mOutput);
1720 numOutputSlots = output->numSlots;
1721 reorderDepth = output->buffers->getReorderDepth();
1722 }
1723 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1724 output->maxDequeueBuffers = numOutputSlots + reorderDepth + kRenderingDepth;
1725 if (output->surface) {
1726 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1727 }
1728 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001729
Pawin Vongmasa36653902018-11-15 00:10:25 -08001730 int32_t flags = 0;
1731 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1732 flags |= MediaCodec::BUFFER_FLAG_EOS;
1733 ALOGV("[%s] onWorkDone: output EOS", mName);
1734 }
1735
Pawin Vongmasa36653902018-11-15 00:10:25 -08001736 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1737 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1738 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1739 // shall correspond to the client input timesamp (in customOrdinal). By using the
1740 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1741 // produces multiple output.
1742 c2_cntr64_t timestamp =
1743 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1744 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001745 if (mInputSurface != nullptr) {
1746 // When using input surface we need to restore the original input timestamp.
1747 timestamp = work->input.ordinal.customOrdinal;
1748 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001749 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1750 mName,
1751 work->input.ordinal.customOrdinal.peekll(),
1752 work->input.ordinal.timestamp.peekll(),
1753 worklet->output.ordinal.timestamp.peekll(),
1754 timestamp.peekll());
1755
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001756 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001757 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001758 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001759 if (output->buffers && outputFormat) {
1760 output->buffers->updateSkipCutBuffer(outputFormat);
1761 output->buffers->setFormat(outputFormat);
1762 }
1763 if (!notifyClient) {
1764 return false;
1765 }
1766 size_t index;
1767 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07001768 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001769 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1770 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1771 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1772
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001773 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001774 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001775 } else {
1776 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001777 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001778 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001779 return false;
1780 }
1781 }
1782
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001783 if (notifyClient && !buffer && !flags) {
Wonsik Kim35bf5732020-05-14 17:40:29 +00001784 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001785 mName, work->input.ordinal.frameIndex.peekull());
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001786 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001787 }
1788
1789 if (buffer) {
1790 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1791 // TODO: properly translate these to metadata
1792 switch (info->coreIndex().coreIndex()) {
1793 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001794 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001795 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1796 }
1797 break;
1798 default:
1799 break;
1800 }
1801 }
1802 }
1803
1804 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001805 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07001806 if (!output->buffers) {
1807 return false;
1808 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001809 output->buffers->pushToStash(
1810 buffer,
1811 notifyClient,
1812 timestamp.peek(),
1813 flags,
1814 outputFormat,
1815 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001816 }
1817 sendOutputBuffers();
1818 return true;
1819}
1820
1821void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001822 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001823 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001824 sp<MediaCodecBuffer> outBuffer;
1825 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001826
1827 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001828 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001829 if (!output->buffers) {
1830 return;
1831 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001832 action = output->buffers->popFromStashAndRegister(
1833 &c2Buffer, &index, &outBuffer);
1834 switch (action) {
1835 case OutputBuffers::SKIP:
1836 return;
1837 case OutputBuffers::DISCARD:
1838 break;
1839 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00001840 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001841 mCallback->onOutputBufferAvailable(index, outBuffer);
1842 break;
1843 case OutputBuffers::REALLOCATE:
1844 if (!output->buffers->isArrayMode()) {
1845 output->buffers =
1846 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001847 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001848 static_cast<OutputBuffersArray*>(output->buffers.get())->
1849 realloc(c2Buffer);
1850 output.unlock();
1851 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07001852 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001853 case OutputBuffers::RETRY:
1854 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
1855 mName);
1856 return;
1857 default:
1858 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
1859 "corrupted BufferAction value (%d) "
1860 "returned from popFromStashAndRegister.",
1861 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001862 return;
1863 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001864 }
1865}
1866
1867status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1868 static std::atomic_uint32_t surfaceGeneration{0};
1869 uint32_t generation = (getpid() << 10) |
1870 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1871 & ((1 << 10) - 1));
1872
1873 sp<IGraphicBufferProducer> producer;
1874 if (newSurface) {
1875 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001876 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Lee08515812019-06-05 11:16:32 -07001877 newSurface->setMaxDequeuedBufferCount(mOutputSurface.lock()->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001878 producer = newSurface->getIGraphicBufferProducer();
1879 producer->setGenerationNumber(generation);
1880 } else {
1881 ALOGE("[%s] setting output surface to null", mName);
1882 return INVALID_OPERATION;
1883 }
1884
1885 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1886 C2BlockPool::local_id_t outputPoolId;
1887 {
1888 Mutexed<BlockPools>::Locked pools(mBlockPools);
1889 outputPoolId = pools->outputPoolId;
1890 outputPoolIntf = pools->outputPoolIntf;
1891 }
1892
1893 if (outputPoolIntf) {
1894 if (mComponent->setOutputSurface(
1895 outputPoolId,
1896 producer,
1897 generation) != C2_OK) {
1898 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1899 return INVALID_OPERATION;
1900 }
1901 }
1902
1903 {
1904 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1905 output->surface = newSurface;
1906 output->generation = generation;
1907 }
1908
1909 return OK;
1910}
1911
Wonsik Kimab34ed62019-01-31 15:28:46 -08001912PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001913 // When client pushed EOS, we want all the work to be done quickly.
1914 // Otherwise, component may have stalled work due to input starvation up to
1915 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001916 size_t n = 0;
1917 if (!mInputMetEos) {
1918 size_t outputDelay = mOutput.lock()->outputDelay;
1919 Mutexed<Input>::Locked input(mInput);
1920 n = input->inputDelay + input->pipelineDelay + outputDelay;
1921 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001922 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001923}
1924
Pawin Vongmasa36653902018-11-15 00:10:25 -08001925void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1926 mMetaMode = mode;
1927}
1928
Wonsik Kim596187e2019-10-25 12:44:10 -07001929void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001930 if (mCrypto != nullptr) {
1931 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
1932 mCrypto->unsetHeap(entry.second);
1933 }
1934 mHeapSeqNumMap.clear();
1935 if (mHeapSeqNum >= 0) {
1936 mCrypto->unsetHeap(mHeapSeqNum);
1937 mHeapSeqNum = -1;
1938 }
1939 }
Wonsik Kim596187e2019-10-25 12:44:10 -07001940 mCrypto = crypto;
1941}
1942
1943void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
1944 mDescrambler = descrambler;
1945}
1946
Pawin Vongmasa36653902018-11-15 00:10:25 -08001947status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1948 // C2_OK is always translated to OK.
1949 if (c2s == C2_OK) {
1950 return OK;
1951 }
1952
1953 // Operation-dependent translation
1954 // TODO: Add as necessary
1955 switch (c2op) {
1956 case C2_OPERATION_Component_start:
1957 switch (c2s) {
1958 case C2_NO_MEMORY:
1959 return NO_MEMORY;
1960 default:
1961 return UNKNOWN_ERROR;
1962 }
1963 default:
1964 break;
1965 }
1966
1967 // Backup operation-agnostic translation
1968 switch (c2s) {
1969 case C2_BAD_INDEX:
1970 return BAD_INDEX;
1971 case C2_BAD_VALUE:
1972 return BAD_VALUE;
1973 case C2_BLOCKING:
1974 return WOULD_BLOCK;
1975 case C2_DUPLICATE:
1976 return ALREADY_EXISTS;
1977 case C2_NO_INIT:
1978 return NO_INIT;
1979 case C2_NO_MEMORY:
1980 return NO_MEMORY;
1981 case C2_NOT_FOUND:
1982 return NAME_NOT_FOUND;
1983 case C2_TIMED_OUT:
1984 return TIMED_OUT;
1985 case C2_BAD_STATE:
1986 case C2_CANCELED:
1987 case C2_CANNOT_DO:
1988 case C2_CORRUPTED:
1989 case C2_OMITTED:
1990 case C2_REFUSED:
1991 return UNKNOWN_ERROR;
1992 default:
1993 return -static_cast<status_t>(c2s);
1994 }
1995}
1996
1997} // namespace android