blob: 94cb04da9d7f37d7a676f817354b19086b9e8a94 [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);
Wonsik Kimffb889a2020-05-28 11:32:25 -0700917 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
918 API_REFLECTION |
919 API_VALUES |
920 API_CURRENT_VALUES |
921 API_DEPENDENCY |
922 API_SAME_INPUT_BUFFER);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800923 std::shared_ptr<C2BlockPool> pool;
924 {
925 Mutexed<BlockPools>::Locked pools(mBlockPools);
926
927 // set default allocator ID.
928 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +0800929 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800930
931 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
932 // from component, create the input block pool with given ID. Otherwise, use default IDs.
933 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -0700934 C2ApiFeaturesSetting featuresSetting{apiFeatures};
935 err = mComponent->query({ &featuresSetting },
Pawin Vongmasa36653902018-11-15 00:10:25 -0800936 { C2PortAllocatorsTuning::input::PARAM_TYPE },
937 C2_DONT_BLOCK,
938 &params);
939 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
940 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
941 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -0700942 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800943 C2PortAllocatorsTuning::input *inputAllocators =
944 C2PortAllocatorsTuning::input::From(params[0].get());
945 if (inputAllocators && inputAllocators->flexCount() > 0) {
946 std::shared_ptr<C2Allocator> allocator;
947 // verify allocator IDs and resolve default allocator
948 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
949 if (allocator) {
950 pools->inputAllocatorId = allocator->getId();
951 } else {
952 ALOGD("[%s] component requested invalid input allocator ID %u",
953 mName, inputAllocators->m.values[0]);
954 }
955 }
956 }
Wonsik Kimffb889a2020-05-28 11:32:25 -0700957 if (featuresSetting) {
958 apiFeatures = featuresSetting.value;
959 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800960
961 // TODO: use C2Component wrapper to associate this pool with ourselves
962 if ((poolMask >> pools->inputAllocatorId) & 1) {
963 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
964 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
965 mName, pools->inputAllocatorId,
966 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
967 asString(err), err);
968 } else {
969 err = C2_NOT_FOUND;
970 }
971 if (err != C2_OK) {
972 C2BlockPool::local_id_t inputPoolId =
973 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
974 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
975 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
976 mName, (unsigned long long)inputPoolId,
977 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
978 asString(err), err);
979 if (err != C2_OK) {
980 return NO_MEMORY;
981 }
982 }
983 pools->inputPool = pool;
984 }
985
Wonsik Kim51051262018-11-28 13:59:05 -0800986 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700987 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -0700988 input->inputDelay = inputDelayValue;
989 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700990 input->numSlots = numInputSlots;
991 input->extraBuffers.flush();
992 input->numExtraSlots = 0u;
Wonsik Kimffb889a2020-05-28 11:32:25 -0700993 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
994 // For encrypted content, framework decrypts source buffer (ashmem) into
995 // C2Buffers. Thus non-conforming codecs can process these.
996 if (!buffersBoundToCodec && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800997 input->buffers.reset(new SlotInputBuffers(mName));
998 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800999 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001000 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001001 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001002 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001003 // This is to ensure buffers do not get released prematurely.
1004 // TODO: handle this without going into array mode
1005 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001006 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001007 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001008 }
1009 } else {
1010 if (hasCryptoOrDescrambler()) {
1011 int32_t capacity = kLinearBufferSize;
1012 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1013 if ((size_t)capacity > kMaxLinearBufferSize) {
1014 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1015 capacity = kMaxLinearBufferSize;
1016 }
1017 if (mDealer == nullptr) {
1018 mDealer = new MemoryDealer(
1019 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001020 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001021 "EncryptedLinearInputBuffers");
1022 mDecryptDestination = mDealer->allocate((size_t)capacity);
1023 }
1024 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001025 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1026 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001027 } else {
1028 mHeapSeqNum = -1;
1029 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001030 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001031 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001032 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001033 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001034 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001035 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001036 }
1037 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001038 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001039
1040 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001041 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001042 } else {
1043 // TODO: error
1044 }
Wonsik Kim51051262018-11-28 13:59:05 -08001045
1046 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001047 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001048 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001049 }
1050
1051 if (outputFormat != nullptr) {
1052 sp<IGraphicBufferProducer> outputSurface;
1053 uint32_t outputGeneration;
1054 {
1055 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001056 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001057 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001058 if (!secure) {
1059 output->maxDequeueBuffers += numInputSlots;
1060 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001061 outputSurface = output->surface ?
1062 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001063 if (outputSurface) {
1064 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1065 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001066 outputGeneration = output->generation;
1067 }
1068
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001069 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001070 C2BlockPool::local_id_t outputPoolId_;
1071
1072 {
1073 Mutexed<BlockPools>::Locked pools(mBlockPools);
1074
1075 // set default allocator ID.
1076 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001077 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001078
1079 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1080 // unsuccessful.
1081 std::vector<std::unique_ptr<C2Param>> params;
1082 err = mComponent->query({ },
1083 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1084 C2_DONT_BLOCK,
1085 &params);
1086 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1087 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1088 mName, params.size(), asString(err), err);
1089 } else if (err == C2_OK && params.size() == 1) {
1090 C2PortAllocatorsTuning::output *outputAllocators =
1091 C2PortAllocatorsTuning::output::From(params[0].get());
1092 if (outputAllocators && outputAllocators->flexCount() > 0) {
1093 std::shared_ptr<C2Allocator> allocator;
1094 // verify allocator IDs and resolve default allocator
1095 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1096 if (allocator) {
1097 pools->outputAllocatorId = allocator->getId();
1098 } else {
1099 ALOGD("[%s] component requested invalid output allocator ID %u",
1100 mName, outputAllocators->m.values[0]);
1101 }
1102 }
1103 }
1104
1105 // use bufferqueue if outputting to a surface.
1106 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1107 // if unsuccessful.
1108 if (outputSurface) {
1109 params.clear();
1110 err = mComponent->query({ },
1111 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1112 C2_DONT_BLOCK,
1113 &params);
1114 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1115 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1116 mName, params.size(), asString(err), err);
1117 } else if (err == C2_OK && params.size() == 1) {
1118 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1119 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1120 if (surfaceAllocator) {
1121 std::shared_ptr<C2Allocator> allocator;
1122 // verify allocator IDs and resolve default allocator
1123 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1124 if (allocator) {
1125 pools->outputAllocatorId = allocator->getId();
1126 } else {
1127 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1128 mName, surfaceAllocator->value);
1129 err = C2_BAD_VALUE;
1130 }
1131 }
1132 }
1133 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1134 && err != C2_OK
1135 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1136 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1137 }
1138 }
1139
1140 if ((poolMask >> pools->outputAllocatorId) & 1) {
1141 err = mComponent->createBlockPool(
1142 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1143 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1144 mName, pools->outputAllocatorId,
1145 (unsigned long long)pools->outputPoolId,
1146 asString(err));
1147 } else {
1148 err = C2_NOT_FOUND;
1149 }
1150 if (err != C2_OK) {
1151 // use basic pool instead
1152 pools->outputPoolId =
1153 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1154 }
1155
1156 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1157 // component.
1158 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1159 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1160
1161 std::vector<std::unique_ptr<C2SettingResult>> failures;
1162 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1163 ALOGD("[%s] Configured output block pool ids %llu => %s",
1164 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1165 outputPoolId_ = pools->outputPoolId;
1166 }
1167
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001168 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001169 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001170 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001171 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001172 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001173 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001174 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001175 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001176 }
1177 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001178 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001179 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001180 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001181
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001182 output->buffers->clearStash();
1183 if (reorderDepth) {
1184 output->buffers->setReorderDepth(reorderDepth.value);
1185 }
1186 if (reorderKey) {
1187 output->buffers->setReorderKey(reorderKey.value);
1188 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001189
1190 // Try to set output surface to created block pool if given.
1191 if (outputSurface) {
1192 mComponent->setOutputSurface(
1193 outputPoolId_,
1194 outputSurface,
1195 outputGeneration);
1196 }
1197
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001198 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001199 if (buffersBoundToCodec) {
1200 // WORKAROUND: if we're using early CSD workaround we convert to
1201 // array mode, to appease apps assuming the output
1202 // buffers to be of the same size.
1203 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1204 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001205
1206 int32_t channelCount;
1207 int32_t sampleRate;
1208 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1209 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1210 int32_t delay = 0;
1211 int32_t padding = 0;;
1212 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1213 delay = 0;
1214 }
1215 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1216 padding = 0;
1217 }
1218 if (delay || padding) {
1219 // We need write access to the buffers, and we're already in
1220 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001221 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001222 }
1223 }
1224 }
1225 }
1226
1227 // Set up pipeline control. This has to be done after mInputBuffers and
1228 // mOutputBuffers are initialized to make sure that lingering callbacks
1229 // about buffers from the previous generation do not interfere with the
1230 // newly initialized pipeline capacity.
1231
Wonsik Kimab34ed62019-01-31 15:28:46 -08001232 {
1233 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001234 watcher->inputDelay(inputDelayValue)
1235 .pipelineDelay(pipelineDelayValue)
1236 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001237 .smoothnessFactor(kSmoothnessFactor);
1238 watcher->flush();
1239 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001240
1241 mInputMetEos = false;
1242 mSync.start();
1243 return OK;
1244}
1245
1246status_t CCodecBufferChannel::requestInitialInputBuffers() {
1247 if (mInputSurface) {
1248 return OK;
1249 }
1250
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001251 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001252 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1253 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1254 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001255 return UNKNOWN_ERROR;
1256 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001257 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001258 std::vector<sp<MediaCodecBuffer>> toBeQueued;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001259 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001260 size_t index;
1261 sp<MediaCodecBuffer> buffer;
1262 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001263 Mutexed<Input>::Locked input(mInput);
1264 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001265 if (i == 0) {
1266 ALOGW("[%s] start: cannot allocate memory at all", mName);
1267 return NO_MEMORY;
1268 } else {
1269 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
1270 mName, i);
1271 }
1272 break;
1273 }
1274 }
1275 if (buffer) {
1276 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1277 ALOGV("[%s] input buffer %zu available", mName, index);
1278 bool post = true;
1279 if (!configs->empty()) {
1280 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001281 configs->pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001282 if (buffer->capacity() >= config->size()) {
1283 memcpy(buffer->base(), config->data(), config->size());
1284 buffer->setRange(0, config->size());
1285 buffer->meta()->clear();
1286 buffer->meta()->setInt64("timeUs", 0);
1287 buffer->meta()->setInt32("csd", 1);
1288 post = false;
1289 } else {
1290 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
1291 mName, buffer->capacity(), config->size());
1292 }
1293 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001294 && (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001295 // WORKAROUND: Some apps expect CSD available without queueing
1296 // any input. Queue an empty buffer to get the CSD.
1297 buffer->setRange(0, 0);
1298 buffer->meta()->clear();
1299 buffer->meta()->setInt64("timeUs", 0);
1300 post = false;
1301 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001302 if (post) {
1303 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001304 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001305 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001306 }
1307 }
1308 }
1309 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
1310 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001311 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001312 }
1313 }
1314 return OK;
1315}
1316
1317void CCodecBufferChannel::stop() {
1318 mSync.stop();
1319 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1320 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001321 mInputSurface.reset();
1322 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001323 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001324}
1325
Wonsik Kim936a89c2020-05-08 16:07:50 -07001326void CCodecBufferChannel::reset() {
1327 stop();
1328 {
1329 Mutexed<Input>::Locked input(mInput);
1330 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001331 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001332 }
1333 {
1334 Mutexed<Output>::Locked output(mOutput);
1335 output->buffers.reset();
1336 }
1337}
1338
1339void CCodecBufferChannel::release() {
1340 mComponent.reset();
1341 mInputAllocator.reset();
1342 mOutputSurface.lock()->surface.clear();
1343 {
1344 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1345 blockPools->inputPool.reset();
1346 blockPools->outputPoolIntf.reset();
1347 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001348 setCrypto(nullptr);
1349 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001350}
1351
1352
Pawin Vongmasa36653902018-11-15 00:10:25 -08001353void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1354 ALOGV("[%s] flush", mName);
1355 {
1356 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1357 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1358 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1359 continue;
1360 }
1361 if (work->input.buffers.empty()
1362 || work->input.buffers.front()->data().linearBlocks().empty()) {
1363 ALOGD("[%s] no linear codec config data found", mName);
1364 continue;
1365 }
1366 C2ReadView view =
1367 work->input.buffers.front()->data().linearBlocks().front().map().get();
1368 if (view.error() != C2_OK) {
1369 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1370 continue;
1371 }
1372 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1373 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1374 }
1375 }
1376 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001377 Mutexed<Input>::Locked input(mInput);
1378 input->buffers->flush();
1379 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001380 }
1381 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001382 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001383 if (output->buffers) {
1384 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001385 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001386 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001387 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001388 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001389}
1390
1391void CCodecBufferChannel::onWorkDone(
1392 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001393 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001395 feedInputBufferIfAvailable();
1396 }
1397}
1398
1399void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001400 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001401 if (mInputSurface) {
1402 return;
1403 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001404 std::shared_ptr<C2Buffer> buffer =
1405 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001406 bool newInputSlotAvailable;
1407 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001408 Mutexed<Input>::Locked input(mInput);
1409 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1410 if (!newInputSlotAvailable) {
1411 (void)input->extraBuffers.expireComponentBuffer(buffer);
1412 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001413 }
1414 if (newInputSlotAvailable) {
1415 feedInputBufferIfAvailable();
1416 }
1417}
1418
1419bool CCodecBufferChannel::handleWork(
1420 std::unique_ptr<C2Work> work,
1421 const sp<AMessage> &outputFormat,
1422 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001423 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001424 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001425 if (!output->buffers) {
1426 return false;
1427 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001428 }
1429
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001430 // Whether the output buffer should be reported to the client or not.
1431 bool notifyClient = false;
1432
1433 if (work->result == C2_OK){
1434 notifyClient = true;
1435 } else if (work->result == C2_NOT_FOUND) {
1436 ALOGD("[%s] flushed work; ignored.", mName);
1437 } else {
1438 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1439 // the config update.
1440 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1441 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1442 return false;
1443 }
1444
1445 if ((work->input.ordinal.frameIndex -
1446 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001447 // Discard frames from previous generation.
1448 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001449 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001450 }
1451
Wonsik Kim524b0582019-03-12 11:28:57 -07001452 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001453 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001454 || !(work->worklets.front()->output.flags &
1455 C2FrameData::FLAG_INCOMPLETE))) {
1456 mPipelineWatcher.lock()->onWorkDone(
1457 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001458 }
1459
1460 // NOTE: MediaCodec usage supposedly have only one worklet
1461 if (work->worklets.size() != 1u) {
1462 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1463 mName, work->worklets.size());
1464 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1465 return false;
1466 }
1467
1468 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1469
1470 std::shared_ptr<C2Buffer> buffer;
1471 // NOTE: MediaCodec usage supposedly have only one output stream.
1472 if (worklet->output.buffers.size() > 1u) {
1473 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1474 mName, worklet->output.buffers.size());
1475 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1476 return false;
1477 } else if (worklet->output.buffers.size() == 1u) {
1478 buffer = worklet->output.buffers[0];
1479 if (!buffer) {
1480 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1481 }
1482 }
1483
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001484 std::optional<uint32_t> newInputDelay, newPipelineDelay;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001485 while (!worklet->output.configUpdate.empty()) {
1486 std::unique_ptr<C2Param> param;
1487 worklet->output.configUpdate.back().swap(param);
1488 worklet->output.configUpdate.pop_back();
1489 switch (param->coreIndex().coreIndex()) {
1490 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1491 C2PortReorderBufferDepthTuning::output reorderDepth;
1492 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001493 bool secure = mComponent->getName().find(".secure") !=
1494 std::string::npos;
1495 mOutput.lock()->buffers->setReorderDepth(
1496 reorderDepth.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001497 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1498 mName, reorderDepth.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001499 size_t numOutputSlots = mOutput.lock()->numSlots;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001500 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001501 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001502 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001503 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001504 if (!secure) {
1505 output->maxDequeueBuffers += numInputSlots;
1506 }
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001507 if (output->surface) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001508 output->surface->setMaxDequeuedBufferCount(
1509 output->maxDequeueBuffers);
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001510 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001511 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001512 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1513 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001514 }
1515 break;
1516 }
1517 case C2PortReorderKeySetting::CORE_INDEX: {
1518 C2PortReorderKeySetting::output reorderKey;
1519 if (reorderKey.updateFrom(*param)) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001520 mOutput.lock()->buffers->setReorderKey(reorderKey.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001521 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1522 mName, reorderKey.value);
1523 } else {
1524 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1525 }
1526 break;
1527 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001528 case C2PortActualDelayTuning::CORE_INDEX: {
1529 if (param->isGlobal()) {
1530 C2ActualPipelineDelayTuning pipelineDelay;
1531 if (pipelineDelay.updateFrom(*param)) {
1532 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1533 mName, pipelineDelay.value);
1534 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001535 (void)mPipelineWatcher.lock()->pipelineDelay(
1536 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001537 }
1538 }
1539 if (param->forInput()) {
1540 C2PortActualDelayTuning::input inputDelay;
1541 if (inputDelay.updateFrom(*param)) {
1542 ALOGV("[%s] onWorkDone: updating input delay %u",
1543 mName, inputDelay.value);
1544 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001545 (void)mPipelineWatcher.lock()->inputDelay(
1546 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001547 }
1548 }
1549 if (param->forOutput()) {
1550 C2PortActualDelayTuning::output outputDelay;
1551 if (outputDelay.updateFrom(*param)) {
1552 ALOGV("[%s] onWorkDone: updating output delay %u",
1553 mName, outputDelay.value);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001554 bool secure = mComponent->getName().find(".secure") !=
1555 std::string::npos;
1556 (void)mPipelineWatcher.lock()->outputDelay(
1557 outputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001558
1559 bool outputBuffersChanged = false;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001560 size_t numOutputSlots = 0;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001561 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001562 {
1563 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001564 if (!output->buffers) {
1565 return false;
1566 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001567 output->outputDelay = outputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001568 numOutputSlots = outputDelay.value +
1569 kSmoothnessFactor;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001570 if (output->numSlots < numOutputSlots) {
1571 output->numSlots = numOutputSlots;
1572 if (output->buffers->isArrayMode()) {
1573 OutputBuffersArray *array =
1574 (OutputBuffersArray *)output->buffers.get();
1575 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1576 mName, numOutputSlots);
1577 array->grow(numOutputSlots);
1578 outputBuffersChanged = true;
1579 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001580 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001581 numOutputSlots = output->numSlots;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001582 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001583
1584 if (outputBuffersChanged) {
1585 mCCodecCallback->onOutputBuffersChanged();
1586 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001587
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001588 uint32_t depth = mOutput.lock()->buffers->getReorderDepth();
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001589 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001590 output->maxDequeueBuffers = numOutputSlots + depth + kRenderingDepth;
1591 if (!secure) {
1592 output->maxDequeueBuffers += numInputSlots;
1593 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001594 if (output->surface) {
1595 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1596 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001597 }
1598 }
1599 break;
1600 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001601 default:
1602 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1603 mName, param->index());
1604 break;
1605 }
1606 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001607 if (newInputDelay || newPipelineDelay) {
1608 Mutexed<Input>::Locked input(mInput);
1609 size_t newNumSlots =
1610 newInputDelay.value_or(input->inputDelay) +
1611 newPipelineDelay.value_or(input->pipelineDelay) +
1612 kSmoothnessFactor;
1613 if (input->buffers->isArrayMode()) {
1614 if (input->numSlots >= newNumSlots) {
1615 input->numExtraSlots = 0;
1616 } else {
1617 input->numExtraSlots = newNumSlots - input->numSlots;
1618 }
1619 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1620 mName, input->numExtraSlots);
1621 } else {
1622 input->numSlots = newNumSlots;
1623 }
1624 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001625
Pawin Vongmasa36653902018-11-15 00:10:25 -08001626 int32_t flags = 0;
1627 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1628 flags |= MediaCodec::BUFFER_FLAG_EOS;
1629 ALOGV("[%s] onWorkDone: output EOS", mName);
1630 }
1631
Pawin Vongmasa36653902018-11-15 00:10:25 -08001632 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1633 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1634 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1635 // shall correspond to the client input timesamp (in customOrdinal). By using the
1636 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1637 // produces multiple output.
1638 c2_cntr64_t timestamp =
1639 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1640 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001641 if (mInputSurface != nullptr) {
1642 // When using input surface we need to restore the original input timestamp.
1643 timestamp = work->input.ordinal.customOrdinal;
1644 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001645 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1646 mName,
1647 work->input.ordinal.customOrdinal.peekll(),
1648 work->input.ordinal.timestamp.peekll(),
1649 worklet->output.ordinal.timestamp.peekll(),
1650 timestamp.peekll());
1651
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001652 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001653 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001654 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001655 if (output->buffers && outputFormat) {
1656 output->buffers->updateSkipCutBuffer(outputFormat);
1657 output->buffers->setFormat(outputFormat);
1658 }
1659 if (!notifyClient) {
1660 return false;
1661 }
1662 size_t index;
1663 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07001664 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001665 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1666 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1667 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1668
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001669 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001670 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001671 } else {
1672 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001673 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001674 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001675 return false;
1676 }
1677 }
1678
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001679 if (notifyClient && !buffer && !flags) {
Wonsik Kim35bf5732020-05-14 17:40:29 +00001680 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001681 mName, work->input.ordinal.frameIndex.peekull());
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001682 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001683 }
1684
1685 if (buffer) {
1686 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1687 // TODO: properly translate these to metadata
1688 switch (info->coreIndex().coreIndex()) {
1689 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001690 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001691 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1692 }
1693 break;
1694 default:
1695 break;
1696 }
1697 }
1698 }
1699
1700 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001701 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07001702 if (!output->buffers) {
1703 return false;
1704 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001705 output->buffers->pushToStash(
1706 buffer,
1707 notifyClient,
1708 timestamp.peek(),
1709 flags,
1710 outputFormat,
1711 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001712 }
1713 sendOutputBuffers();
1714 return true;
1715}
1716
1717void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001718 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001719 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001720 sp<MediaCodecBuffer> outBuffer;
1721 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001722
1723 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001724 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001725 if (!output->buffers) {
1726 return;
1727 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001728 action = output->buffers->popFromStashAndRegister(
1729 &c2Buffer, &index, &outBuffer);
1730 switch (action) {
1731 case OutputBuffers::SKIP:
1732 return;
1733 case OutputBuffers::DISCARD:
1734 break;
1735 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00001736 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001737 mCallback->onOutputBufferAvailable(index, outBuffer);
1738 break;
1739 case OutputBuffers::REALLOCATE:
1740 if (!output->buffers->isArrayMode()) {
1741 output->buffers =
1742 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001743 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001744 static_cast<OutputBuffersArray*>(output->buffers.get())->
1745 realloc(c2Buffer);
1746 output.unlock();
1747 mCCodecCallback->onOutputBuffersChanged();
1748 return;
1749 case OutputBuffers::RETRY:
1750 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
1751 mName);
1752 return;
1753 default:
1754 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
1755 "corrupted BufferAction value (%d) "
1756 "returned from popFromStashAndRegister.",
1757 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001758 return;
1759 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001760 }
1761}
1762
1763status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1764 static std::atomic_uint32_t surfaceGeneration{0};
1765 uint32_t generation = (getpid() << 10) |
1766 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1767 & ((1 << 10) - 1));
1768
1769 sp<IGraphicBufferProducer> producer;
1770 if (newSurface) {
1771 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001772 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Lee08515812019-06-05 11:16:32 -07001773 newSurface->setMaxDequeuedBufferCount(mOutputSurface.lock()->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001774 producer = newSurface->getIGraphicBufferProducer();
1775 producer->setGenerationNumber(generation);
1776 } else {
1777 ALOGE("[%s] setting output surface to null", mName);
1778 return INVALID_OPERATION;
1779 }
1780
1781 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1782 C2BlockPool::local_id_t outputPoolId;
1783 {
1784 Mutexed<BlockPools>::Locked pools(mBlockPools);
1785 outputPoolId = pools->outputPoolId;
1786 outputPoolIntf = pools->outputPoolIntf;
1787 }
1788
1789 if (outputPoolIntf) {
1790 if (mComponent->setOutputSurface(
1791 outputPoolId,
1792 producer,
1793 generation) != C2_OK) {
1794 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1795 return INVALID_OPERATION;
1796 }
1797 }
1798
1799 {
1800 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1801 output->surface = newSurface;
1802 output->generation = generation;
1803 }
1804
1805 return OK;
1806}
1807
Wonsik Kimab34ed62019-01-31 15:28:46 -08001808PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001809 // When client pushed EOS, we want all the work to be done quickly.
1810 // Otherwise, component may have stalled work due to input starvation up to
1811 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001812 size_t n = 0;
1813 if (!mInputMetEos) {
1814 size_t outputDelay = mOutput.lock()->outputDelay;
1815 Mutexed<Input>::Locked input(mInput);
1816 n = input->inputDelay + input->pipelineDelay + outputDelay;
1817 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001818 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001819}
1820
Pawin Vongmasa36653902018-11-15 00:10:25 -08001821void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1822 mMetaMode = mode;
1823}
1824
Wonsik Kim596187e2019-10-25 12:44:10 -07001825void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001826 if (mCrypto != nullptr) {
1827 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
1828 mCrypto->unsetHeap(entry.second);
1829 }
1830 mHeapSeqNumMap.clear();
1831 if (mHeapSeqNum >= 0) {
1832 mCrypto->unsetHeap(mHeapSeqNum);
1833 mHeapSeqNum = -1;
1834 }
1835 }
Wonsik Kim596187e2019-10-25 12:44:10 -07001836 mCrypto = crypto;
1837}
1838
1839void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
1840 mDescrambler = descrambler;
1841}
1842
Pawin Vongmasa36653902018-11-15 00:10:25 -08001843status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1844 // C2_OK is always translated to OK.
1845 if (c2s == C2_OK) {
1846 return OK;
1847 }
1848
1849 // Operation-dependent translation
1850 // TODO: Add as necessary
1851 switch (c2op) {
1852 case C2_OPERATION_Component_start:
1853 switch (c2s) {
1854 case C2_NO_MEMORY:
1855 return NO_MEMORY;
1856 default:
1857 return UNKNOWN_ERROR;
1858 }
1859 default:
1860 break;
1861 }
1862
1863 // Backup operation-agnostic translation
1864 switch (c2s) {
1865 case C2_BAD_INDEX:
1866 return BAD_INDEX;
1867 case C2_BAD_VALUE:
1868 return BAD_VALUE;
1869 case C2_BLOCKING:
1870 return WOULD_BLOCK;
1871 case C2_DUPLICATE:
1872 return ALREADY_EXISTS;
1873 case C2_NO_INIT:
1874 return NO_INIT;
1875 case C2_NO_MEMORY:
1876 return NO_MEMORY;
1877 case C2_NOT_FOUND:
1878 return NAME_NOT_FOUND;
1879 case C2_TIMED_OUT:
1880 return TIMED_OUT;
1881 case C2_BAD_STATE:
1882 case C2_CANCELED:
1883 case C2_CANNOT_DO:
1884 case C2_CORRUPTED:
1885 case C2_OMITTED:
1886 case C2_REFUSED:
1887 return UNKNOWN_ERROR;
1888 default:
1889 return -static_cast<status_t>(c2s);
1890 }
1891}
1892
1893} // namespace android