blob: 3773528fc761d2f1b82e18b56c14bf38f969ca60 [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 Kima4e049d2020-04-28 19:42:23 +0000131// CCodecBufferChannel::ReorderStash
132
133CCodecBufferChannel::ReorderStash::ReorderStash() {
134 clear();
135}
136
137void CCodecBufferChannel::ReorderStash::clear() {
138 mPending.clear();
139 mStash.clear();
140 mDepth = 0;
141 mKey = C2Config::ORDINAL;
142}
143
144void CCodecBufferChannel::ReorderStash::flush() {
145 mPending.clear();
146 mStash.clear();
147}
148
149void CCodecBufferChannel::ReorderStash::setDepth(uint32_t depth) {
150 mPending.splice(mPending.end(), mStash);
151 mDepth = depth;
152}
153
154void CCodecBufferChannel::ReorderStash::setKey(C2Config::ordinal_key_t key) {
155 mPending.splice(mPending.end(), mStash);
156 mKey = key;
157}
158
159bool CCodecBufferChannel::ReorderStash::pop(Entry *entry) {
160 if (mPending.empty()) {
161 return false;
162 }
163 entry->buffer = mPending.front().buffer;
164 entry->timestamp = mPending.front().timestamp;
165 entry->flags = mPending.front().flags;
166 entry->ordinal = mPending.front().ordinal;
167 mPending.pop_front();
168 return true;
169}
170
171void CCodecBufferChannel::ReorderStash::emplace(
172 const std::shared_ptr<C2Buffer> &buffer,
173 int64_t timestamp,
174 int32_t flags,
175 const C2WorkOrdinalStruct &ordinal) {
176 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
177 if (!buffer && eos) {
178 // TRICKY: we may be violating ordering of the stash here. Because we
179 // don't expect any more emplace() calls after this, the ordering should
180 // not matter.
181 mStash.emplace_back(buffer, timestamp, flags, ordinal);
182 } else {
183 flags = flags & ~MediaCodec::BUFFER_FLAG_EOS;
184 auto it = mStash.begin();
185 for (; it != mStash.end(); ++it) {
186 if (less(ordinal, it->ordinal)) {
187 break;
188 }
189 }
190 mStash.emplace(it, buffer, timestamp, flags, ordinal);
191 if (eos) {
192 mStash.back().flags = mStash.back().flags | MediaCodec::BUFFER_FLAG_EOS;
193 }
194 }
195 while (!mStash.empty() && mStash.size() > mDepth) {
196 mPending.push_back(mStash.front());
197 mStash.pop_front();
198 }
199}
200
201void CCodecBufferChannel::ReorderStash::defer(
202 const CCodecBufferChannel::ReorderStash::Entry &entry) {
203 mPending.push_front(entry);
204}
205
206bool CCodecBufferChannel::ReorderStash::hasPending() const {
207 return !mPending.empty();
208}
209
210bool CCodecBufferChannel::ReorderStash::less(
211 const C2WorkOrdinalStruct &o1, const C2WorkOrdinalStruct &o2) {
212 switch (mKey) {
213 case C2Config::ORDINAL: return o1.frameIndex < o2.frameIndex;
214 case C2Config::TIMESTAMP: return o1.timestamp < o2.timestamp;
215 case C2Config::CUSTOM: return o1.customOrdinal < o2.customOrdinal;
216 default:
217 ALOGD("Unrecognized key; default to timestamp");
218 return o1.frameIndex < o2.frameIndex;
219 }
220}
221
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700222// Input
223
224CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
225
Pawin Vongmasa36653902018-11-15 00:10:25 -0800226// CCodecBufferChannel
227
228CCodecBufferChannel::CCodecBufferChannel(
229 const std::shared_ptr<CCodecCallback> &callback)
230 : mHeapSeqNum(-1),
231 mCCodecCallback(callback),
232 mFrameIndex(0u),
233 mFirstValidFrameIndex(0u),
234 mMetaMode(MODE_NONE),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800235 mInputMetEos(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700236 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700237 {
238 Mutexed<Input>::Locked input(mInput);
239 input->buffers.reset(new DummyInputBuffers(""));
240 input->extraBuffers.flush();
241 input->inputDelay = 0u;
242 input->pipelineDelay = 0u;
243 input->numSlots = kSmoothnessFactor;
244 input->numExtraSlots = 0u;
245 }
246 {
247 Mutexed<Output>::Locked output(mOutput);
248 output->outputDelay = 0u;
249 output->numSlots = kSmoothnessFactor;
250 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800251}
252
253CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800254 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800255 mCrypto->unsetHeap(mHeapSeqNum);
256 }
257}
258
259void CCodecBufferChannel::setComponent(
260 const std::shared_ptr<Codec2Client::Component> &component) {
261 mComponent = component;
262 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
263 mName = mComponentName.c_str();
264}
265
266status_t CCodecBufferChannel::setInputSurface(
267 const std::shared_ptr<InputSurfaceWrapper> &surface) {
268 ALOGV("[%s] setInputSurface", mName);
269 mInputSurface = surface;
270 return mInputSurface->connect(mComponent);
271}
272
273status_t CCodecBufferChannel::signalEndOfInputStream() {
274 if (mInputSurface == nullptr) {
275 return INVALID_OPERATION;
276 }
277 return mInputSurface->signalEndOfInputStream();
278}
279
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700280status_t CCodecBufferChannel::queueInputBufferInternal(sp<MediaCodecBuffer> buffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800281 int64_t timeUs;
282 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
283
284 if (mInputMetEos) {
285 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
286 return OK;
287 }
288
289 int32_t flags = 0;
290 int32_t tmp = 0;
291 bool eos = false;
292 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
293 eos = true;
294 mInputMetEos = true;
295 ALOGV("[%s] input EOS", mName);
296 }
297 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
298 flags |= C2FrameData::FLAG_CODEC_CONFIG;
299 }
300 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
301 std::unique_ptr<C2Work> work(new C2Work);
302 work->input.ordinal.timestamp = timeUs;
303 work->input.ordinal.frameIndex = mFrameIndex++;
304 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
305 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
306 // Keep client timestamp in customOrdinal
307 work->input.ordinal.customOrdinal = timeUs;
308 work->input.buffers.clear();
309
Wonsik Kimab34ed62019-01-31 15:28:46 -0800310 uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
311 std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700312 sp<Codec2Buffer> copy;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800313
Pawin Vongmasa36653902018-11-15 00:10:25 -0800314 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700315 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800316 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700317 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800318 return -ENOENT;
319 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700320 // TODO: we want to delay copying buffers.
321 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
322 copy = input->buffers->cloneAndReleaseBuffer(buffer);
323 if (copy != nullptr) {
324 (void)input->extraBuffers.assignSlot(copy);
325 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
326 return UNKNOWN_ERROR;
327 }
328 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
329 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
330 mName, released ? "" : "not ");
331 buffer.clear();
332 } else {
333 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
334 "buffer starvation on component.", mName);
335 }
336 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800337 work->input.buffers.push_back(c2buffer);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800338 queuedBuffers.push_back(c2buffer);
339 } else if (eos) {
340 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800341 }
342 work->input.flags = (C2FrameData::flags_t)flags;
343 // TODO: fill info's
344
345 work->input.configUpdate = std::move(mParamsToBeSet);
346 work->worklets.clear();
347 work->worklets.emplace_back(new C2Worklet);
348
349 std::list<std::unique_ptr<C2Work>> items;
350 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800351 mPipelineWatcher.lock()->onWorkQueued(
352 queuedFrameIndex,
353 std::move(queuedBuffers),
354 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800355 c2_status_t err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800356 if (err != C2_OK) {
357 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
358 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800359
360 if (err == C2_OK && eos && buffer->size() > 0u) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800361 work.reset(new C2Work);
362 work->input.ordinal.timestamp = timeUs;
363 work->input.ordinal.frameIndex = mFrameIndex++;
364 // WORKAROUND: keep client timestamp in customOrdinal
365 work->input.ordinal.customOrdinal = timeUs;
366 work->input.buffers.clear();
367 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800368 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800369
Wonsik Kimab34ed62019-01-31 15:28:46 -0800370 queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
371 queuedBuffers.clear();
372
Pawin Vongmasa36653902018-11-15 00:10:25 -0800373 items.clear();
374 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800375
376 mPipelineWatcher.lock()->onWorkQueued(
377 queuedFrameIndex,
378 std::move(queuedBuffers),
379 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800380 err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800381 if (err != C2_OK) {
382 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
383 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800384 }
385 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700386 Mutexed<Input>::Locked input(mInput);
387 bool released = false;
388 if (buffer) {
389 released = input->buffers->releaseBuffer(buffer, nullptr, true);
390 } else if (copy) {
391 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
392 }
393 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
394 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800395 }
396
397 feedInputBufferIfAvailableInternal();
398 return err;
399}
400
401status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
402 QueueGuard guard(mSync);
403 if (!guard.isRunning()) {
404 ALOGD("[%s] setParameters is only supported in the running state.", mName);
405 return -ENOSYS;
406 }
407 mParamsToBeSet.insert(mParamsToBeSet.end(),
408 std::make_move_iterator(params.begin()),
409 std::make_move_iterator(params.end()));
410 params.clear();
411 return OK;
412}
413
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800414status_t CCodecBufferChannel::attachBuffer(
415 const std::shared_ptr<C2Buffer> &c2Buffer,
416 const sp<MediaCodecBuffer> &buffer) {
417 if (!buffer->copy(c2Buffer)) {
418 return -ENOSYS;
419 }
420 return OK;
421}
422
423void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
424 if (!mDecryptDestination || mDecryptDestination->size() < size) {
425 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
426 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
427 mCrypto->unsetHeap(mHeapSeqNum);
428 }
429 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
430 if (mCrypto) {
431 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
432 }
433 }
434}
435
436int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
437 CHECK(mCrypto);
438 auto it = mHeapSeqNumMap.find(memory);
439 int32_t heapSeqNum = -1;
440 if (it == mHeapSeqNumMap.end()) {
441 heapSeqNum = mCrypto->setHeap(memory);
442 mHeapSeqNumMap.emplace(memory, heapSeqNum);
443 } else {
444 heapSeqNum = it->second;
445 }
446 return heapSeqNum;
447}
448
449status_t CCodecBufferChannel::attachEncryptedBuffer(
450 const sp<hardware::HidlMemory> &memory,
451 bool secure,
452 const uint8_t *key,
453 const uint8_t *iv,
454 CryptoPlugin::Mode mode,
455 CryptoPlugin::Pattern pattern,
456 size_t offset,
457 const CryptoPlugin::SubSample *subSamples,
458 size_t numSubSamples,
459 const sp<MediaCodecBuffer> &buffer) {
460 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
461 static const C2MemoryUsage kDefaultReadWriteUsage{
462 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
463
464 size_t size = 0;
465 for (size_t i = 0; i < numSubSamples; ++i) {
466 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
467 }
468 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
469 std::shared_ptr<C2LinearBlock> block;
470 c2_status_t err = pool->fetchLinearBlock(
471 size,
472 secure ? kSecureUsage : kDefaultReadWriteUsage,
473 &block);
474 if (err != C2_OK) {
475 return NO_MEMORY;
476 }
477 if (!secure) {
478 ensureDecryptDestination(size);
479 }
480 ssize_t result = -1;
481 ssize_t codecDataOffset = 0;
482 if (mCrypto) {
483 AString errorDetailMsg;
484 int32_t heapSeqNum = getHeapSeqNum(memory);
485 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
486 hardware::drm::V1_0::DestinationBuffer dst;
487 if (secure) {
488 dst.type = DrmBufferType::NATIVE_HANDLE;
489 dst.secureMemory = hardware::hidl_handle(block->handle());
490 } else {
491 dst.type = DrmBufferType::SHARED_MEMORY;
492 IMemoryToSharedBuffer(
493 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
494 }
495 result = mCrypto->decrypt(
496 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
497 dst, &errorDetailMsg);
498 if (result < 0) {
499 return result;
500 }
501 if (dst.type == DrmBufferType::SHARED_MEMORY) {
502 C2WriteView view = block->map().get();
503 if (view.error() != C2_OK) {
504 return false;
505 }
506 if (view.size() < result) {
507 return false;
508 }
509 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
510 }
511 } else {
512 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
513 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
514 hidl_vec<SubSample> hidlSubSamples;
515 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
516
517 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
518 hardware::cas::native::V1_0::DestinationBuffer dst;
519 if (secure) {
520 dst.type = BufferType::NATIVE_HANDLE;
521 dst.secureMemory = hardware::hidl_handle(block->handle());
522 } else {
523 dst.type = BufferType::SHARED_MEMORY;
524 dst.nonsecureMemory = src;
525 }
526
527 CasStatus status = CasStatus::OK;
528 hidl_string detailedError;
529 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
530
531 if (key != nullptr) {
532 sctrl = (ScramblingControl)key[0];
533 // Adjust for the PES offset
534 codecDataOffset = key[2] | (key[3] << 8);
535 }
536
537 auto returnVoid = mDescrambler->descramble(
538 sctrl,
539 hidlSubSamples,
540 src,
541 0,
542 dst,
543 0,
544 [&status, &result, &detailedError] (
545 CasStatus _status, uint32_t _bytesWritten,
546 const hidl_string& _detailedError) {
547 status = _status;
548 result = (ssize_t)_bytesWritten;
549 detailedError = _detailedError;
550 });
551
552 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
553 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
554 mName, returnVoid.description().c_str(), status, result);
555 return UNKNOWN_ERROR;
556 }
557
558 if (result < codecDataOffset) {
559 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
560 return BAD_VALUE;
561 }
562 }
563 if (!secure) {
564 C2WriteView view = block->map().get();
565 if (view.error() != C2_OK) {
566 return UNKNOWN_ERROR;
567 }
568 if (view.size() < result) {
569 return UNKNOWN_ERROR;
570 }
571 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
572 }
573 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
574 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
575 if (!buffer->copy(c2Buffer)) {
576 return -ENOSYS;
577 }
578 return OK;
579}
580
Pawin Vongmasa36653902018-11-15 00:10:25 -0800581status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
582 QueueGuard guard(mSync);
583 if (!guard.isRunning()) {
584 ALOGD("[%s] No more buffers should be queued at current state.", mName);
585 return -ENOSYS;
586 }
587 return queueInputBufferInternal(buffer);
588}
589
590status_t CCodecBufferChannel::queueSecureInputBuffer(
591 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
592 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
593 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
594 AString *errorDetailMsg) {
595 QueueGuard guard(mSync);
596 if (!guard.isRunning()) {
597 ALOGD("[%s] No more buffers should be queued at current state.", mName);
598 return -ENOSYS;
599 }
600
601 if (!hasCryptoOrDescrambler()) {
602 return -ENOSYS;
603 }
604 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
605
606 ssize_t result = -1;
607 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700608 if (numSubSamples == 1
609 && subSamples[0].mNumBytesOfClearData == 0
610 && subSamples[0].mNumBytesOfEncryptedData == 0) {
611 // We don't need to go through crypto or descrambler if the input is empty.
612 result = 0;
613 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700614 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800615 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700616 destination.type = DrmBufferType::NATIVE_HANDLE;
617 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800618 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700619 destination.type = DrmBufferType::SHARED_MEMORY;
620 IMemoryToSharedBuffer(
621 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800622 }
Robert Shih895fba92019-07-16 16:29:44 -0700623 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800624 encryptedBuffer->fillSourceBuffer(&source);
625 result = mCrypto->decrypt(
626 key, iv, mode, pattern, source, buffer->offset(),
627 subSamples, numSubSamples, destination, errorDetailMsg);
628 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700629 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800630 return result;
631 }
Robert Shih895fba92019-07-16 16:29:44 -0700632 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800633 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
634 }
635 } else {
636 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
637 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
638 hidl_vec<SubSample> hidlSubSamples;
639 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
640
641 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
642 encryptedBuffer->fillSourceBuffer(&srcBuffer);
643
644 DestinationBuffer dstBuffer;
645 if (secure) {
646 dstBuffer.type = BufferType::NATIVE_HANDLE;
647 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
648 } else {
649 dstBuffer.type = BufferType::SHARED_MEMORY;
650 dstBuffer.nonsecureMemory = srcBuffer;
651 }
652
653 CasStatus status = CasStatus::OK;
654 hidl_string detailedError;
655 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
656
657 if (key != nullptr) {
658 sctrl = (ScramblingControl)key[0];
659 // Adjust for the PES offset
660 codecDataOffset = key[2] | (key[3] << 8);
661 }
662
663 auto returnVoid = mDescrambler->descramble(
664 sctrl,
665 hidlSubSamples,
666 srcBuffer,
667 0,
668 dstBuffer,
669 0,
670 [&status, &result, &detailedError] (
671 CasStatus _status, uint32_t _bytesWritten,
672 const hidl_string& _detailedError) {
673 status = _status;
674 result = (ssize_t)_bytesWritten;
675 detailedError = _detailedError;
676 });
677
678 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
679 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
680 mName, returnVoid.description().c_str(), status, result);
681 return UNKNOWN_ERROR;
682 }
683
684 if (result < codecDataOffset) {
685 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
686 return BAD_VALUE;
687 }
688
689 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
690
691 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
692 encryptedBuffer->copyDecryptedContentFromMemory(result);
693 }
694 }
695
696 buffer->setRange(codecDataOffset, result - codecDataOffset);
697 return queueInputBufferInternal(buffer);
698}
699
700void CCodecBufferChannel::feedInputBufferIfAvailable() {
701 QueueGuard guard(mSync);
702 if (!guard.isRunning()) {
703 ALOGV("[%s] We're not running --- no input buffer reported", mName);
704 return;
705 }
706 feedInputBufferIfAvailableInternal();
707}
708
709void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800710 if (mInputMetEos ||
Wonsik Kima4e049d2020-04-28 19:42:23 +0000711 mReorderStash.lock()->hasPending() ||
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800712 mPipelineWatcher.lock()->pipelineFull()) {
713 return;
714 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700715 Mutexed<Output>::Locked output(mOutput);
716 if (output->buffers->numClientBuffers() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800717 return;
718 }
719 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700720 size_t numInputSlots = mInput.lock()->numSlots;
721 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800722 sp<MediaCodecBuffer> inBuffer;
723 size_t index;
724 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700725 Mutexed<Input>::Locked input(mInput);
726 if (input->buffers->numClientBuffers() >= input->numSlots) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800727 return;
728 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700729 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800730 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800731 break;
732 }
733 }
734 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
735 mCallback->onInputBufferAvailable(index, inBuffer);
736 }
737}
738
739status_t CCodecBufferChannel::renderOutputBuffer(
740 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800741 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800742 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800743 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800744 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700745 Mutexed<Output>::Locked output(mOutput);
746 if (output->buffers) {
747 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748 }
749 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800750 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
751 // set to true.
752 sendOutputBuffers();
753 // input buffer feeding may have been gated by pending output buffers
754 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800755 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800756 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700757 std::call_once(mRenderWarningFlag, [this] {
758 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
759 "timestamp or render=true with non-video buffers. Apps should "
760 "call releaseOutputBuffer() with render=false for those.",
761 mName);
762 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800763 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800764 return INVALID_OPERATION;
765 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800766
767#if 0
768 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
769 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
770 for (const std::shared_ptr<const C2Info> &info : infoParams) {
771 AString res;
772 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
773 if (ix) res.append(", ");
774 res.append(*((int32_t*)info.get() + (ix / 4)));
775 }
776 ALOGV(" [%s]", res.c_str());
777 }
778#endif
779 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
780 std::static_pointer_cast<const C2StreamRotationInfo::output>(
781 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
782 bool flip = rotation && (rotation->flip & 1);
783 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
784 uint32_t transform = 0;
785 switch (quarters) {
786 case 0: // no rotation
787 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
788 break;
789 case 1: // 90 degrees counter-clockwise
790 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
791 : HAL_TRANSFORM_ROT_270;
792 break;
793 case 2: // 180 degrees
794 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
795 break;
796 case 3: // 90 degrees clockwise
797 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
798 : HAL_TRANSFORM_ROT_90;
799 break;
800 }
801
802 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
803 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
804 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
805 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
806 if (surfaceScaling) {
807 videoScalingMode = surfaceScaling->value;
808 }
809
810 // Use dataspace from format as it has the default aspects already applied
811 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
812 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
813
814 // HDR static info
815 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
816 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
817 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
818
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800819 // HDR10 plus info
820 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
821 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
822 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
823
Pawin Vongmasa36653902018-11-15 00:10:25 -0800824 {
825 Mutexed<OutputSurface>::Locked output(mOutputSurface);
826 if (output->surface == nullptr) {
827 ALOGI("[%s] cannot render buffer without surface", mName);
828 return OK;
829 }
830 }
831
832 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
833 if (blocks.size() != 1u) {
834 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
835 return UNKNOWN_ERROR;
836 }
837 const C2ConstGraphicBlock &block = blocks.front();
838
839 // TODO: revisit this after C2Fence implementation.
840 android::IGraphicBufferProducer::QueueBufferInput qbi(
841 timestampNs,
842 false, // droppable
843 dataSpace,
844 Rect(blocks.front().crop().left,
845 blocks.front().crop().top,
846 blocks.front().crop().right(),
847 blocks.front().crop().bottom()),
848 videoScalingMode,
849 transform,
850 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800851 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800852 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800853 if (hdrStaticInfo) {
854 struct android_smpte2086_metadata smpte2086_meta = {
855 .displayPrimaryRed = {
856 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
857 },
858 .displayPrimaryGreen = {
859 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
860 },
861 .displayPrimaryBlue = {
862 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
863 },
864 .whitePoint = {
865 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
866 },
867 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
868 .minLuminance = hdrStaticInfo->mastering.minLuminance,
869 };
870
871 struct android_cta861_3_metadata cta861_meta = {
872 .maxContentLightLevel = hdrStaticInfo->maxCll,
873 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
874 };
875
876 hdr.validTypes = HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3;
877 hdr.smpte2086 = smpte2086_meta;
878 hdr.cta8613 = cta861_meta;
879 }
880 if (hdr10PlusInfo) {
881 hdr.validTypes |= HdrMetadata::HDR10PLUS;
882 hdr.hdr10plus.assign(
883 hdr10PlusInfo->m.value,
884 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
885 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800886 qbi.setHdrMetadata(hdr);
887 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800888 // we don't have dirty regions
889 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800890 android::IGraphicBufferProducer::QueueBufferOutput qbo;
891 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
892 if (result != OK) {
893 ALOGI("[%s] queueBuffer failed: %d", mName, result);
894 return result;
895 }
896 ALOGV("[%s] queue buffer successful", mName);
897
898 int64_t mediaTimeUs = 0;
899 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
900 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
901
902 return OK;
903}
904
905status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
906 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
907 bool released = false;
908 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700909 Mutexed<Input>::Locked input(mInput);
910 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800911 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800912 }
913 }
914 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700915 Mutexed<Output>::Locked output(mOutput);
916 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800917 released = true;
918 }
919 }
920 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800921 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800922 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800923 } else {
924 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
925 }
926 return OK;
927}
928
929void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
930 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700931 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800932
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700933 if (!input->buffers->isArrayMode()) {
934 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800935 }
936
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700937 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800938}
939
940void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
941 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700942 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800943
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700944 if (!output->buffers->isArrayMode()) {
945 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800946 }
947
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700948 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800949}
950
951status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800952 const sp<AMessage> &inputFormat,
953 const sp<AMessage> &outputFormat,
954 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800955 C2StreamBufferTypeSetting::input iStreamFormat(0u);
956 C2StreamBufferTypeSetting::output oStreamFormat(0u);
957 C2PortReorderBufferDepthTuning::output reorderDepth;
958 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800959 C2PortActualDelayTuning::input inputDelay(0);
960 C2PortActualDelayTuning::output outputDelay(0);
961 C2ActualPipelineDelayTuning pipelineDelay(0);
962
Pawin Vongmasa36653902018-11-15 00:10:25 -0800963 c2_status_t err = mComponent->query(
964 {
965 &iStreamFormat,
966 &oStreamFormat,
967 &reorderDepth,
968 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800969 &inputDelay,
970 &pipelineDelay,
971 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800972 },
973 {},
974 C2_DONT_BLOCK,
975 nullptr);
976 if (err == C2_BAD_INDEX) {
977 if (!iStreamFormat || !oStreamFormat) {
978 return UNKNOWN_ERROR;
979 }
980 } else if (err != C2_OK) {
981 return UNKNOWN_ERROR;
982 }
983
Wonsik Kima4e049d2020-04-28 19:42:23 +0000984 {
985 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
986 reorder->clear();
987 if (reorderDepth) {
988 reorder->setDepth(reorderDepth.value);
989 }
990 if (reorderKey) {
991 reorder->setKey(reorderKey.value);
992 }
993 }
994
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800995 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
996 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
997 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
998
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700999 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1000 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001001
Pawin Vongmasa36653902018-11-15 00:10:25 -08001002 // TODO: get this from input format
1003 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1004
1005 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001006 int poolMask = GetCodec2PoolMask();
1007 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001008
1009 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001010 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001011 std::shared_ptr<C2BlockPool> pool;
1012 {
1013 Mutexed<BlockPools>::Locked pools(mBlockPools);
1014
1015 // set default allocator ID.
1016 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001017 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001018
1019 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1020 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1021 std::vector<std::unique_ptr<C2Param>> params;
1022 err = mComponent->query({ },
1023 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1024 C2_DONT_BLOCK,
1025 &params);
1026 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1027 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1028 mName, params.size(), asString(err), err);
1029 } else if (err == C2_OK && params.size() == 1) {
1030 C2PortAllocatorsTuning::input *inputAllocators =
1031 C2PortAllocatorsTuning::input::From(params[0].get());
1032 if (inputAllocators && inputAllocators->flexCount() > 0) {
1033 std::shared_ptr<C2Allocator> allocator;
1034 // verify allocator IDs and resolve default allocator
1035 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1036 if (allocator) {
1037 pools->inputAllocatorId = allocator->getId();
1038 } else {
1039 ALOGD("[%s] component requested invalid input allocator ID %u",
1040 mName, inputAllocators->m.values[0]);
1041 }
1042 }
1043 }
1044
1045 // TODO: use C2Component wrapper to associate this pool with ourselves
1046 if ((poolMask >> pools->inputAllocatorId) & 1) {
1047 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1048 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1049 mName, pools->inputAllocatorId,
1050 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1051 asString(err), err);
1052 } else {
1053 err = C2_NOT_FOUND;
1054 }
1055 if (err != C2_OK) {
1056 C2BlockPool::local_id_t inputPoolId =
1057 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1058 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1059 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1060 mName, (unsigned long long)inputPoolId,
1061 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1062 asString(err), err);
1063 if (err != C2_OK) {
1064 return NO_MEMORY;
1065 }
1066 }
1067 pools->inputPool = pool;
1068 }
1069
Wonsik Kim51051262018-11-28 13:59:05 -08001070 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001071 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001072 input->inputDelay = inputDelayValue;
1073 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001074 input->numSlots = numInputSlots;
1075 input->extraBuffers.flush();
1076 input->numExtraSlots = 0u;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001077 if (!buffersBoundToCodec) {
1078 input->buffers.reset(new SlotInputBuffers(mName));
1079 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001080 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001081 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001082 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001083 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001084 // This is to ensure buffers do not get released prematurely.
1085 // TODO: handle this without going into array mode
1086 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001087 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001088 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001089 }
1090 } else {
1091 if (hasCryptoOrDescrambler()) {
1092 int32_t capacity = kLinearBufferSize;
1093 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1094 if ((size_t)capacity > kMaxLinearBufferSize) {
1095 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1096 capacity = kMaxLinearBufferSize;
1097 }
1098 if (mDealer == nullptr) {
1099 mDealer = new MemoryDealer(
1100 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001101 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001102 "EncryptedLinearInputBuffers");
1103 mDecryptDestination = mDealer->allocate((size_t)capacity);
1104 }
1105 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001106 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1107 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001108 } else {
1109 mHeapSeqNum = -1;
1110 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001111 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001112 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001113 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001114 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001115 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001116 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001117 }
1118 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001119 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001120
1121 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001122 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001123 } else {
1124 // TODO: error
1125 }
Wonsik Kim51051262018-11-28 13:59:05 -08001126
1127 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001128 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001129 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001130 }
1131
1132 if (outputFormat != nullptr) {
1133 sp<IGraphicBufferProducer> outputSurface;
1134 uint32_t outputGeneration;
1135 {
1136 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001137 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001138 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001139 if (!secure) {
1140 output->maxDequeueBuffers += numInputSlots;
1141 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001142 outputSurface = output->surface ?
1143 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001144 if (outputSurface) {
1145 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1146 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001147 outputGeneration = output->generation;
1148 }
1149
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001150 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001151 C2BlockPool::local_id_t outputPoolId_;
1152
1153 {
1154 Mutexed<BlockPools>::Locked pools(mBlockPools);
1155
1156 // set default allocator ID.
1157 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001158 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001159
1160 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1161 // unsuccessful.
1162 std::vector<std::unique_ptr<C2Param>> params;
1163 err = mComponent->query({ },
1164 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1165 C2_DONT_BLOCK,
1166 &params);
1167 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1168 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1169 mName, params.size(), asString(err), err);
1170 } else if (err == C2_OK && params.size() == 1) {
1171 C2PortAllocatorsTuning::output *outputAllocators =
1172 C2PortAllocatorsTuning::output::From(params[0].get());
1173 if (outputAllocators && outputAllocators->flexCount() > 0) {
1174 std::shared_ptr<C2Allocator> allocator;
1175 // verify allocator IDs and resolve default allocator
1176 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1177 if (allocator) {
1178 pools->outputAllocatorId = allocator->getId();
1179 } else {
1180 ALOGD("[%s] component requested invalid output allocator ID %u",
1181 mName, outputAllocators->m.values[0]);
1182 }
1183 }
1184 }
1185
1186 // use bufferqueue if outputting to a surface.
1187 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1188 // if unsuccessful.
1189 if (outputSurface) {
1190 params.clear();
1191 err = mComponent->query({ },
1192 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1193 C2_DONT_BLOCK,
1194 &params);
1195 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1196 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1197 mName, params.size(), asString(err), err);
1198 } else if (err == C2_OK && params.size() == 1) {
1199 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1200 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1201 if (surfaceAllocator) {
1202 std::shared_ptr<C2Allocator> allocator;
1203 // verify allocator IDs and resolve default allocator
1204 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1205 if (allocator) {
1206 pools->outputAllocatorId = allocator->getId();
1207 } else {
1208 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1209 mName, surfaceAllocator->value);
1210 err = C2_BAD_VALUE;
1211 }
1212 }
1213 }
1214 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1215 && err != C2_OK
1216 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1217 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1218 }
1219 }
1220
1221 if ((poolMask >> pools->outputAllocatorId) & 1) {
1222 err = mComponent->createBlockPool(
1223 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1224 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1225 mName, pools->outputAllocatorId,
1226 (unsigned long long)pools->outputPoolId,
1227 asString(err));
1228 } else {
1229 err = C2_NOT_FOUND;
1230 }
1231 if (err != C2_OK) {
1232 // use basic pool instead
1233 pools->outputPoolId =
1234 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1235 }
1236
1237 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1238 // component.
1239 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1240 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1241
1242 std::vector<std::unique_ptr<C2SettingResult>> failures;
1243 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1244 ALOGD("[%s] Configured output block pool ids %llu => %s",
1245 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1246 outputPoolId_ = pools->outputPoolId;
1247 }
1248
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001249 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001250 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001251 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001252 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001253 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001254 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001255 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001256 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001257 }
1258 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001259 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001260 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001261 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001262
1263
1264 // Try to set output surface to created block pool if given.
1265 if (outputSurface) {
1266 mComponent->setOutputSurface(
1267 outputPoolId_,
1268 outputSurface,
1269 outputGeneration);
1270 }
1271
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001272 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001273 if (buffersBoundToCodec) {
1274 // WORKAROUND: if we're using early CSD workaround we convert to
1275 // array mode, to appease apps assuming the output
1276 // buffers to be of the same size.
1277 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1278 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001279
1280 int32_t channelCount;
1281 int32_t sampleRate;
1282 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1283 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1284 int32_t delay = 0;
1285 int32_t padding = 0;;
1286 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1287 delay = 0;
1288 }
1289 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1290 padding = 0;
1291 }
1292 if (delay || padding) {
1293 // We need write access to the buffers, and we're already in
1294 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001295 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001296 }
1297 }
1298 }
1299 }
1300
1301 // Set up pipeline control. This has to be done after mInputBuffers and
1302 // mOutputBuffers are initialized to make sure that lingering callbacks
1303 // about buffers from the previous generation do not interfere with the
1304 // newly initialized pipeline capacity.
1305
Wonsik Kimab34ed62019-01-31 15:28:46 -08001306 {
1307 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001308 watcher->inputDelay(inputDelayValue)
1309 .pipelineDelay(pipelineDelayValue)
1310 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001311 .smoothnessFactor(kSmoothnessFactor);
1312 watcher->flush();
1313 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001314
1315 mInputMetEos = false;
1316 mSync.start();
1317 return OK;
1318}
1319
1320status_t CCodecBufferChannel::requestInitialInputBuffers() {
1321 if (mInputSurface) {
1322 return OK;
1323 }
1324
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001325 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001326 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1327 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1328 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001329 return UNKNOWN_ERROR;
1330 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001331 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001332 std::vector<sp<MediaCodecBuffer>> toBeQueued;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001333 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001334 size_t index;
1335 sp<MediaCodecBuffer> buffer;
1336 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001337 Mutexed<Input>::Locked input(mInput);
1338 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001339 if (i == 0) {
1340 ALOGW("[%s] start: cannot allocate memory at all", mName);
1341 return NO_MEMORY;
1342 } else {
1343 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
1344 mName, i);
1345 }
1346 break;
1347 }
1348 }
1349 if (buffer) {
1350 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1351 ALOGV("[%s] input buffer %zu available", mName, index);
1352 bool post = true;
1353 if (!configs->empty()) {
1354 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001355 configs->pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001356 if (buffer->capacity() >= config->size()) {
1357 memcpy(buffer->base(), config->data(), config->size());
1358 buffer->setRange(0, config->size());
1359 buffer->meta()->clear();
1360 buffer->meta()->setInt64("timeUs", 0);
1361 buffer->meta()->setInt32("csd", 1);
1362 post = false;
1363 } else {
1364 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
1365 mName, buffer->capacity(), config->size());
1366 }
1367 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001368 && (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001369 // WORKAROUND: Some apps expect CSD available without queueing
1370 // any input. Queue an empty buffer to get the CSD.
1371 buffer->setRange(0, 0);
1372 buffer->meta()->clear();
1373 buffer->meta()->setInt64("timeUs", 0);
1374 post = false;
1375 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001376 if (post) {
1377 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001378 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001379 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001380 }
1381 }
1382 }
1383 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
1384 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001385 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001386 }
1387 }
1388 return OK;
1389}
1390
1391void CCodecBufferChannel::stop() {
1392 mSync.stop();
1393 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1394 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001395 mInputSurface.reset();
1396 }
1397}
1398
1399void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1400 ALOGV("[%s] flush", mName);
1401 {
1402 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1403 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1404 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1405 continue;
1406 }
1407 if (work->input.buffers.empty()
1408 || work->input.buffers.front()->data().linearBlocks().empty()) {
1409 ALOGD("[%s] no linear codec config data found", mName);
1410 continue;
1411 }
1412 C2ReadView view =
1413 work->input.buffers.front()->data().linearBlocks().front().map().get();
1414 if (view.error() != C2_OK) {
1415 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1416 continue;
1417 }
1418 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1419 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1420 }
1421 }
1422 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001423 Mutexed<Input>::Locked input(mInput);
1424 input->buffers->flush();
1425 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001426 }
1427 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001428 Mutexed<Output>::Locked output(mOutput);
1429 output->buffers->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001430 }
Wonsik Kima4e049d2020-04-28 19:42:23 +00001431 mReorderStash.lock()->flush();
Wonsik Kimab34ed62019-01-31 15:28:46 -08001432 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001433}
1434
1435void CCodecBufferChannel::onWorkDone(
1436 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001437 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001438 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001439 feedInputBufferIfAvailable();
1440 }
1441}
1442
1443void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001444 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001445 if (mInputSurface) {
1446 return;
1447 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001448 std::shared_ptr<C2Buffer> buffer =
1449 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001450 bool newInputSlotAvailable;
1451 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001452 Mutexed<Input>::Locked input(mInput);
1453 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1454 if (!newInputSlotAvailable) {
1455 (void)input->extraBuffers.expireComponentBuffer(buffer);
1456 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001457 }
1458 if (newInputSlotAvailable) {
1459 feedInputBufferIfAvailable();
1460 }
1461}
1462
1463bool CCodecBufferChannel::handleWork(
1464 std::unique_ptr<C2Work> work,
1465 const sp<AMessage> &outputFormat,
1466 const C2StreamInitDataInfo::output *initData) {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001467 if (outputFormat != nullptr) {
1468 Mutexed<Output>::Locked output(mOutput);
1469 ALOGD("[%s] onWorkDone: output format changed to %s",
1470 mName, outputFormat->debugString().c_str());
1471 output->buffers->setFormat(outputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001472
Wonsik Kima4e049d2020-04-28 19:42:23 +00001473 AString mediaType;
1474 if (outputFormat->findString(KEY_MIME, &mediaType)
1475 && mediaType == MIMETYPE_AUDIO_RAW) {
1476 int32_t channelCount;
1477 int32_t sampleRate;
1478 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1479 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1480 output->buffers->updateSkipCutBuffer(sampleRate, channelCount);
1481 }
1482 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001483 }
1484
Wonsik Kima4e049d2020-04-28 19:42:23 +00001485 if ((work->input.ordinal.frameIndex - mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001486 // Discard frames from previous generation.
1487 ALOGD("[%s] Discard frames from previous generation.", mName);
Wonsik Kima4e049d2020-04-28 19:42:23 +00001488 return false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001489 }
1490
Wonsik Kim524b0582019-03-12 11:28:57 -07001491 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001492 || !work->worklets.front()
Wonsik Kima4e049d2020-04-28 19:42:23 +00001493 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE))) {
1494 mPipelineWatcher.lock()->onWorkDone(work->input.ordinal.frameIndex.peeku());
1495 }
1496
1497 if (work->result == C2_NOT_FOUND) {
1498 ALOGD("[%s] flushed work; ignored.", mName);
1499 return true;
1500 }
1501
1502 if (work->result != C2_OK) {
1503 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1504 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1505 return false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001506 }
1507
1508 // NOTE: MediaCodec usage supposedly have only one worklet
1509 if (work->worklets.size() != 1u) {
1510 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1511 mName, work->worklets.size());
1512 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1513 return false;
1514 }
1515
1516 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1517
1518 std::shared_ptr<C2Buffer> buffer;
1519 // NOTE: MediaCodec usage supposedly have only one output stream.
1520 if (worklet->output.buffers.size() > 1u) {
1521 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1522 mName, worklet->output.buffers.size());
1523 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1524 return false;
1525 } else if (worklet->output.buffers.size() == 1u) {
1526 buffer = worklet->output.buffers[0];
1527 if (!buffer) {
1528 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1529 }
1530 }
1531
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001532 std::optional<uint32_t> newInputDelay, newPipelineDelay;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001533 while (!worklet->output.configUpdate.empty()) {
1534 std::unique_ptr<C2Param> param;
1535 worklet->output.configUpdate.back().swap(param);
1536 worklet->output.configUpdate.pop_back();
1537 switch (param->coreIndex().coreIndex()) {
1538 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1539 C2PortReorderBufferDepthTuning::output reorderDepth;
1540 if (reorderDepth.updateFrom(*param)) {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001541 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1542 mReorderStash.lock()->setDepth(reorderDepth.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001543 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1544 mName, reorderDepth.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001545 size_t numOutputSlots = mOutput.lock()->numSlots;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001546 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001547 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001548 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001549 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001550 if (!secure) {
1551 output->maxDequeueBuffers += numInputSlots;
1552 }
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001553 if (output->surface) {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001554 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001555 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001556 } else {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001557 ALOGD("[%s] onWorkDone: failed to read reorder depth", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001558 }
1559 break;
1560 }
1561 case C2PortReorderKeySetting::CORE_INDEX: {
1562 C2PortReorderKeySetting::output reorderKey;
1563 if (reorderKey.updateFrom(*param)) {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001564 mReorderStash.lock()->setKey(reorderKey.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001565 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1566 mName, reorderKey.value);
1567 } else {
1568 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1569 }
1570 break;
1571 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001572 case C2PortActualDelayTuning::CORE_INDEX: {
1573 if (param->isGlobal()) {
1574 C2ActualPipelineDelayTuning pipelineDelay;
1575 if (pipelineDelay.updateFrom(*param)) {
1576 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1577 mName, pipelineDelay.value);
1578 newPipelineDelay = pipelineDelay.value;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001579 (void)mPipelineWatcher.lock()->pipelineDelay(pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001580 }
1581 }
1582 if (param->forInput()) {
1583 C2PortActualDelayTuning::input inputDelay;
1584 if (inputDelay.updateFrom(*param)) {
1585 ALOGV("[%s] onWorkDone: updating input delay %u",
1586 mName, inputDelay.value);
1587 newInputDelay = inputDelay.value;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001588 (void)mPipelineWatcher.lock()->inputDelay(inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001589 }
1590 }
1591 if (param->forOutput()) {
1592 C2PortActualDelayTuning::output outputDelay;
1593 if (outputDelay.updateFrom(*param)) {
1594 ALOGV("[%s] onWorkDone: updating output delay %u",
1595 mName, outputDelay.value);
Wonsik Kima4e049d2020-04-28 19:42:23 +00001596 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1597 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001598
1599 bool outputBuffersChanged = false;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001600 size_t numOutputSlots = 0;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001601 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001602 {
1603 Mutexed<Output>::Locked output(mOutput);
1604 output->outputDelay = outputDelay.value;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001605 numOutputSlots = outputDelay.value + kSmoothnessFactor;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001606 if (output->numSlots < numOutputSlots) {
1607 output->numSlots = numOutputSlots;
1608 if (output->buffers->isArrayMode()) {
1609 OutputBuffersArray *array =
1610 (OutputBuffersArray *)output->buffers.get();
1611 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1612 mName, numOutputSlots);
1613 array->grow(numOutputSlots);
1614 outputBuffersChanged = true;
1615 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001616 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001617 numOutputSlots = output->numSlots;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001618 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001619
1620 if (outputBuffersChanged) {
1621 mCCodecCallback->onOutputBuffersChanged();
1622 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001623
Wonsik Kima4e049d2020-04-28 19:42:23 +00001624 uint32_t depth = mReorderStash.lock()->depth();
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001625 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001626 output->maxDequeueBuffers = numOutputSlots + depth + kRenderingDepth;
1627 if (!secure) {
1628 output->maxDequeueBuffers += numInputSlots;
1629 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001630 if (output->surface) {
1631 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1632 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001633 }
1634 }
1635 break;
1636 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001637 default:
1638 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1639 mName, param->index());
1640 break;
1641 }
1642 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001643 if (newInputDelay || newPipelineDelay) {
1644 Mutexed<Input>::Locked input(mInput);
1645 size_t newNumSlots =
1646 newInputDelay.value_or(input->inputDelay) +
1647 newPipelineDelay.value_or(input->pipelineDelay) +
1648 kSmoothnessFactor;
1649 if (input->buffers->isArrayMode()) {
1650 if (input->numSlots >= newNumSlots) {
1651 input->numExtraSlots = 0;
1652 } else {
1653 input->numExtraSlots = newNumSlots - input->numSlots;
1654 }
1655 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1656 mName, input->numExtraSlots);
1657 } else {
1658 input->numSlots = newNumSlots;
1659 }
1660 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001661
Pawin Vongmasa36653902018-11-15 00:10:25 -08001662 int32_t flags = 0;
1663 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1664 flags |= MediaCodec::BUFFER_FLAG_EOS;
1665 ALOGV("[%s] onWorkDone: output EOS", mName);
1666 }
1667
Wonsik Kima4e049d2020-04-28 19:42:23 +00001668 sp<MediaCodecBuffer> outBuffer;
1669 size_t index;
1670
Pawin Vongmasa36653902018-11-15 00:10:25 -08001671 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1672 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1673 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1674 // shall correspond to the client input timesamp (in customOrdinal). By using the
1675 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1676 // produces multiple output.
1677 c2_cntr64_t timestamp =
1678 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1679 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001680 if (mInputSurface != nullptr) {
1681 // When using input surface we need to restore the original input timestamp.
1682 timestamp = work->input.ordinal.customOrdinal;
1683 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001684 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1685 mName,
1686 work->input.ordinal.customOrdinal.peekll(),
1687 work->input.ordinal.timestamp.peekll(),
1688 worklet->output.ordinal.timestamp.peekll(),
1689 timestamp.peekll());
1690
1691 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001692 Mutexed<Output>::Locked output(mOutput);
1693 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001694 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1695 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1696 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1697
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001698 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001699 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001700 } else {
1701 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001702 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001703 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001704 return false;
1705 }
1706 }
1707
Wonsik Kim910a3172020-04-29 16:58:16 -07001708 if (!buffer && !flags && outputFormat == nullptr) {
1709 ALOGV("[%s] onWorkDone: nothing to report from the work (%lld)",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001710 mName, work->input.ordinal.frameIndex.peekull());
Wonsik Kima4e049d2020-04-28 19:42:23 +00001711 return true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001712 }
1713
1714 if (buffer) {
1715 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1716 // TODO: properly translate these to metadata
1717 switch (info->coreIndex().coreIndex()) {
1718 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001719 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001720 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1721 }
1722 break;
1723 default:
1724 break;
1725 }
1726 }
1727 }
1728
1729 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001730 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1731 reorder->emplace(buffer, timestamp.peek(), flags, worklet->output.ordinal);
1732 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
1733 // Flush reorder stash
1734 reorder->setDepth(0);
1735 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001736 }
1737 sendOutputBuffers();
1738 return true;
1739}
1740
1741void CCodecBufferChannel::sendOutputBuffers() {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001742 ReorderStash::Entry entry;
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001743 sp<MediaCodecBuffer> outBuffer;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001744 size_t index;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001745
1746 while (true) {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001747 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1748 if (!reorder->hasPending()) {
1749 break;
1750 }
1751 if (!reorder->pop(&entry)) {
1752 break;
1753 }
1754
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001755 Mutexed<Output>::Locked output(mOutput);
Wonsik Kima4e049d2020-04-28 19:42:23 +00001756 status_t err = output->buffers->registerBuffer(entry.buffer, &index, &outBuffer);
1757 if (err != OK) {
1758 bool outputBuffersChanged = false;
1759 if (err != WOULD_BLOCK) {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001760 if (!output->buffers->isArrayMode()) {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001761 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001762 }
Wonsik Kima4e049d2020-04-28 19:42:23 +00001763 OutputBuffersArray *array = (OutputBuffersArray *)output->buffers.get();
1764 array->realloc(entry.buffer);
1765 outputBuffersChanged = true;
1766 }
1767 ALOGV("[%s] sendOutputBuffers: unable to register output buffer", mName);
1768 reorder->defer(entry);
1769
1770 output.unlock();
1771 reorder.unlock();
1772
1773 if (outputBuffersChanged) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001774 mCCodecCallback->onOutputBuffersChanged();
1775 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001776 return;
1777 }
Wonsik Kima4e049d2020-04-28 19:42:23 +00001778 output.unlock();
1779 reorder.unlock();
1780
1781 outBuffer->meta()->setInt64("timeUs", entry.timestamp);
1782 outBuffer->meta()->setInt32("flags", entry.flags);
1783 ALOGV("[%s] sendOutputBuffers: out buffer index = %zu [%p] => %p + %zu (%lld)",
1784 mName, index, outBuffer.get(), outBuffer->data(), outBuffer->size(),
1785 (long long)entry.timestamp);
1786 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001787 }
1788}
1789
1790status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1791 static std::atomic_uint32_t surfaceGeneration{0};
1792 uint32_t generation = (getpid() << 10) |
1793 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1794 & ((1 << 10) - 1));
1795
1796 sp<IGraphicBufferProducer> producer;
1797 if (newSurface) {
1798 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001799 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Lee08515812019-06-05 11:16:32 -07001800 newSurface->setMaxDequeuedBufferCount(mOutputSurface.lock()->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001801 producer = newSurface->getIGraphicBufferProducer();
1802 producer->setGenerationNumber(generation);
1803 } else {
1804 ALOGE("[%s] setting output surface to null", mName);
1805 return INVALID_OPERATION;
1806 }
1807
1808 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1809 C2BlockPool::local_id_t outputPoolId;
1810 {
1811 Mutexed<BlockPools>::Locked pools(mBlockPools);
1812 outputPoolId = pools->outputPoolId;
1813 outputPoolIntf = pools->outputPoolIntf;
1814 }
1815
1816 if (outputPoolIntf) {
1817 if (mComponent->setOutputSurface(
1818 outputPoolId,
1819 producer,
1820 generation) != C2_OK) {
1821 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1822 return INVALID_OPERATION;
1823 }
1824 }
1825
1826 {
1827 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1828 output->surface = newSurface;
1829 output->generation = generation;
1830 }
1831
1832 return OK;
1833}
1834
Wonsik Kimab34ed62019-01-31 15:28:46 -08001835PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001836 // When client pushed EOS, we want all the work to be done quickly.
1837 // Otherwise, component may have stalled work due to input starvation up to
1838 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001839 size_t n = 0;
1840 if (!mInputMetEos) {
1841 size_t outputDelay = mOutput.lock()->outputDelay;
1842 Mutexed<Input>::Locked input(mInput);
1843 n = input->inputDelay + input->pipelineDelay + outputDelay;
1844 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001845 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001846}
1847
Pawin Vongmasa36653902018-11-15 00:10:25 -08001848void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1849 mMetaMode = mode;
1850}
1851
Wonsik Kim596187e2019-10-25 12:44:10 -07001852void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001853 if (mCrypto != nullptr) {
1854 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
1855 mCrypto->unsetHeap(entry.second);
1856 }
1857 mHeapSeqNumMap.clear();
1858 if (mHeapSeqNum >= 0) {
1859 mCrypto->unsetHeap(mHeapSeqNum);
1860 mHeapSeqNum = -1;
1861 }
1862 }
Wonsik Kim596187e2019-10-25 12:44:10 -07001863 mCrypto = crypto;
1864}
1865
1866void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
1867 mDescrambler = descrambler;
1868}
1869
Pawin Vongmasa36653902018-11-15 00:10:25 -08001870status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1871 // C2_OK is always translated to OK.
1872 if (c2s == C2_OK) {
1873 return OK;
1874 }
1875
1876 // Operation-dependent translation
1877 // TODO: Add as necessary
1878 switch (c2op) {
1879 case C2_OPERATION_Component_start:
1880 switch (c2s) {
1881 case C2_NO_MEMORY:
1882 return NO_MEMORY;
1883 default:
1884 return UNKNOWN_ERROR;
1885 }
1886 default:
1887 break;
1888 }
1889
1890 // Backup operation-agnostic translation
1891 switch (c2s) {
1892 case C2_BAD_INDEX:
1893 return BAD_INDEX;
1894 case C2_BAD_VALUE:
1895 return BAD_VALUE;
1896 case C2_BLOCKING:
1897 return WOULD_BLOCK;
1898 case C2_DUPLICATE:
1899 return ALREADY_EXISTS;
1900 case C2_NO_INIT:
1901 return NO_INIT;
1902 case C2_NO_MEMORY:
1903 return NO_MEMORY;
1904 case C2_NOT_FOUND:
1905 return NAME_NOT_FOUND;
1906 case C2_TIMED_OUT:
1907 return TIMED_OUT;
1908 case C2_BAD_STATE:
1909 case C2_CANCELED:
1910 case C2_CANNOT_DO:
1911 case C2_CORRUPTED:
1912 case C2_OMITTED:
1913 case C2_REFUSED:
1914 return UNKNOWN_ERROR;
1915 default:
1916 return -static_cast<status_t>(c2s);
1917 }
1918}
1919
1920} // namespace android