blob: 907aa39b15dd8b44ce6b1e47625a6c8baa3bc443 [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
21#include <numeric>
22
23#include <C2AllocatorGralloc.h>
24#include <C2PlatformSupport.h>
25#include <C2BlockInternal.h>
26#include <C2Config.h>
27#include <C2Debug.h>
28
29#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070030#include <android/hardware/drm/1.0/types.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080031#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080032#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080033#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070034#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080035#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070036#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080037#include <media/openmax/OMX_Core.h>
38#include <media/stagefright/foundation/ABuffer.h>
39#include <media/stagefright/foundation/ALookup.h>
40#include <media/stagefright/foundation/AMessage.h>
41#include <media/stagefright/foundation/AUtils.h>
42#include <media/stagefright/foundation/hexdump.h>
43#include <media/stagefright/MediaCodec.h>
44#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070045#include <media/stagefright/SkipCutBuffer.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080046#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070047#include <mediadrm/ICrypto.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080048#include <system/window.h>
49
50#include "CCodecBufferChannel.h"
51#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080052
53namespace android {
54
55using android::base::StringPrintf;
56using hardware::hidl_handle;
57using hardware::hidl_string;
58using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070059using hardware::fromHeap;
60using hardware::HidlMemory;
61
Pawin Vongmasa36653902018-11-15 00:10:25 -080062using namespace hardware::cas::V1_0;
63using namespace hardware::cas::native::V1_0;
64
65using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070066using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080067
Pawin Vongmasa36653902018-11-15 00:10:25 -080068namespace {
69
Wonsik Kim469c8342019-04-11 16:46:09 -070070constexpr size_t kSmoothnessFactor = 4;
71constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080072
Sungtak Leeab6f2f32019-02-15 14:43:51 -080073// This is for keeping IGBP's buffer dropping logic in legacy mode other
74// than making it non-blocking. Do not change this value.
75const static size_t kDequeueTimeoutNs = 0;
76
Pawin Vongmasa36653902018-11-15 00:10:25 -080077} // namespace
78
79CCodecBufferChannel::QueueGuard::QueueGuard(
80 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
81 Mutex::Autolock l(mSync.mGuardLock);
82 // At this point it's guaranteed that mSync is not under state transition,
83 // as we are holding its mutex.
84
85 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
86 if (count->value == -1) {
87 mRunning = false;
88 } else {
89 ++count->value;
90 mRunning = true;
91 }
92}
93
94CCodecBufferChannel::QueueGuard::~QueueGuard() {
95 if (mRunning) {
96 // We are not holding mGuardLock at this point so that QueueSync::stop() can
97 // keep holding the lock until mCount reaches zero.
98 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
99 --count->value;
100 count->cond.broadcast();
101 }
102}
103
104void CCodecBufferChannel::QueueSync::start() {
105 Mutex::Autolock l(mGuardLock);
106 // If stopped, it goes to running state; otherwise no-op.
107 Mutexed<Counter>::Locked count(mCount);
108 if (count->value == -1) {
109 count->value = 0;
110 }
111}
112
113void CCodecBufferChannel::QueueSync::stop() {
114 Mutex::Autolock l(mGuardLock);
115 Mutexed<Counter>::Locked count(mCount);
116 if (count->value == -1) {
117 // no-op
118 return;
119 }
120 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
121 // mCount can only decrement. In other words, threads that acquired the lock
122 // are allowed to finish execution but additional threads trying to acquire
123 // the lock at this point will block, and then get QueueGuard at STOPPED
124 // state.
125 while (count->value != 0) {
126 count.waitForCondition(count->cond);
127 }
128 count->value = -1;
129}
130
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700131// Input
132
133CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
134
Pawin Vongmasa36653902018-11-15 00:10:25 -0800135// CCodecBufferChannel
136
137CCodecBufferChannel::CCodecBufferChannel(
138 const std::shared_ptr<CCodecCallback> &callback)
139 : mHeapSeqNum(-1),
140 mCCodecCallback(callback),
141 mFrameIndex(0u),
142 mFirstValidFrameIndex(0u),
143 mMetaMode(MODE_NONE),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800144 mInputMetEos(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700145 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700146 {
147 Mutexed<Input>::Locked input(mInput);
148 input->buffers.reset(new DummyInputBuffers(""));
149 input->extraBuffers.flush();
150 input->inputDelay = 0u;
151 input->pipelineDelay = 0u;
152 input->numSlots = kSmoothnessFactor;
153 input->numExtraSlots = 0u;
154 }
155 {
156 Mutexed<Output>::Locked output(mOutput);
157 output->outputDelay = 0u;
158 output->numSlots = kSmoothnessFactor;
159 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800160}
161
162CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800163 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800164 mCrypto->unsetHeap(mHeapSeqNum);
165 }
166}
167
168void CCodecBufferChannel::setComponent(
169 const std::shared_ptr<Codec2Client::Component> &component) {
170 mComponent = component;
171 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
172 mName = mComponentName.c_str();
173}
174
175status_t CCodecBufferChannel::setInputSurface(
176 const std::shared_ptr<InputSurfaceWrapper> &surface) {
177 ALOGV("[%s] setInputSurface", mName);
178 mInputSurface = surface;
179 return mInputSurface->connect(mComponent);
180}
181
182status_t CCodecBufferChannel::signalEndOfInputStream() {
183 if (mInputSurface == nullptr) {
184 return INVALID_OPERATION;
185 }
186 return mInputSurface->signalEndOfInputStream();
187}
188
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700189status_t CCodecBufferChannel::queueInputBufferInternal(sp<MediaCodecBuffer> buffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800190 int64_t timeUs;
191 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
192
193 if (mInputMetEos) {
194 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
195 return OK;
196 }
197
198 int32_t flags = 0;
199 int32_t tmp = 0;
200 bool eos = false;
201 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
202 eos = true;
203 mInputMetEos = true;
204 ALOGV("[%s] input EOS", mName);
205 }
206 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
207 flags |= C2FrameData::FLAG_CODEC_CONFIG;
208 }
209 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
210 std::unique_ptr<C2Work> work(new C2Work);
211 work->input.ordinal.timestamp = timeUs;
212 work->input.ordinal.frameIndex = mFrameIndex++;
213 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
214 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
215 // Keep client timestamp in customOrdinal
216 work->input.ordinal.customOrdinal = timeUs;
217 work->input.buffers.clear();
218
Wonsik Kimab34ed62019-01-31 15:28:46 -0800219 uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
220 std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700221 sp<Codec2Buffer> copy;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800222
Pawin Vongmasa36653902018-11-15 00:10:25 -0800223 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700224 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800225 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700226 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800227 return -ENOENT;
228 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700229 // TODO: we want to delay copying buffers.
230 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
231 copy = input->buffers->cloneAndReleaseBuffer(buffer);
232 if (copy != nullptr) {
233 (void)input->extraBuffers.assignSlot(copy);
234 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
235 return UNKNOWN_ERROR;
236 }
237 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
238 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
239 mName, released ? "" : "not ");
240 buffer.clear();
241 } else {
242 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
243 "buffer starvation on component.", mName);
244 }
245 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800246 work->input.buffers.push_back(c2buffer);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800247 queuedBuffers.push_back(c2buffer);
248 } else if (eos) {
249 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800250 }
251 work->input.flags = (C2FrameData::flags_t)flags;
252 // TODO: fill info's
253
254 work->input.configUpdate = std::move(mParamsToBeSet);
255 work->worklets.clear();
256 work->worklets.emplace_back(new C2Worklet);
257
258 std::list<std::unique_ptr<C2Work>> items;
259 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800260 mPipelineWatcher.lock()->onWorkQueued(
261 queuedFrameIndex,
262 std::move(queuedBuffers),
263 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800264 c2_status_t err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800265 if (err != C2_OK) {
266 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
267 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800268
269 if (err == C2_OK && eos && buffer->size() > 0u) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800270 work.reset(new C2Work);
271 work->input.ordinal.timestamp = timeUs;
272 work->input.ordinal.frameIndex = mFrameIndex++;
273 // WORKAROUND: keep client timestamp in customOrdinal
274 work->input.ordinal.customOrdinal = timeUs;
275 work->input.buffers.clear();
276 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800277 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800278
Wonsik Kimab34ed62019-01-31 15:28:46 -0800279 queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
280 queuedBuffers.clear();
281
Pawin Vongmasa36653902018-11-15 00:10:25 -0800282 items.clear();
283 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800284
285 mPipelineWatcher.lock()->onWorkQueued(
286 queuedFrameIndex,
287 std::move(queuedBuffers),
288 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800289 err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800290 if (err != C2_OK) {
291 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
292 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800293 }
294 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700295 Mutexed<Input>::Locked input(mInput);
296 bool released = false;
297 if (buffer) {
298 released = input->buffers->releaseBuffer(buffer, nullptr, true);
299 } else if (copy) {
300 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
301 }
302 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
303 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800304 }
305
306 feedInputBufferIfAvailableInternal();
307 return err;
308}
309
310status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
311 QueueGuard guard(mSync);
312 if (!guard.isRunning()) {
313 ALOGD("[%s] setParameters is only supported in the running state.", mName);
314 return -ENOSYS;
315 }
316 mParamsToBeSet.insert(mParamsToBeSet.end(),
317 std::make_move_iterator(params.begin()),
318 std::make_move_iterator(params.end()));
319 params.clear();
320 return OK;
321}
322
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800323status_t CCodecBufferChannel::attachBuffer(
324 const std::shared_ptr<C2Buffer> &c2Buffer,
325 const sp<MediaCodecBuffer> &buffer) {
326 if (!buffer->copy(c2Buffer)) {
327 return -ENOSYS;
328 }
329 return OK;
330}
331
332void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
333 if (!mDecryptDestination || mDecryptDestination->size() < size) {
334 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
335 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
336 mCrypto->unsetHeap(mHeapSeqNum);
337 }
338 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
339 if (mCrypto) {
340 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
341 }
342 }
343}
344
345int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
346 CHECK(mCrypto);
347 auto it = mHeapSeqNumMap.find(memory);
348 int32_t heapSeqNum = -1;
349 if (it == mHeapSeqNumMap.end()) {
350 heapSeqNum = mCrypto->setHeap(memory);
351 mHeapSeqNumMap.emplace(memory, heapSeqNum);
352 } else {
353 heapSeqNum = it->second;
354 }
355 return heapSeqNum;
356}
357
358status_t CCodecBufferChannel::attachEncryptedBuffer(
359 const sp<hardware::HidlMemory> &memory,
360 bool secure,
361 const uint8_t *key,
362 const uint8_t *iv,
363 CryptoPlugin::Mode mode,
364 CryptoPlugin::Pattern pattern,
365 size_t offset,
366 const CryptoPlugin::SubSample *subSamples,
367 size_t numSubSamples,
368 const sp<MediaCodecBuffer> &buffer) {
369 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
370 static const C2MemoryUsage kDefaultReadWriteUsage{
371 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
372
373 size_t size = 0;
374 for (size_t i = 0; i < numSubSamples; ++i) {
375 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
376 }
377 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
378 std::shared_ptr<C2LinearBlock> block;
379 c2_status_t err = pool->fetchLinearBlock(
380 size,
381 secure ? kSecureUsage : kDefaultReadWriteUsage,
382 &block);
383 if (err != C2_OK) {
384 return NO_MEMORY;
385 }
386 if (!secure) {
387 ensureDecryptDestination(size);
388 }
389 ssize_t result = -1;
390 ssize_t codecDataOffset = 0;
391 if (mCrypto) {
392 AString errorDetailMsg;
393 int32_t heapSeqNum = getHeapSeqNum(memory);
394 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
395 hardware::drm::V1_0::DestinationBuffer dst;
396 if (secure) {
397 dst.type = DrmBufferType::NATIVE_HANDLE;
398 dst.secureMemory = hardware::hidl_handle(block->handle());
399 } else {
400 dst.type = DrmBufferType::SHARED_MEMORY;
401 IMemoryToSharedBuffer(
402 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
403 }
404 result = mCrypto->decrypt(
405 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
406 dst, &errorDetailMsg);
407 if (result < 0) {
408 return result;
409 }
410 if (dst.type == DrmBufferType::SHARED_MEMORY) {
411 C2WriteView view = block->map().get();
412 if (view.error() != C2_OK) {
413 return false;
414 }
415 if (view.size() < result) {
416 return false;
417 }
418 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
419 }
420 } else {
421 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
422 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
423 hidl_vec<SubSample> hidlSubSamples;
424 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
425
426 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
427 hardware::cas::native::V1_0::DestinationBuffer dst;
428 if (secure) {
429 dst.type = BufferType::NATIVE_HANDLE;
430 dst.secureMemory = hardware::hidl_handle(block->handle());
431 } else {
432 dst.type = BufferType::SHARED_MEMORY;
433 dst.nonsecureMemory = src;
434 }
435
436 CasStatus status = CasStatus::OK;
437 hidl_string detailedError;
438 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
439
440 if (key != nullptr) {
441 sctrl = (ScramblingControl)key[0];
442 // Adjust for the PES offset
443 codecDataOffset = key[2] | (key[3] << 8);
444 }
445
446 auto returnVoid = mDescrambler->descramble(
447 sctrl,
448 hidlSubSamples,
449 src,
450 0,
451 dst,
452 0,
453 [&status, &result, &detailedError] (
454 CasStatus _status, uint32_t _bytesWritten,
455 const hidl_string& _detailedError) {
456 status = _status;
457 result = (ssize_t)_bytesWritten;
458 detailedError = _detailedError;
459 });
460
461 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
462 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
463 mName, returnVoid.description().c_str(), status, result);
464 return UNKNOWN_ERROR;
465 }
466
467 if (result < codecDataOffset) {
468 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
469 return BAD_VALUE;
470 }
471 }
472 if (!secure) {
473 C2WriteView view = block->map().get();
474 if (view.error() != C2_OK) {
475 return UNKNOWN_ERROR;
476 }
477 if (view.size() < result) {
478 return UNKNOWN_ERROR;
479 }
480 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
481 }
482 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
483 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
484 if (!buffer->copy(c2Buffer)) {
485 return -ENOSYS;
486 }
487 return OK;
488}
489
Pawin Vongmasa36653902018-11-15 00:10:25 -0800490status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
491 QueueGuard guard(mSync);
492 if (!guard.isRunning()) {
493 ALOGD("[%s] No more buffers should be queued at current state.", mName);
494 return -ENOSYS;
495 }
496 return queueInputBufferInternal(buffer);
497}
498
499status_t CCodecBufferChannel::queueSecureInputBuffer(
500 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
501 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
502 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
503 AString *errorDetailMsg) {
504 QueueGuard guard(mSync);
505 if (!guard.isRunning()) {
506 ALOGD("[%s] No more buffers should be queued at current state.", mName);
507 return -ENOSYS;
508 }
509
510 if (!hasCryptoOrDescrambler()) {
511 return -ENOSYS;
512 }
513 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
514
515 ssize_t result = -1;
516 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700517 if (numSubSamples == 1
518 && subSamples[0].mNumBytesOfClearData == 0
519 && subSamples[0].mNumBytesOfEncryptedData == 0) {
520 // We don't need to go through crypto or descrambler if the input is empty.
521 result = 0;
522 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700523 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800524 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700525 destination.type = DrmBufferType::NATIVE_HANDLE;
526 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800527 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700528 destination.type = DrmBufferType::SHARED_MEMORY;
529 IMemoryToSharedBuffer(
530 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800531 }
Robert Shih895fba92019-07-16 16:29:44 -0700532 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800533 encryptedBuffer->fillSourceBuffer(&source);
534 result = mCrypto->decrypt(
535 key, iv, mode, pattern, source, buffer->offset(),
536 subSamples, numSubSamples, destination, errorDetailMsg);
537 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700538 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800539 return result;
540 }
Robert Shih895fba92019-07-16 16:29:44 -0700541 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800542 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
543 }
544 } else {
545 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
546 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
547 hidl_vec<SubSample> hidlSubSamples;
548 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
549
550 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
551 encryptedBuffer->fillSourceBuffer(&srcBuffer);
552
553 DestinationBuffer dstBuffer;
554 if (secure) {
555 dstBuffer.type = BufferType::NATIVE_HANDLE;
556 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
557 } else {
558 dstBuffer.type = BufferType::SHARED_MEMORY;
559 dstBuffer.nonsecureMemory = srcBuffer;
560 }
561
562 CasStatus status = CasStatus::OK;
563 hidl_string detailedError;
564 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
565
566 if (key != nullptr) {
567 sctrl = (ScramblingControl)key[0];
568 // Adjust for the PES offset
569 codecDataOffset = key[2] | (key[3] << 8);
570 }
571
572 auto returnVoid = mDescrambler->descramble(
573 sctrl,
574 hidlSubSamples,
575 srcBuffer,
576 0,
577 dstBuffer,
578 0,
579 [&status, &result, &detailedError] (
580 CasStatus _status, uint32_t _bytesWritten,
581 const hidl_string& _detailedError) {
582 status = _status;
583 result = (ssize_t)_bytesWritten;
584 detailedError = _detailedError;
585 });
586
587 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
588 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
589 mName, returnVoid.description().c_str(), status, result);
590 return UNKNOWN_ERROR;
591 }
592
593 if (result < codecDataOffset) {
594 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
595 return BAD_VALUE;
596 }
597
598 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
599
600 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
601 encryptedBuffer->copyDecryptedContentFromMemory(result);
602 }
603 }
604
605 buffer->setRange(codecDataOffset, result - codecDataOffset);
606 return queueInputBufferInternal(buffer);
607}
608
609void CCodecBufferChannel::feedInputBufferIfAvailable() {
610 QueueGuard guard(mSync);
611 if (!guard.isRunning()) {
612 ALOGV("[%s] We're not running --- no input buffer reported", mName);
613 return;
614 }
615 feedInputBufferIfAvailableInternal();
616}
617
618void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800619 if (mInputMetEos ||
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700620 mOutput.lock()->buffers->hasPending() ||
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800621 mPipelineWatcher.lock()->pipelineFull()) {
622 return;
623 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700624 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -0700625 if (!output->buffers || output->buffers->numClientBuffers() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800626 return;
627 }
628 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700629 size_t numInputSlots = mInput.lock()->numSlots;
630 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800631 sp<MediaCodecBuffer> inBuffer;
632 size_t index;
633 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700634 Mutexed<Input>::Locked input(mInput);
635 if (input->buffers->numClientBuffers() >= input->numSlots) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800636 return;
637 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700638 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800639 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800640 break;
641 }
642 }
643 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
644 mCallback->onInputBufferAvailable(index, inBuffer);
645 }
646}
647
648status_t CCodecBufferChannel::renderOutputBuffer(
649 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800650 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800651 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800652 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800653 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700654 Mutexed<Output>::Locked output(mOutput);
655 if (output->buffers) {
656 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800657 }
658 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800659 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
660 // set to true.
661 sendOutputBuffers();
662 // input buffer feeding may have been gated by pending output buffers
663 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800664 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800665 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700666 std::call_once(mRenderWarningFlag, [this] {
667 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
668 "timestamp or render=true with non-video buffers. Apps should "
669 "call releaseOutputBuffer() with render=false for those.",
670 mName);
671 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800672 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800673 return INVALID_OPERATION;
674 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800675
676#if 0
677 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
678 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
679 for (const std::shared_ptr<const C2Info> &info : infoParams) {
680 AString res;
681 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
682 if (ix) res.append(", ");
683 res.append(*((int32_t*)info.get() + (ix / 4)));
684 }
685 ALOGV(" [%s]", res.c_str());
686 }
687#endif
688 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
689 std::static_pointer_cast<const C2StreamRotationInfo::output>(
690 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
691 bool flip = rotation && (rotation->flip & 1);
692 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
693 uint32_t transform = 0;
694 switch (quarters) {
695 case 0: // no rotation
696 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
697 break;
698 case 1: // 90 degrees counter-clockwise
699 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
700 : HAL_TRANSFORM_ROT_270;
701 break;
702 case 2: // 180 degrees
703 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
704 break;
705 case 3: // 90 degrees clockwise
706 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
707 : HAL_TRANSFORM_ROT_90;
708 break;
709 }
710
711 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
712 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
713 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
714 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
715 if (surfaceScaling) {
716 videoScalingMode = surfaceScaling->value;
717 }
718
719 // Use dataspace from format as it has the default aspects already applied
720 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
721 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
722
723 // HDR static info
724 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
725 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
726 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
727
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800728 // HDR10 plus info
729 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
730 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
731 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
732
Pawin Vongmasa36653902018-11-15 00:10:25 -0800733 {
734 Mutexed<OutputSurface>::Locked output(mOutputSurface);
735 if (output->surface == nullptr) {
736 ALOGI("[%s] cannot render buffer without surface", mName);
737 return OK;
738 }
739 }
740
741 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
742 if (blocks.size() != 1u) {
743 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
744 return UNKNOWN_ERROR;
745 }
746 const C2ConstGraphicBlock &block = blocks.front();
747
748 // TODO: revisit this after C2Fence implementation.
749 android::IGraphicBufferProducer::QueueBufferInput qbi(
750 timestampNs,
751 false, // droppable
752 dataSpace,
753 Rect(blocks.front().crop().left,
754 blocks.front().crop().top,
755 blocks.front().crop().right(),
756 blocks.front().crop().bottom()),
757 videoScalingMode,
758 transform,
759 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800760 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800761 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800762 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800763 // If mastering max and min luminance fields are 0, do not use them.
764 // It indicates the value may not be present in the stream.
765 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
766 hdrStaticInfo->mastering.minLuminance > 0.0f) {
767 struct android_smpte2086_metadata smpte2086_meta = {
768 .displayPrimaryRed = {
769 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
770 },
771 .displayPrimaryGreen = {
772 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
773 },
774 .displayPrimaryBlue = {
775 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
776 },
777 .whitePoint = {
778 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
779 },
780 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
781 .minLuminance = hdrStaticInfo->mastering.minLuminance,
782 };
783 hdr.validTypes = HdrMetadata::SMPTE2086;
784 hdr.smpte2086 = smpte2086_meta;
785 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700786 // If the content light level fields are 0, do not use them, it
787 // indicates the value may not be present in the stream.
788 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
789 struct android_cta861_3_metadata cta861_meta = {
790 .maxContentLightLevel = hdrStaticInfo->maxCll,
791 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
792 };
793 hdr.validTypes |= HdrMetadata::CTA861_3;
794 hdr.cta8613 = cta861_meta;
795 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800796 }
797 if (hdr10PlusInfo) {
798 hdr.validTypes |= HdrMetadata::HDR10PLUS;
799 hdr.hdr10plus.assign(
800 hdr10PlusInfo->m.value,
801 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
802 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800803 qbi.setHdrMetadata(hdr);
804 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800805 // we don't have dirty regions
806 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800807 android::IGraphicBufferProducer::QueueBufferOutput qbo;
808 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
809 if (result != OK) {
810 ALOGI("[%s] queueBuffer failed: %d", mName, result);
811 return result;
812 }
813 ALOGV("[%s] queue buffer successful", mName);
814
815 int64_t mediaTimeUs = 0;
816 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
817 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
818
819 return OK;
820}
821
822status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
823 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
824 bool released = false;
825 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700826 Mutexed<Input>::Locked input(mInput);
827 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800828 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800829 }
830 }
831 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700832 Mutexed<Output>::Locked output(mOutput);
833 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800834 released = true;
835 }
836 }
837 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800838 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800839 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800840 } else {
841 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
842 }
843 return OK;
844}
845
846void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
847 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700848 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800849
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700850 if (!input->buffers->isArrayMode()) {
851 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800852 }
853
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700854 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800855}
856
857void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
858 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700859 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800860
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700861 if (!output->buffers->isArrayMode()) {
862 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800863 }
864
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700865 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800866}
867
868status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800869 const sp<AMessage> &inputFormat,
870 const sp<AMessage> &outputFormat,
871 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800872 C2StreamBufferTypeSetting::input iStreamFormat(0u);
873 C2StreamBufferTypeSetting::output oStreamFormat(0u);
874 C2PortReorderBufferDepthTuning::output reorderDepth;
875 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800876 C2PortActualDelayTuning::input inputDelay(0);
877 C2PortActualDelayTuning::output outputDelay(0);
878 C2ActualPipelineDelayTuning pipelineDelay(0);
879
Pawin Vongmasa36653902018-11-15 00:10:25 -0800880 c2_status_t err = mComponent->query(
881 {
882 &iStreamFormat,
883 &oStreamFormat,
884 &reorderDepth,
885 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800886 &inputDelay,
887 &pipelineDelay,
888 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800889 },
890 {},
891 C2_DONT_BLOCK,
892 nullptr);
893 if (err == C2_BAD_INDEX) {
894 if (!iStreamFormat || !oStreamFormat) {
895 return UNKNOWN_ERROR;
896 }
897 } else if (err != C2_OK) {
898 return UNKNOWN_ERROR;
899 }
900
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800901 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
902 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
903 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
904
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700905 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
906 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800907
Pawin Vongmasa36653902018-11-15 00:10:25 -0800908 // TODO: get this from input format
909 bool secure = mComponent->getName().find(".secure") != std::string::npos;
910
911 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +0800912 int poolMask = GetCodec2PoolMask();
913 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800914
915 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800916 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800917 std::shared_ptr<C2BlockPool> pool;
918 {
919 Mutexed<BlockPools>::Locked pools(mBlockPools);
920
921 // set default allocator ID.
922 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +0800923 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800924
925 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
926 // from component, create the input block pool with given ID. Otherwise, use default IDs.
927 std::vector<std::unique_ptr<C2Param>> params;
928 err = mComponent->query({ },
929 { C2PortAllocatorsTuning::input::PARAM_TYPE },
930 C2_DONT_BLOCK,
931 &params);
932 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
933 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
934 mName, params.size(), asString(err), err);
935 } else if (err == C2_OK && params.size() == 1) {
936 C2PortAllocatorsTuning::input *inputAllocators =
937 C2PortAllocatorsTuning::input::From(params[0].get());
938 if (inputAllocators && inputAllocators->flexCount() > 0) {
939 std::shared_ptr<C2Allocator> allocator;
940 // verify allocator IDs and resolve default allocator
941 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
942 if (allocator) {
943 pools->inputAllocatorId = allocator->getId();
944 } else {
945 ALOGD("[%s] component requested invalid input allocator ID %u",
946 mName, inputAllocators->m.values[0]);
947 }
948 }
949 }
950
951 // TODO: use C2Component wrapper to associate this pool with ourselves
952 if ((poolMask >> pools->inputAllocatorId) & 1) {
953 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
954 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
955 mName, pools->inputAllocatorId,
956 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
957 asString(err), err);
958 } else {
959 err = C2_NOT_FOUND;
960 }
961 if (err != C2_OK) {
962 C2BlockPool::local_id_t inputPoolId =
963 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
964 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
965 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
966 mName, (unsigned long long)inputPoolId,
967 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
968 asString(err), err);
969 if (err != C2_OK) {
970 return NO_MEMORY;
971 }
972 }
973 pools->inputPool = pool;
974 }
975
Wonsik Kim51051262018-11-28 13:59:05 -0800976 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700977 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -0700978 input->inputDelay = inputDelayValue;
979 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700980 input->numSlots = numInputSlots;
981 input->extraBuffers.flush();
982 input->numExtraSlots = 0u;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800983 if (!buffersBoundToCodec) {
984 input->buffers.reset(new SlotInputBuffers(mName));
985 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800986 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700987 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800988 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700989 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -0700990 // This is to ensure buffers do not get released prematurely.
991 // TODO: handle this without going into array mode
992 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800993 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -0700994 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800995 }
996 } else {
997 if (hasCryptoOrDescrambler()) {
998 int32_t capacity = kLinearBufferSize;
999 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1000 if ((size_t)capacity > kMaxLinearBufferSize) {
1001 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1002 capacity = kMaxLinearBufferSize;
1003 }
1004 if (mDealer == nullptr) {
1005 mDealer = new MemoryDealer(
1006 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001007 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001008 "EncryptedLinearInputBuffers");
1009 mDecryptDestination = mDealer->allocate((size_t)capacity);
1010 }
1011 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001012 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1013 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001014 } else {
1015 mHeapSeqNum = -1;
1016 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001017 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001018 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001019 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001020 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001021 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001022 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001023 }
1024 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001025 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001026
1027 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001028 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001029 } else {
1030 // TODO: error
1031 }
Wonsik Kim51051262018-11-28 13:59:05 -08001032
1033 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001034 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001035 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001036 }
1037
1038 if (outputFormat != nullptr) {
1039 sp<IGraphicBufferProducer> outputSurface;
1040 uint32_t outputGeneration;
1041 {
1042 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001043 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001044 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001045 if (!secure) {
1046 output->maxDequeueBuffers += numInputSlots;
1047 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001048 outputSurface = output->surface ?
1049 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001050 if (outputSurface) {
1051 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1052 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001053 outputGeneration = output->generation;
1054 }
1055
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001056 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001057 C2BlockPool::local_id_t outputPoolId_;
1058
1059 {
1060 Mutexed<BlockPools>::Locked pools(mBlockPools);
1061
1062 // set default allocator ID.
1063 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001064 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001065
1066 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1067 // unsuccessful.
1068 std::vector<std::unique_ptr<C2Param>> params;
1069 err = mComponent->query({ },
1070 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1071 C2_DONT_BLOCK,
1072 &params);
1073 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1074 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1075 mName, params.size(), asString(err), err);
1076 } else if (err == C2_OK && params.size() == 1) {
1077 C2PortAllocatorsTuning::output *outputAllocators =
1078 C2PortAllocatorsTuning::output::From(params[0].get());
1079 if (outputAllocators && outputAllocators->flexCount() > 0) {
1080 std::shared_ptr<C2Allocator> allocator;
1081 // verify allocator IDs and resolve default allocator
1082 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1083 if (allocator) {
1084 pools->outputAllocatorId = allocator->getId();
1085 } else {
1086 ALOGD("[%s] component requested invalid output allocator ID %u",
1087 mName, outputAllocators->m.values[0]);
1088 }
1089 }
1090 }
1091
1092 // use bufferqueue if outputting to a surface.
1093 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1094 // if unsuccessful.
1095 if (outputSurface) {
1096 params.clear();
1097 err = mComponent->query({ },
1098 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1099 C2_DONT_BLOCK,
1100 &params);
1101 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1102 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1103 mName, params.size(), asString(err), err);
1104 } else if (err == C2_OK && params.size() == 1) {
1105 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1106 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1107 if (surfaceAllocator) {
1108 std::shared_ptr<C2Allocator> allocator;
1109 // verify allocator IDs and resolve default allocator
1110 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1111 if (allocator) {
1112 pools->outputAllocatorId = allocator->getId();
1113 } else {
1114 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1115 mName, surfaceAllocator->value);
1116 err = C2_BAD_VALUE;
1117 }
1118 }
1119 }
1120 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1121 && err != C2_OK
1122 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1123 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1124 }
1125 }
1126
1127 if ((poolMask >> pools->outputAllocatorId) & 1) {
1128 err = mComponent->createBlockPool(
1129 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1130 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1131 mName, pools->outputAllocatorId,
1132 (unsigned long long)pools->outputPoolId,
1133 asString(err));
1134 } else {
1135 err = C2_NOT_FOUND;
1136 }
1137 if (err != C2_OK) {
1138 // use basic pool instead
1139 pools->outputPoolId =
1140 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1141 }
1142
1143 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1144 // component.
1145 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1146 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1147
1148 std::vector<std::unique_ptr<C2SettingResult>> failures;
1149 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1150 ALOGD("[%s] Configured output block pool ids %llu => %s",
1151 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1152 outputPoolId_ = pools->outputPoolId;
1153 }
1154
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001155 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001156 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001157 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001158 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001159 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001160 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001161 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001162 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001163 }
1164 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001165 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001166 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001167 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001168
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001169 output->buffers->clearStash();
1170 if (reorderDepth) {
1171 output->buffers->setReorderDepth(reorderDepth.value);
1172 }
1173 if (reorderKey) {
1174 output->buffers->setReorderKey(reorderKey.value);
1175 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001176
1177 // Try to set output surface to created block pool if given.
1178 if (outputSurface) {
1179 mComponent->setOutputSurface(
1180 outputPoolId_,
1181 outputSurface,
1182 outputGeneration);
1183 }
1184
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001185 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001186 if (buffersBoundToCodec) {
1187 // WORKAROUND: if we're using early CSD workaround we convert to
1188 // array mode, to appease apps assuming the output
1189 // buffers to be of the same size.
1190 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1191 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001192
1193 int32_t channelCount;
1194 int32_t sampleRate;
1195 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1196 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1197 int32_t delay = 0;
1198 int32_t padding = 0;;
1199 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1200 delay = 0;
1201 }
1202 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1203 padding = 0;
1204 }
1205 if (delay || padding) {
1206 // We need write access to the buffers, and we're already in
1207 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001208 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001209 }
1210 }
1211 }
1212 }
1213
1214 // Set up pipeline control. This has to be done after mInputBuffers and
1215 // mOutputBuffers are initialized to make sure that lingering callbacks
1216 // about buffers from the previous generation do not interfere with the
1217 // newly initialized pipeline capacity.
1218
Wonsik Kimab34ed62019-01-31 15:28:46 -08001219 {
1220 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001221 watcher->inputDelay(inputDelayValue)
1222 .pipelineDelay(pipelineDelayValue)
1223 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001224 .smoothnessFactor(kSmoothnessFactor);
1225 watcher->flush();
1226 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001227
1228 mInputMetEos = false;
1229 mSync.start();
1230 return OK;
1231}
1232
1233status_t CCodecBufferChannel::requestInitialInputBuffers() {
1234 if (mInputSurface) {
1235 return OK;
1236 }
1237
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001238 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001239 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1240 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1241 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001242 return UNKNOWN_ERROR;
1243 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001244 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001245 std::vector<sp<MediaCodecBuffer>> toBeQueued;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001246 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001247 size_t index;
1248 sp<MediaCodecBuffer> buffer;
1249 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001250 Mutexed<Input>::Locked input(mInput);
1251 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001252 if (i == 0) {
1253 ALOGW("[%s] start: cannot allocate memory at all", mName);
1254 return NO_MEMORY;
1255 } else {
1256 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
1257 mName, i);
1258 }
1259 break;
1260 }
1261 }
1262 if (buffer) {
1263 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1264 ALOGV("[%s] input buffer %zu available", mName, index);
1265 bool post = true;
1266 if (!configs->empty()) {
1267 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001268 configs->pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001269 if (buffer->capacity() >= config->size()) {
1270 memcpy(buffer->base(), config->data(), config->size());
1271 buffer->setRange(0, config->size());
1272 buffer->meta()->clear();
1273 buffer->meta()->setInt64("timeUs", 0);
1274 buffer->meta()->setInt32("csd", 1);
1275 post = false;
1276 } else {
1277 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
1278 mName, buffer->capacity(), config->size());
1279 }
1280 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001281 && (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001282 // WORKAROUND: Some apps expect CSD available without queueing
1283 // any input. Queue an empty buffer to get the CSD.
1284 buffer->setRange(0, 0);
1285 buffer->meta()->clear();
1286 buffer->meta()->setInt64("timeUs", 0);
1287 post = false;
1288 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001289 if (post) {
1290 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001291 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001292 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001293 }
1294 }
1295 }
1296 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
1297 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001298 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001299 }
1300 }
1301 return OK;
1302}
1303
1304void CCodecBufferChannel::stop() {
1305 mSync.stop();
1306 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1307 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001308 mInputSurface.reset();
1309 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001310 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001311}
1312
Wonsik Kim936a89c2020-05-08 16:07:50 -07001313void CCodecBufferChannel::reset() {
1314 stop();
1315 {
1316 Mutexed<Input>::Locked input(mInput);
1317 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001318 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001319 }
1320 {
1321 Mutexed<Output>::Locked output(mOutput);
1322 output->buffers.reset();
1323 }
1324}
1325
1326void CCodecBufferChannel::release() {
1327 mComponent.reset();
1328 mInputAllocator.reset();
1329 mOutputSurface.lock()->surface.clear();
1330 {
1331 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1332 blockPools->inputPool.reset();
1333 blockPools->outputPoolIntf.reset();
1334 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001335 setCrypto(nullptr);
1336 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001337}
1338
1339
Pawin Vongmasa36653902018-11-15 00:10:25 -08001340void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1341 ALOGV("[%s] flush", mName);
1342 {
1343 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1344 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1345 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1346 continue;
1347 }
1348 if (work->input.buffers.empty()
1349 || work->input.buffers.front()->data().linearBlocks().empty()) {
1350 ALOGD("[%s] no linear codec config data found", mName);
1351 continue;
1352 }
1353 C2ReadView view =
1354 work->input.buffers.front()->data().linearBlocks().front().map().get();
1355 if (view.error() != C2_OK) {
1356 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1357 continue;
1358 }
1359 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1360 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1361 }
1362 }
1363 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001364 Mutexed<Input>::Locked input(mInput);
1365 input->buffers->flush();
1366 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001367 }
1368 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001369 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001370 if (output->buffers) {
1371 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001372 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001373 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001374 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001375 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001376}
1377
1378void CCodecBufferChannel::onWorkDone(
1379 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001380 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001381 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001382 feedInputBufferIfAvailable();
1383 }
1384}
1385
1386void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001387 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001388 if (mInputSurface) {
1389 return;
1390 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001391 std::shared_ptr<C2Buffer> buffer =
1392 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001393 bool newInputSlotAvailable;
1394 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001395 Mutexed<Input>::Locked input(mInput);
1396 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1397 if (!newInputSlotAvailable) {
1398 (void)input->extraBuffers.expireComponentBuffer(buffer);
1399 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001400 }
1401 if (newInputSlotAvailable) {
1402 feedInputBufferIfAvailable();
1403 }
1404}
1405
1406bool CCodecBufferChannel::handleWork(
1407 std::unique_ptr<C2Work> work,
1408 const sp<AMessage> &outputFormat,
1409 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001410 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001411 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001412 if (!output->buffers) {
1413 return false;
1414 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001415 }
1416
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001417 // Whether the output buffer should be reported to the client or not.
1418 bool notifyClient = false;
1419
1420 if (work->result == C2_OK){
1421 notifyClient = true;
1422 } else if (work->result == C2_NOT_FOUND) {
1423 ALOGD("[%s] flushed work; ignored.", mName);
1424 } else {
1425 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1426 // the config update.
1427 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1428 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1429 return false;
1430 }
1431
1432 if ((work->input.ordinal.frameIndex -
1433 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001434 // Discard frames from previous generation.
1435 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001436 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001437 }
1438
Wonsik Kim524b0582019-03-12 11:28:57 -07001439 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001440 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001441 || !(work->worklets.front()->output.flags &
1442 C2FrameData::FLAG_INCOMPLETE))) {
1443 mPipelineWatcher.lock()->onWorkDone(
1444 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001445 }
1446
1447 // NOTE: MediaCodec usage supposedly have only one worklet
1448 if (work->worklets.size() != 1u) {
1449 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1450 mName, work->worklets.size());
1451 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1452 return false;
1453 }
1454
1455 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1456
1457 std::shared_ptr<C2Buffer> buffer;
1458 // NOTE: MediaCodec usage supposedly have only one output stream.
1459 if (worklet->output.buffers.size() > 1u) {
1460 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1461 mName, worklet->output.buffers.size());
1462 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1463 return false;
1464 } else if (worklet->output.buffers.size() == 1u) {
1465 buffer = worklet->output.buffers[0];
1466 if (!buffer) {
1467 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1468 }
1469 }
1470
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001471 std::optional<uint32_t> newInputDelay, newPipelineDelay;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001472 while (!worklet->output.configUpdate.empty()) {
1473 std::unique_ptr<C2Param> param;
1474 worklet->output.configUpdate.back().swap(param);
1475 worklet->output.configUpdate.pop_back();
1476 switch (param->coreIndex().coreIndex()) {
1477 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1478 C2PortReorderBufferDepthTuning::output reorderDepth;
1479 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001480 bool secure = mComponent->getName().find(".secure") !=
1481 std::string::npos;
1482 mOutput.lock()->buffers->setReorderDepth(
1483 reorderDepth.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001484 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1485 mName, reorderDepth.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001486 size_t numOutputSlots = mOutput.lock()->numSlots;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001487 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001488 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001489 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001490 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001491 if (!secure) {
1492 output->maxDequeueBuffers += numInputSlots;
1493 }
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001494 if (output->surface) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001495 output->surface->setMaxDequeuedBufferCount(
1496 output->maxDequeueBuffers);
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001497 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001498 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001499 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1500 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001501 }
1502 break;
1503 }
1504 case C2PortReorderKeySetting::CORE_INDEX: {
1505 C2PortReorderKeySetting::output reorderKey;
1506 if (reorderKey.updateFrom(*param)) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001507 mOutput.lock()->buffers->setReorderKey(reorderKey.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001508 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1509 mName, reorderKey.value);
1510 } else {
1511 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1512 }
1513 break;
1514 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001515 case C2PortActualDelayTuning::CORE_INDEX: {
1516 if (param->isGlobal()) {
1517 C2ActualPipelineDelayTuning pipelineDelay;
1518 if (pipelineDelay.updateFrom(*param)) {
1519 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1520 mName, pipelineDelay.value);
1521 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001522 (void)mPipelineWatcher.lock()->pipelineDelay(
1523 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001524 }
1525 }
1526 if (param->forInput()) {
1527 C2PortActualDelayTuning::input inputDelay;
1528 if (inputDelay.updateFrom(*param)) {
1529 ALOGV("[%s] onWorkDone: updating input delay %u",
1530 mName, inputDelay.value);
1531 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001532 (void)mPipelineWatcher.lock()->inputDelay(
1533 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001534 }
1535 }
1536 if (param->forOutput()) {
1537 C2PortActualDelayTuning::output outputDelay;
1538 if (outputDelay.updateFrom(*param)) {
1539 ALOGV("[%s] onWorkDone: updating output delay %u",
1540 mName, outputDelay.value);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001541 bool secure = mComponent->getName().find(".secure") !=
1542 std::string::npos;
1543 (void)mPipelineWatcher.lock()->outputDelay(
1544 outputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001545
1546 bool outputBuffersChanged = false;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001547 size_t numOutputSlots = 0;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001548 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001549 {
1550 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001551 if (!output->buffers) {
1552 return false;
1553 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001554 output->outputDelay = outputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001555 numOutputSlots = outputDelay.value +
1556 kSmoothnessFactor;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001557 if (output->numSlots < numOutputSlots) {
1558 output->numSlots = numOutputSlots;
1559 if (output->buffers->isArrayMode()) {
1560 OutputBuffersArray *array =
1561 (OutputBuffersArray *)output->buffers.get();
1562 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1563 mName, numOutputSlots);
1564 array->grow(numOutputSlots);
1565 outputBuffersChanged = true;
1566 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001567 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001568 numOutputSlots = output->numSlots;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001569 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001570
1571 if (outputBuffersChanged) {
1572 mCCodecCallback->onOutputBuffersChanged();
1573 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001574
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001575 uint32_t depth = mOutput.lock()->buffers->getReorderDepth();
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001576 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001577 output->maxDequeueBuffers = numOutputSlots + depth + kRenderingDepth;
1578 if (!secure) {
1579 output->maxDequeueBuffers += numInputSlots;
1580 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001581 if (output->surface) {
1582 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1583 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001584 }
1585 }
1586 break;
1587 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001588 default:
1589 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1590 mName, param->index());
1591 break;
1592 }
1593 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001594 if (newInputDelay || newPipelineDelay) {
1595 Mutexed<Input>::Locked input(mInput);
1596 size_t newNumSlots =
1597 newInputDelay.value_or(input->inputDelay) +
1598 newPipelineDelay.value_or(input->pipelineDelay) +
1599 kSmoothnessFactor;
1600 if (input->buffers->isArrayMode()) {
1601 if (input->numSlots >= newNumSlots) {
1602 input->numExtraSlots = 0;
1603 } else {
1604 input->numExtraSlots = newNumSlots - input->numSlots;
1605 }
1606 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1607 mName, input->numExtraSlots);
1608 } else {
1609 input->numSlots = newNumSlots;
1610 }
1611 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001612
Pawin Vongmasa36653902018-11-15 00:10:25 -08001613 int32_t flags = 0;
1614 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1615 flags |= MediaCodec::BUFFER_FLAG_EOS;
1616 ALOGV("[%s] onWorkDone: output EOS", mName);
1617 }
1618
Pawin Vongmasa36653902018-11-15 00:10:25 -08001619 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1620 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1621 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1622 // shall correspond to the client input timesamp (in customOrdinal). By using the
1623 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1624 // produces multiple output.
1625 c2_cntr64_t timestamp =
1626 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1627 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001628 if (mInputSurface != nullptr) {
1629 // When using input surface we need to restore the original input timestamp.
1630 timestamp = work->input.ordinal.customOrdinal;
1631 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001632 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1633 mName,
1634 work->input.ordinal.customOrdinal.peekll(),
1635 work->input.ordinal.timestamp.peekll(),
1636 worklet->output.ordinal.timestamp.peekll(),
1637 timestamp.peekll());
1638
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001639 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001640 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001641 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001642 if (output->buffers && outputFormat) {
1643 output->buffers->updateSkipCutBuffer(outputFormat);
1644 output->buffers->setFormat(outputFormat);
1645 }
1646 if (!notifyClient) {
1647 return false;
1648 }
1649 size_t index;
1650 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07001651 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001652 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1653 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1654 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1655
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001656 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001657 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001658 } else {
1659 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001660 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001661 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001662 return false;
1663 }
1664 }
1665
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001666 if (notifyClient && !buffer && !flags) {
Wonsik Kim35bf5732020-05-14 17:40:29 +00001667 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001668 mName, work->input.ordinal.frameIndex.peekull());
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001669 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001670 }
1671
1672 if (buffer) {
1673 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1674 // TODO: properly translate these to metadata
1675 switch (info->coreIndex().coreIndex()) {
1676 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001677 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001678 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1679 }
1680 break;
1681 default:
1682 break;
1683 }
1684 }
1685 }
1686
1687 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001688 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07001689 if (!output->buffers) {
1690 return false;
1691 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001692 output->buffers->pushToStash(
1693 buffer,
1694 notifyClient,
1695 timestamp.peek(),
1696 flags,
1697 outputFormat,
1698 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001699 }
1700 sendOutputBuffers();
1701 return true;
1702}
1703
1704void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001705 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001706 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001707 sp<MediaCodecBuffer> outBuffer;
1708 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001709
1710 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001711 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001712 if (!output->buffers) {
1713 return;
1714 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001715 action = output->buffers->popFromStashAndRegister(
1716 &c2Buffer, &index, &outBuffer);
1717 switch (action) {
1718 case OutputBuffers::SKIP:
1719 return;
1720 case OutputBuffers::DISCARD:
1721 break;
1722 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00001723 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001724 mCallback->onOutputBufferAvailable(index, outBuffer);
1725 break;
1726 case OutputBuffers::REALLOCATE:
1727 if (!output->buffers->isArrayMode()) {
1728 output->buffers =
1729 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001730 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001731 static_cast<OutputBuffersArray*>(output->buffers.get())->
1732 realloc(c2Buffer);
1733 output.unlock();
1734 mCCodecCallback->onOutputBuffersChanged();
1735 return;
1736 case OutputBuffers::RETRY:
1737 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
1738 mName);
1739 return;
1740 default:
1741 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
1742 "corrupted BufferAction value (%d) "
1743 "returned from popFromStashAndRegister.",
1744 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001745 return;
1746 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001747 }
1748}
1749
1750status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1751 static std::atomic_uint32_t surfaceGeneration{0};
1752 uint32_t generation = (getpid() << 10) |
1753 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1754 & ((1 << 10) - 1));
1755
1756 sp<IGraphicBufferProducer> producer;
1757 if (newSurface) {
1758 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001759 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Lee08515812019-06-05 11:16:32 -07001760 newSurface->setMaxDequeuedBufferCount(mOutputSurface.lock()->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001761 producer = newSurface->getIGraphicBufferProducer();
1762 producer->setGenerationNumber(generation);
1763 } else {
1764 ALOGE("[%s] setting output surface to null", mName);
1765 return INVALID_OPERATION;
1766 }
1767
1768 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1769 C2BlockPool::local_id_t outputPoolId;
1770 {
1771 Mutexed<BlockPools>::Locked pools(mBlockPools);
1772 outputPoolId = pools->outputPoolId;
1773 outputPoolIntf = pools->outputPoolIntf;
1774 }
1775
1776 if (outputPoolIntf) {
1777 if (mComponent->setOutputSurface(
1778 outputPoolId,
1779 producer,
1780 generation) != C2_OK) {
1781 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1782 return INVALID_OPERATION;
1783 }
1784 }
1785
1786 {
1787 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1788 output->surface = newSurface;
1789 output->generation = generation;
1790 }
1791
1792 return OK;
1793}
1794
Wonsik Kimab34ed62019-01-31 15:28:46 -08001795PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001796 // When client pushed EOS, we want all the work to be done quickly.
1797 // Otherwise, component may have stalled work due to input starvation up to
1798 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001799 size_t n = 0;
1800 if (!mInputMetEos) {
1801 size_t outputDelay = mOutput.lock()->outputDelay;
1802 Mutexed<Input>::Locked input(mInput);
1803 n = input->inputDelay + input->pipelineDelay + outputDelay;
1804 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001805 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001806}
1807
Pawin Vongmasa36653902018-11-15 00:10:25 -08001808void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1809 mMetaMode = mode;
1810}
1811
Wonsik Kim596187e2019-10-25 12:44:10 -07001812void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001813 if (mCrypto != nullptr) {
1814 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
1815 mCrypto->unsetHeap(entry.second);
1816 }
1817 mHeapSeqNumMap.clear();
1818 if (mHeapSeqNum >= 0) {
1819 mCrypto->unsetHeap(mHeapSeqNum);
1820 mHeapSeqNum = -1;
1821 }
1822 }
Wonsik Kim596187e2019-10-25 12:44:10 -07001823 mCrypto = crypto;
1824}
1825
1826void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
1827 mDescrambler = descrambler;
1828}
1829
Pawin Vongmasa36653902018-11-15 00:10:25 -08001830status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1831 // C2_OK is always translated to OK.
1832 if (c2s == C2_OK) {
1833 return OK;
1834 }
1835
1836 // Operation-dependent translation
1837 // TODO: Add as necessary
1838 switch (c2op) {
1839 case C2_OPERATION_Component_start:
1840 switch (c2s) {
1841 case C2_NO_MEMORY:
1842 return NO_MEMORY;
1843 default:
1844 return UNKNOWN_ERROR;
1845 }
1846 default:
1847 break;
1848 }
1849
1850 // Backup operation-agnostic translation
1851 switch (c2s) {
1852 case C2_BAD_INDEX:
1853 return BAD_INDEX;
1854 case C2_BAD_VALUE:
1855 return BAD_VALUE;
1856 case C2_BLOCKING:
1857 return WOULD_BLOCK;
1858 case C2_DUPLICATE:
1859 return ALREADY_EXISTS;
1860 case C2_NO_INIT:
1861 return NO_INIT;
1862 case C2_NO_MEMORY:
1863 return NO_MEMORY;
1864 case C2_NOT_FOUND:
1865 return NAME_NOT_FOUND;
1866 case C2_TIMED_OUT:
1867 return TIMED_OUT;
1868 case C2_BAD_STATE:
1869 case C2_CANCELED:
1870 case C2_CANNOT_DO:
1871 case C2_CORRUPTED:
1872 case C2_OMITTED:
1873 case C2_REFUSED:
1874 return UNKNOWN_ERROR;
1875 default:
1876 return -static_cast<status_t>(c2s);
1877 }
1878}
1879
1880} // namespace android