blob: e85e73a62d4fe4c0e0835ffbd069eb83618461e1 [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>
47#include <system/window.h>
48
49#include "CCodecBufferChannel.h"
50#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080051
52namespace android {
53
54using android::base::StringPrintf;
55using hardware::hidl_handle;
56using hardware::hidl_string;
57using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070058using hardware::fromHeap;
59using hardware::HidlMemory;
60
Pawin Vongmasa36653902018-11-15 00:10:25 -080061using namespace hardware::cas::V1_0;
62using namespace hardware::cas::native::V1_0;
63
64using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070065using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080066
Pawin Vongmasa36653902018-11-15 00:10:25 -080067namespace {
68
Wonsik Kim469c8342019-04-11 16:46:09 -070069constexpr size_t kSmoothnessFactor = 4;
70constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080071
Sungtak Leeab6f2f32019-02-15 14:43:51 -080072// This is for keeping IGBP's buffer dropping logic in legacy mode other
73// than making it non-blocking. Do not change this value.
74const static size_t kDequeueTimeoutNs = 0;
75
Pawin Vongmasa36653902018-11-15 00:10:25 -080076} // namespace
77
78CCodecBufferChannel::QueueGuard::QueueGuard(
79 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
80 Mutex::Autolock l(mSync.mGuardLock);
81 // At this point it's guaranteed that mSync is not under state transition,
82 // as we are holding its mutex.
83
84 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
85 if (count->value == -1) {
86 mRunning = false;
87 } else {
88 ++count->value;
89 mRunning = true;
90 }
91}
92
93CCodecBufferChannel::QueueGuard::~QueueGuard() {
94 if (mRunning) {
95 // We are not holding mGuardLock at this point so that QueueSync::stop() can
96 // keep holding the lock until mCount reaches zero.
97 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
98 --count->value;
99 count->cond.broadcast();
100 }
101}
102
103void CCodecBufferChannel::QueueSync::start() {
104 Mutex::Autolock l(mGuardLock);
105 // If stopped, it goes to running state; otherwise no-op.
106 Mutexed<Counter>::Locked count(mCount);
107 if (count->value == -1) {
108 count->value = 0;
109 }
110}
111
112void CCodecBufferChannel::QueueSync::stop() {
113 Mutex::Autolock l(mGuardLock);
114 Mutexed<Counter>::Locked count(mCount);
115 if (count->value == -1) {
116 // no-op
117 return;
118 }
119 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
120 // mCount can only decrement. In other words, threads that acquired the lock
121 // are allowed to finish execution but additional threads trying to acquire
122 // the lock at this point will block, and then get QueueGuard at STOPPED
123 // state.
124 while (count->value != 0) {
125 count.waitForCondition(count->cond);
126 }
127 count->value = -1;
128}
129
Pawin Vongmasa36653902018-11-15 00:10:25 -0800130// CCodecBufferChannel::ReorderStash
131
132CCodecBufferChannel::ReorderStash::ReorderStash() {
133 clear();
134}
135
136void CCodecBufferChannel::ReorderStash::clear() {
137 mPending.clear();
138 mStash.clear();
139 mDepth = 0;
140 mKey = C2Config::ORDINAL;
141}
142
Wonsik Kim6897f222019-01-30 13:29:24 -0800143void CCodecBufferChannel::ReorderStash::flush() {
144 mPending.clear();
145 mStash.clear();
146}
147
Pawin Vongmasa36653902018-11-15 00:10:25 -0800148void CCodecBufferChannel::ReorderStash::setDepth(uint32_t depth) {
149 mPending.splice(mPending.end(), mStash);
150 mDepth = depth;
151}
Wonsik Kim66427432019-03-21 15:06:22 -0700152
Pawin Vongmasa36653902018-11-15 00:10:25 -0800153void CCodecBufferChannel::ReorderStash::setKey(C2Config::ordinal_key_t key) {
154 mPending.splice(mPending.end(), mStash);
155 mKey = key;
156}
157
158bool CCodecBufferChannel::ReorderStash::pop(Entry *entry) {
159 if (mPending.empty()) {
160 return false;
161 }
162 entry->buffer = mPending.front().buffer;
163 entry->timestamp = mPending.front().timestamp;
164 entry->flags = mPending.front().flags;
165 entry->ordinal = mPending.front().ordinal;
166 mPending.pop_front();
167 return true;
168}
169
170void CCodecBufferChannel::ReorderStash::emplace(
171 const std::shared_ptr<C2Buffer> &buffer,
172 int64_t timestamp,
173 int32_t flags,
174 const C2WorkOrdinalStruct &ordinal) {
Wonsik Kim66427432019-03-21 15:06:22 -0700175 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
176 if (!buffer && eos) {
177 // TRICKY: we may be violating ordering of the stash here. Because we
178 // don't expect any more emplace() calls after this, the ordering should
179 // not matter.
180 mStash.emplace_back(buffer, timestamp, flags, ordinal);
181 } else {
182 flags = flags & ~MediaCodec::BUFFER_FLAG_EOS;
183 auto it = mStash.begin();
184 for (; it != mStash.end(); ++it) {
185 if (less(ordinal, it->ordinal)) {
186 break;
187 }
188 }
189 mStash.emplace(it, buffer, timestamp, flags, ordinal);
190 if (eos) {
191 mStash.back().flags = mStash.back().flags | MediaCodec::BUFFER_FLAG_EOS;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800192 }
193 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800194 while (!mStash.empty() && mStash.size() > mDepth) {
195 mPending.push_back(mStash.front());
196 mStash.pop_front();
197 }
198}
199
200void CCodecBufferChannel::ReorderStash::defer(
201 const CCodecBufferChannel::ReorderStash::Entry &entry) {
202 mPending.push_front(entry);
203}
204
205bool CCodecBufferChannel::ReorderStash::hasPending() const {
206 return !mPending.empty();
207}
208
209bool CCodecBufferChannel::ReorderStash::less(
210 const C2WorkOrdinalStruct &o1, const C2WorkOrdinalStruct &o2) {
211 switch (mKey) {
212 case C2Config::ORDINAL: return o1.frameIndex < o2.frameIndex;
213 case C2Config::TIMESTAMP: return o1.timestamp < o2.timestamp;
214 case C2Config::CUSTOM: return o1.customOrdinal < o2.customOrdinal;
215 default:
216 ALOGD("Unrecognized key; default to timestamp");
217 return o1.frameIndex < o2.frameIndex;
218 }
219}
220
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700221// Input
222
223CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
224
Pawin Vongmasa36653902018-11-15 00:10:25 -0800225// CCodecBufferChannel
226
227CCodecBufferChannel::CCodecBufferChannel(
228 const std::shared_ptr<CCodecCallback> &callback)
229 : mHeapSeqNum(-1),
230 mCCodecCallback(callback),
231 mFrameIndex(0u),
232 mFirstValidFrameIndex(0u),
233 mMetaMode(MODE_NONE),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800234 mInputMetEos(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700235 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700236 {
237 Mutexed<Input>::Locked input(mInput);
238 input->buffers.reset(new DummyInputBuffers(""));
239 input->extraBuffers.flush();
240 input->inputDelay = 0u;
241 input->pipelineDelay = 0u;
242 input->numSlots = kSmoothnessFactor;
243 input->numExtraSlots = 0u;
244 }
245 {
246 Mutexed<Output>::Locked output(mOutput);
247 output->outputDelay = 0u;
248 output->numSlots = kSmoothnessFactor;
249 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800250}
251
252CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800253 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800254 mCrypto->unsetHeap(mHeapSeqNum);
255 }
256}
257
258void CCodecBufferChannel::setComponent(
259 const std::shared_ptr<Codec2Client::Component> &component) {
260 mComponent = component;
261 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
262 mName = mComponentName.c_str();
263}
264
265status_t CCodecBufferChannel::setInputSurface(
266 const std::shared_ptr<InputSurfaceWrapper> &surface) {
267 ALOGV("[%s] setInputSurface", mName);
268 mInputSurface = surface;
269 return mInputSurface->connect(mComponent);
270}
271
272status_t CCodecBufferChannel::signalEndOfInputStream() {
273 if (mInputSurface == nullptr) {
274 return INVALID_OPERATION;
275 }
276 return mInputSurface->signalEndOfInputStream();
277}
278
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700279status_t CCodecBufferChannel::queueInputBufferInternal(sp<MediaCodecBuffer> buffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800280 int64_t timeUs;
281 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
282
283 if (mInputMetEos) {
284 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
285 return OK;
286 }
287
288 int32_t flags = 0;
289 int32_t tmp = 0;
290 bool eos = false;
291 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
292 eos = true;
293 mInputMetEos = true;
294 ALOGV("[%s] input EOS", mName);
295 }
296 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
297 flags |= C2FrameData::FLAG_CODEC_CONFIG;
298 }
299 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
300 std::unique_ptr<C2Work> work(new C2Work);
301 work->input.ordinal.timestamp = timeUs;
302 work->input.ordinal.frameIndex = mFrameIndex++;
303 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
304 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
305 // Keep client timestamp in customOrdinal
306 work->input.ordinal.customOrdinal = timeUs;
307 work->input.buffers.clear();
308
Wonsik Kimab34ed62019-01-31 15:28:46 -0800309 uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
310 std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700311 sp<Codec2Buffer> copy;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800312
Pawin Vongmasa36653902018-11-15 00:10:25 -0800313 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700314 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800315 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700316 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800317 return -ENOENT;
318 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700319 // TODO: we want to delay copying buffers.
320 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
321 copy = input->buffers->cloneAndReleaseBuffer(buffer);
322 if (copy != nullptr) {
323 (void)input->extraBuffers.assignSlot(copy);
324 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
325 return UNKNOWN_ERROR;
326 }
327 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
328 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
329 mName, released ? "" : "not ");
330 buffer.clear();
331 } else {
332 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
333 "buffer starvation on component.", mName);
334 }
335 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800336 work->input.buffers.push_back(c2buffer);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800337 queuedBuffers.push_back(c2buffer);
338 } else if (eos) {
339 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800340 }
341 work->input.flags = (C2FrameData::flags_t)flags;
342 // TODO: fill info's
343
344 work->input.configUpdate = std::move(mParamsToBeSet);
345 work->worklets.clear();
346 work->worklets.emplace_back(new C2Worklet);
347
348 std::list<std::unique_ptr<C2Work>> items;
349 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800350 mPipelineWatcher.lock()->onWorkQueued(
351 queuedFrameIndex,
352 std::move(queuedBuffers),
353 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800354 c2_status_t err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800355 if (err != C2_OK) {
356 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
357 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800358
359 if (err == C2_OK && eos && buffer->size() > 0u) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800360 work.reset(new C2Work);
361 work->input.ordinal.timestamp = timeUs;
362 work->input.ordinal.frameIndex = mFrameIndex++;
363 // WORKAROUND: keep client timestamp in customOrdinal
364 work->input.ordinal.customOrdinal = timeUs;
365 work->input.buffers.clear();
366 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800367 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800368
Wonsik Kimab34ed62019-01-31 15:28:46 -0800369 queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
370 queuedBuffers.clear();
371
Pawin Vongmasa36653902018-11-15 00:10:25 -0800372 items.clear();
373 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800374
375 mPipelineWatcher.lock()->onWorkQueued(
376 queuedFrameIndex,
377 std::move(queuedBuffers),
378 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800379 err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800380 if (err != C2_OK) {
381 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
382 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800383 }
384 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700385 Mutexed<Input>::Locked input(mInput);
386 bool released = false;
387 if (buffer) {
388 released = input->buffers->releaseBuffer(buffer, nullptr, true);
389 } else if (copy) {
390 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
391 }
392 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
393 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800394 }
395
396 feedInputBufferIfAvailableInternal();
397 return err;
398}
399
400status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
401 QueueGuard guard(mSync);
402 if (!guard.isRunning()) {
403 ALOGD("[%s] setParameters is only supported in the running state.", mName);
404 return -ENOSYS;
405 }
406 mParamsToBeSet.insert(mParamsToBeSet.end(),
407 std::make_move_iterator(params.begin()),
408 std::make_move_iterator(params.end()));
409 params.clear();
410 return OK;
411}
412
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800413status_t CCodecBufferChannel::attachBuffer(
414 const std::shared_ptr<C2Buffer> &c2Buffer,
415 const sp<MediaCodecBuffer> &buffer) {
416 if (!buffer->copy(c2Buffer)) {
417 return -ENOSYS;
418 }
419 return OK;
420}
421
422void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
423 if (!mDecryptDestination || mDecryptDestination->size() < size) {
424 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
425 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
426 mCrypto->unsetHeap(mHeapSeqNum);
427 }
428 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
429 if (mCrypto) {
430 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
431 }
432 }
433}
434
435int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
436 CHECK(mCrypto);
437 auto it = mHeapSeqNumMap.find(memory);
438 int32_t heapSeqNum = -1;
439 if (it == mHeapSeqNumMap.end()) {
440 heapSeqNum = mCrypto->setHeap(memory);
441 mHeapSeqNumMap.emplace(memory, heapSeqNum);
442 } else {
443 heapSeqNum = it->second;
444 }
445 return heapSeqNum;
446}
447
448status_t CCodecBufferChannel::attachEncryptedBuffer(
449 const sp<hardware::HidlMemory> &memory,
450 bool secure,
451 const uint8_t *key,
452 const uint8_t *iv,
453 CryptoPlugin::Mode mode,
454 CryptoPlugin::Pattern pattern,
455 size_t offset,
456 const CryptoPlugin::SubSample *subSamples,
457 size_t numSubSamples,
458 const sp<MediaCodecBuffer> &buffer) {
459 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
460 static const C2MemoryUsage kDefaultReadWriteUsage{
461 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
462
463 size_t size = 0;
464 for (size_t i = 0; i < numSubSamples; ++i) {
465 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
466 }
467 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
468 std::shared_ptr<C2LinearBlock> block;
469 c2_status_t err = pool->fetchLinearBlock(
470 size,
471 secure ? kSecureUsage : kDefaultReadWriteUsage,
472 &block);
473 if (err != C2_OK) {
474 return NO_MEMORY;
475 }
476 if (!secure) {
477 ensureDecryptDestination(size);
478 }
479 ssize_t result = -1;
480 ssize_t codecDataOffset = 0;
481 if (mCrypto) {
482 AString errorDetailMsg;
483 int32_t heapSeqNum = getHeapSeqNum(memory);
484 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
485 hardware::drm::V1_0::DestinationBuffer dst;
486 if (secure) {
487 dst.type = DrmBufferType::NATIVE_HANDLE;
488 dst.secureMemory = hardware::hidl_handle(block->handle());
489 } else {
490 dst.type = DrmBufferType::SHARED_MEMORY;
491 IMemoryToSharedBuffer(
492 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
493 }
494 result = mCrypto->decrypt(
495 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
496 dst, &errorDetailMsg);
497 if (result < 0) {
498 return result;
499 }
500 if (dst.type == DrmBufferType::SHARED_MEMORY) {
501 C2WriteView view = block->map().get();
502 if (view.error() != C2_OK) {
503 return false;
504 }
505 if (view.size() < result) {
506 return false;
507 }
508 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
509 }
510 } else {
511 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
512 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
513 hidl_vec<SubSample> hidlSubSamples;
514 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
515
516 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
517 hardware::cas::native::V1_0::DestinationBuffer dst;
518 if (secure) {
519 dst.type = BufferType::NATIVE_HANDLE;
520 dst.secureMemory = hardware::hidl_handle(block->handle());
521 } else {
522 dst.type = BufferType::SHARED_MEMORY;
523 dst.nonsecureMemory = src;
524 }
525
526 CasStatus status = CasStatus::OK;
527 hidl_string detailedError;
528 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
529
530 if (key != nullptr) {
531 sctrl = (ScramblingControl)key[0];
532 // Adjust for the PES offset
533 codecDataOffset = key[2] | (key[3] << 8);
534 }
535
536 auto returnVoid = mDescrambler->descramble(
537 sctrl,
538 hidlSubSamples,
539 src,
540 0,
541 dst,
542 0,
543 [&status, &result, &detailedError] (
544 CasStatus _status, uint32_t _bytesWritten,
545 const hidl_string& _detailedError) {
546 status = _status;
547 result = (ssize_t)_bytesWritten;
548 detailedError = _detailedError;
549 });
550
551 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
552 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
553 mName, returnVoid.description().c_str(), status, result);
554 return UNKNOWN_ERROR;
555 }
556
557 if (result < codecDataOffset) {
558 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
559 return BAD_VALUE;
560 }
561 }
562 if (!secure) {
563 C2WriteView view = block->map().get();
564 if (view.error() != C2_OK) {
565 return UNKNOWN_ERROR;
566 }
567 if (view.size() < result) {
568 return UNKNOWN_ERROR;
569 }
570 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
571 }
572 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
573 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
574 if (!buffer->copy(c2Buffer)) {
575 return -ENOSYS;
576 }
577 return OK;
578}
579
Pawin Vongmasa36653902018-11-15 00:10:25 -0800580status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
581 QueueGuard guard(mSync);
582 if (!guard.isRunning()) {
583 ALOGD("[%s] No more buffers should be queued at current state.", mName);
584 return -ENOSYS;
585 }
586 return queueInputBufferInternal(buffer);
587}
588
589status_t CCodecBufferChannel::queueSecureInputBuffer(
590 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
591 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
592 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
593 AString *errorDetailMsg) {
594 QueueGuard guard(mSync);
595 if (!guard.isRunning()) {
596 ALOGD("[%s] No more buffers should be queued at current state.", mName);
597 return -ENOSYS;
598 }
599
600 if (!hasCryptoOrDescrambler()) {
601 return -ENOSYS;
602 }
603 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
604
605 ssize_t result = -1;
606 ssize_t codecDataOffset = 0;
607 if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700608 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800609 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700610 destination.type = DrmBufferType::NATIVE_HANDLE;
611 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800612 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700613 destination.type = DrmBufferType::SHARED_MEMORY;
614 IMemoryToSharedBuffer(
615 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800616 }
Robert Shih895fba92019-07-16 16:29:44 -0700617 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800618 encryptedBuffer->fillSourceBuffer(&source);
619 result = mCrypto->decrypt(
620 key, iv, mode, pattern, source, buffer->offset(),
621 subSamples, numSubSamples, destination, errorDetailMsg);
622 if (result < 0) {
623 return result;
624 }
Robert Shih895fba92019-07-16 16:29:44 -0700625 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800626 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
627 }
628 } else {
629 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
630 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
631 hidl_vec<SubSample> hidlSubSamples;
632 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
633
634 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
635 encryptedBuffer->fillSourceBuffer(&srcBuffer);
636
637 DestinationBuffer dstBuffer;
638 if (secure) {
639 dstBuffer.type = BufferType::NATIVE_HANDLE;
640 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
641 } else {
642 dstBuffer.type = BufferType::SHARED_MEMORY;
643 dstBuffer.nonsecureMemory = srcBuffer;
644 }
645
646 CasStatus status = CasStatus::OK;
647 hidl_string detailedError;
648 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
649
650 if (key != nullptr) {
651 sctrl = (ScramblingControl)key[0];
652 // Adjust for the PES offset
653 codecDataOffset = key[2] | (key[3] << 8);
654 }
655
656 auto returnVoid = mDescrambler->descramble(
657 sctrl,
658 hidlSubSamples,
659 srcBuffer,
660 0,
661 dstBuffer,
662 0,
663 [&status, &result, &detailedError] (
664 CasStatus _status, uint32_t _bytesWritten,
665 const hidl_string& _detailedError) {
666 status = _status;
667 result = (ssize_t)_bytesWritten;
668 detailedError = _detailedError;
669 });
670
671 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
672 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
673 mName, returnVoid.description().c_str(), status, result);
674 return UNKNOWN_ERROR;
675 }
676
677 if (result < codecDataOffset) {
678 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
679 return BAD_VALUE;
680 }
681
682 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
683
684 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
685 encryptedBuffer->copyDecryptedContentFromMemory(result);
686 }
687 }
688
689 buffer->setRange(codecDataOffset, result - codecDataOffset);
690 return queueInputBufferInternal(buffer);
691}
692
693void CCodecBufferChannel::feedInputBufferIfAvailable() {
694 QueueGuard guard(mSync);
695 if (!guard.isRunning()) {
696 ALOGV("[%s] We're not running --- no input buffer reported", mName);
697 return;
698 }
699 feedInputBufferIfAvailableInternal();
700}
701
702void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800703 if (mInputMetEos ||
704 mReorderStash.lock()->hasPending() ||
705 mPipelineWatcher.lock()->pipelineFull()) {
706 return;
707 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700708 Mutexed<Output>::Locked output(mOutput);
709 if (output->buffers->numClientBuffers() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800710 return;
711 }
712 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700713 size_t numInputSlots = mInput.lock()->numSlots;
714 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800715 sp<MediaCodecBuffer> inBuffer;
716 size_t index;
717 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700718 Mutexed<Input>::Locked input(mInput);
719 if (input->buffers->numClientBuffers() >= input->numSlots) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800720 return;
721 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700722 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800723 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800724 break;
725 }
726 }
727 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
728 mCallback->onInputBufferAvailable(index, inBuffer);
729 }
730}
731
732status_t CCodecBufferChannel::renderOutputBuffer(
733 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800734 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800735 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800736 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800737 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700738 Mutexed<Output>::Locked output(mOutput);
739 if (output->buffers) {
740 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800741 }
742 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800743 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
744 // set to true.
745 sendOutputBuffers();
746 // input buffer feeding may have been gated by pending output buffers
747 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800749 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700750 std::call_once(mRenderWarningFlag, [this] {
751 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
752 "timestamp or render=true with non-video buffers. Apps should "
753 "call releaseOutputBuffer() with render=false for those.",
754 mName);
755 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800756 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800757 return INVALID_OPERATION;
758 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759
760#if 0
761 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
762 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
763 for (const std::shared_ptr<const C2Info> &info : infoParams) {
764 AString res;
765 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
766 if (ix) res.append(", ");
767 res.append(*((int32_t*)info.get() + (ix / 4)));
768 }
769 ALOGV(" [%s]", res.c_str());
770 }
771#endif
772 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
773 std::static_pointer_cast<const C2StreamRotationInfo::output>(
774 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
775 bool flip = rotation && (rotation->flip & 1);
776 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
777 uint32_t transform = 0;
778 switch (quarters) {
779 case 0: // no rotation
780 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
781 break;
782 case 1: // 90 degrees counter-clockwise
783 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
784 : HAL_TRANSFORM_ROT_270;
785 break;
786 case 2: // 180 degrees
787 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
788 break;
789 case 3: // 90 degrees clockwise
790 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
791 : HAL_TRANSFORM_ROT_90;
792 break;
793 }
794
795 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
796 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
797 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
798 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
799 if (surfaceScaling) {
800 videoScalingMode = surfaceScaling->value;
801 }
802
803 // Use dataspace from format as it has the default aspects already applied
804 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
805 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
806
807 // HDR static info
808 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
809 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
810 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
811
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800812 // HDR10 plus info
813 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
814 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
815 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
816
Pawin Vongmasa36653902018-11-15 00:10:25 -0800817 {
818 Mutexed<OutputSurface>::Locked output(mOutputSurface);
819 if (output->surface == nullptr) {
820 ALOGI("[%s] cannot render buffer without surface", mName);
821 return OK;
822 }
823 }
824
825 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
826 if (blocks.size() != 1u) {
827 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
828 return UNKNOWN_ERROR;
829 }
830 const C2ConstGraphicBlock &block = blocks.front();
831
832 // TODO: revisit this after C2Fence implementation.
833 android::IGraphicBufferProducer::QueueBufferInput qbi(
834 timestampNs,
835 false, // droppable
836 dataSpace,
837 Rect(blocks.front().crop().left,
838 blocks.front().crop().top,
839 blocks.front().crop().right(),
840 blocks.front().crop().bottom()),
841 videoScalingMode,
842 transform,
843 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800844 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800845 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800846 if (hdrStaticInfo) {
847 struct android_smpte2086_metadata smpte2086_meta = {
848 .displayPrimaryRed = {
849 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
850 },
851 .displayPrimaryGreen = {
852 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
853 },
854 .displayPrimaryBlue = {
855 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
856 },
857 .whitePoint = {
858 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
859 },
860 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
861 .minLuminance = hdrStaticInfo->mastering.minLuminance,
862 };
863
864 struct android_cta861_3_metadata cta861_meta = {
865 .maxContentLightLevel = hdrStaticInfo->maxCll,
866 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
867 };
868
869 hdr.validTypes = HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3;
870 hdr.smpte2086 = smpte2086_meta;
871 hdr.cta8613 = cta861_meta;
872 }
873 if (hdr10PlusInfo) {
874 hdr.validTypes |= HdrMetadata::HDR10PLUS;
875 hdr.hdr10plus.assign(
876 hdr10PlusInfo->m.value,
877 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
878 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800879 qbi.setHdrMetadata(hdr);
880 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800881 // we don't have dirty regions
882 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800883 android::IGraphicBufferProducer::QueueBufferOutput qbo;
884 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
885 if (result != OK) {
886 ALOGI("[%s] queueBuffer failed: %d", mName, result);
887 return result;
888 }
889 ALOGV("[%s] queue buffer successful", mName);
890
891 int64_t mediaTimeUs = 0;
892 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
893 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
894
895 return OK;
896}
897
898status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
899 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
900 bool released = false;
901 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700902 Mutexed<Input>::Locked input(mInput);
903 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800904 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800905 }
906 }
907 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700908 Mutexed<Output>::Locked output(mOutput);
909 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800910 released = true;
911 }
912 }
913 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800914 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800915 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800916 } else {
917 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
918 }
919 return OK;
920}
921
922void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
923 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700924 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800925
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700926 if (!input->buffers->isArrayMode()) {
927 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800928 }
929
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700930 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800931}
932
933void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
934 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700935 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800936
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700937 if (!output->buffers->isArrayMode()) {
938 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800939 }
940
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700941 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800942}
943
944status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800945 const sp<AMessage> &inputFormat,
946 const sp<AMessage> &outputFormat,
947 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800948 C2StreamBufferTypeSetting::input iStreamFormat(0u);
949 C2StreamBufferTypeSetting::output oStreamFormat(0u);
950 C2PortReorderBufferDepthTuning::output reorderDepth;
951 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800952 C2PortActualDelayTuning::input inputDelay(0);
953 C2PortActualDelayTuning::output outputDelay(0);
954 C2ActualPipelineDelayTuning pipelineDelay(0);
955
Pawin Vongmasa36653902018-11-15 00:10:25 -0800956 c2_status_t err = mComponent->query(
957 {
958 &iStreamFormat,
959 &oStreamFormat,
960 &reorderDepth,
961 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800962 &inputDelay,
963 &pipelineDelay,
964 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800965 },
966 {},
967 C2_DONT_BLOCK,
968 nullptr);
969 if (err == C2_BAD_INDEX) {
970 if (!iStreamFormat || !oStreamFormat) {
971 return UNKNOWN_ERROR;
972 }
973 } else if (err != C2_OK) {
974 return UNKNOWN_ERROR;
975 }
976
977 {
978 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
979 reorder->clear();
980 if (reorderDepth) {
981 reorder->setDepth(reorderDepth.value);
982 }
983 if (reorderKey) {
984 reorder->setKey(reorderKey.value);
985 }
986 }
Wonsik Kim078b58e2019-01-09 15:08:06 -0800987
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800988 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
989 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
990 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
991
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700992 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
993 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800994
Pawin Vongmasa36653902018-11-15 00:10:25 -0800995 // TODO: get this from input format
996 bool secure = mComponent->getName().find(".secure") != std::string::npos;
997
998 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +0800999 int poolMask = GetCodec2PoolMask();
1000 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001001
1002 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001003 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001004 std::shared_ptr<C2BlockPool> pool;
1005 {
1006 Mutexed<BlockPools>::Locked pools(mBlockPools);
1007
1008 // set default allocator ID.
1009 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001010 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001011
1012 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1013 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1014 std::vector<std::unique_ptr<C2Param>> params;
1015 err = mComponent->query({ },
1016 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1017 C2_DONT_BLOCK,
1018 &params);
1019 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1020 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1021 mName, params.size(), asString(err), err);
1022 } else if (err == C2_OK && params.size() == 1) {
1023 C2PortAllocatorsTuning::input *inputAllocators =
1024 C2PortAllocatorsTuning::input::From(params[0].get());
1025 if (inputAllocators && inputAllocators->flexCount() > 0) {
1026 std::shared_ptr<C2Allocator> allocator;
1027 // verify allocator IDs and resolve default allocator
1028 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1029 if (allocator) {
1030 pools->inputAllocatorId = allocator->getId();
1031 } else {
1032 ALOGD("[%s] component requested invalid input allocator ID %u",
1033 mName, inputAllocators->m.values[0]);
1034 }
1035 }
1036 }
1037
1038 // TODO: use C2Component wrapper to associate this pool with ourselves
1039 if ((poolMask >> pools->inputAllocatorId) & 1) {
1040 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1041 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1042 mName, pools->inputAllocatorId,
1043 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1044 asString(err), err);
1045 } else {
1046 err = C2_NOT_FOUND;
1047 }
1048 if (err != C2_OK) {
1049 C2BlockPool::local_id_t inputPoolId =
1050 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1051 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1052 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1053 mName, (unsigned long long)inputPoolId,
1054 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1055 asString(err), err);
1056 if (err != C2_OK) {
1057 return NO_MEMORY;
1058 }
1059 }
1060 pools->inputPool = pool;
1061 }
1062
Wonsik Kim51051262018-11-28 13:59:05 -08001063 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001064 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001065 input->inputDelay = inputDelayValue;
1066 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001067 input->numSlots = numInputSlots;
1068 input->extraBuffers.flush();
1069 input->numExtraSlots = 0u;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001070 if (!buffersBoundToCodec) {
1071 input->buffers.reset(new SlotInputBuffers(mName));
1072 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001073 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001074 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001075 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001076 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001077 // This is to ensure buffers do not get released prematurely.
1078 // TODO: handle this without going into array mode
1079 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001080 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001081 input->buffers.reset(new GraphicInputBuffers(numInputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001082 }
1083 } else {
1084 if (hasCryptoOrDescrambler()) {
1085 int32_t capacity = kLinearBufferSize;
1086 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1087 if ((size_t)capacity > kMaxLinearBufferSize) {
1088 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1089 capacity = kMaxLinearBufferSize;
1090 }
1091 if (mDealer == nullptr) {
1092 mDealer = new MemoryDealer(
1093 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001094 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001095 "EncryptedLinearInputBuffers");
1096 mDecryptDestination = mDealer->allocate((size_t)capacity);
1097 }
1098 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001099 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1100 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001101 } else {
1102 mHeapSeqNum = -1;
1103 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001104 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001105 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001106 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001107 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001108 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001109 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001110 }
1111 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001112 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001113
1114 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001115 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001116 } else {
1117 // TODO: error
1118 }
Wonsik Kim51051262018-11-28 13:59:05 -08001119
1120 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001121 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001122 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001123 }
1124
1125 if (outputFormat != nullptr) {
1126 sp<IGraphicBufferProducer> outputSurface;
1127 uint32_t outputGeneration;
1128 {
1129 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001130 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001131 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001132 if (!secure) {
1133 output->maxDequeueBuffers += numInputSlots;
1134 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001135 outputSurface = output->surface ?
1136 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001137 if (outputSurface) {
1138 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1139 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001140 outputGeneration = output->generation;
1141 }
1142
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001143 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001144 C2BlockPool::local_id_t outputPoolId_;
1145
1146 {
1147 Mutexed<BlockPools>::Locked pools(mBlockPools);
1148
1149 // set default allocator ID.
1150 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001151 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001152
1153 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1154 // unsuccessful.
1155 std::vector<std::unique_ptr<C2Param>> params;
1156 err = mComponent->query({ },
1157 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1158 C2_DONT_BLOCK,
1159 &params);
1160 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1161 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1162 mName, params.size(), asString(err), err);
1163 } else if (err == C2_OK && params.size() == 1) {
1164 C2PortAllocatorsTuning::output *outputAllocators =
1165 C2PortAllocatorsTuning::output::From(params[0].get());
1166 if (outputAllocators && outputAllocators->flexCount() > 0) {
1167 std::shared_ptr<C2Allocator> allocator;
1168 // verify allocator IDs and resolve default allocator
1169 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1170 if (allocator) {
1171 pools->outputAllocatorId = allocator->getId();
1172 } else {
1173 ALOGD("[%s] component requested invalid output allocator ID %u",
1174 mName, outputAllocators->m.values[0]);
1175 }
1176 }
1177 }
1178
1179 // use bufferqueue if outputting to a surface.
1180 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1181 // if unsuccessful.
1182 if (outputSurface) {
1183 params.clear();
1184 err = mComponent->query({ },
1185 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1186 C2_DONT_BLOCK,
1187 &params);
1188 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1189 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1190 mName, params.size(), asString(err), err);
1191 } else if (err == C2_OK && params.size() == 1) {
1192 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1193 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1194 if (surfaceAllocator) {
1195 std::shared_ptr<C2Allocator> allocator;
1196 // verify allocator IDs and resolve default allocator
1197 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1198 if (allocator) {
1199 pools->outputAllocatorId = allocator->getId();
1200 } else {
1201 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1202 mName, surfaceAllocator->value);
1203 err = C2_BAD_VALUE;
1204 }
1205 }
1206 }
1207 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1208 && err != C2_OK
1209 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1210 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1211 }
1212 }
1213
1214 if ((poolMask >> pools->outputAllocatorId) & 1) {
1215 err = mComponent->createBlockPool(
1216 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1217 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1218 mName, pools->outputAllocatorId,
1219 (unsigned long long)pools->outputPoolId,
1220 asString(err));
1221 } else {
1222 err = C2_NOT_FOUND;
1223 }
1224 if (err != C2_OK) {
1225 // use basic pool instead
1226 pools->outputPoolId =
1227 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1228 }
1229
1230 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1231 // component.
1232 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1233 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1234
1235 std::vector<std::unique_ptr<C2SettingResult>> failures;
1236 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1237 ALOGD("[%s] Configured output block pool ids %llu => %s",
1238 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1239 outputPoolId_ = pools->outputPoolId;
1240 }
1241
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001242 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001243 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001244 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001245 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001246 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001247 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001248 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001249 output->buffers.reset(new RawGraphicOutputBuffers(numOutputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001250 }
1251 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001252 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001253 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001254 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001255
1256
1257 // Try to set output surface to created block pool if given.
1258 if (outputSurface) {
1259 mComponent->setOutputSurface(
1260 outputPoolId_,
1261 outputSurface,
1262 outputGeneration);
1263 }
1264
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001265 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001266 if (buffersBoundToCodec) {
1267 // WORKAROUND: if we're using early CSD workaround we convert to
1268 // array mode, to appease apps assuming the output
1269 // buffers to be of the same size.
1270 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1271 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001272
1273 int32_t channelCount;
1274 int32_t sampleRate;
1275 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1276 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1277 int32_t delay = 0;
1278 int32_t padding = 0;;
1279 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1280 delay = 0;
1281 }
1282 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1283 padding = 0;
1284 }
1285 if (delay || padding) {
1286 // We need write access to the buffers, and we're already in
1287 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001288 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001289 }
1290 }
1291 }
1292 }
1293
1294 // Set up pipeline control. This has to be done after mInputBuffers and
1295 // mOutputBuffers are initialized to make sure that lingering callbacks
1296 // about buffers from the previous generation do not interfere with the
1297 // newly initialized pipeline capacity.
1298
Wonsik Kimab34ed62019-01-31 15:28:46 -08001299 {
1300 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001301 watcher->inputDelay(inputDelayValue)
1302 .pipelineDelay(pipelineDelayValue)
1303 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001304 .smoothnessFactor(kSmoothnessFactor);
1305 watcher->flush();
1306 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001307
1308 mInputMetEos = false;
1309 mSync.start();
1310 return OK;
1311}
1312
1313status_t CCodecBufferChannel::requestInitialInputBuffers() {
1314 if (mInputSurface) {
1315 return OK;
1316 }
1317
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001318 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001319 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1320 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1321 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001322 return UNKNOWN_ERROR;
1323 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001324 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001325 std::vector<sp<MediaCodecBuffer>> toBeQueued;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001326 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001327 size_t index;
1328 sp<MediaCodecBuffer> buffer;
1329 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001330 Mutexed<Input>::Locked input(mInput);
1331 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001332 if (i == 0) {
1333 ALOGW("[%s] start: cannot allocate memory at all", mName);
1334 return NO_MEMORY;
1335 } else {
1336 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
1337 mName, i);
1338 }
1339 break;
1340 }
1341 }
1342 if (buffer) {
1343 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1344 ALOGV("[%s] input buffer %zu available", mName, index);
1345 bool post = true;
1346 if (!configs->empty()) {
1347 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001348 configs->pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001349 if (buffer->capacity() >= config->size()) {
1350 memcpy(buffer->base(), config->data(), config->size());
1351 buffer->setRange(0, config->size());
1352 buffer->meta()->clear();
1353 buffer->meta()->setInt64("timeUs", 0);
1354 buffer->meta()->setInt32("csd", 1);
1355 post = false;
1356 } else {
1357 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
1358 mName, buffer->capacity(), config->size());
1359 }
1360 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001361 && (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001362 // WORKAROUND: Some apps expect CSD available without queueing
1363 // any input. Queue an empty buffer to get the CSD.
1364 buffer->setRange(0, 0);
1365 buffer->meta()->clear();
1366 buffer->meta()->setInt64("timeUs", 0);
1367 post = false;
1368 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001369 if (post) {
1370 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001371 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001372 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001373 }
1374 }
1375 }
1376 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
1377 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001378 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001379 }
1380 }
1381 return OK;
1382}
1383
1384void CCodecBufferChannel::stop() {
1385 mSync.stop();
1386 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1387 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001388 mInputSurface.reset();
1389 }
1390}
1391
1392void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1393 ALOGV("[%s] flush", mName);
1394 {
1395 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1396 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1397 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1398 continue;
1399 }
1400 if (work->input.buffers.empty()
1401 || work->input.buffers.front()->data().linearBlocks().empty()) {
1402 ALOGD("[%s] no linear codec config data found", mName);
1403 continue;
1404 }
1405 C2ReadView view =
1406 work->input.buffers.front()->data().linearBlocks().front().map().get();
1407 if (view.error() != C2_OK) {
1408 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1409 continue;
1410 }
1411 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1412 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1413 }
1414 }
1415 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001416 Mutexed<Input>::Locked input(mInput);
1417 input->buffers->flush();
1418 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001419 }
1420 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001421 Mutexed<Output>::Locked output(mOutput);
1422 output->buffers->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001423 }
Wonsik Kim6897f222019-01-30 13:29:24 -08001424 mReorderStash.lock()->flush();
Wonsik Kimab34ed62019-01-31 15:28:46 -08001425 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001426}
1427
1428void CCodecBufferChannel::onWorkDone(
1429 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001430 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001431 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001432 feedInputBufferIfAvailable();
1433 }
1434}
1435
1436void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001437 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001438 if (mInputSurface) {
1439 return;
1440 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001441 std::shared_ptr<C2Buffer> buffer =
1442 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001443 bool newInputSlotAvailable;
1444 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001445 Mutexed<Input>::Locked input(mInput);
1446 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1447 if (!newInputSlotAvailable) {
1448 (void)input->extraBuffers.expireComponentBuffer(buffer);
1449 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001450 }
1451 if (newInputSlotAvailable) {
1452 feedInputBufferIfAvailable();
1453 }
1454}
1455
1456bool CCodecBufferChannel::handleWork(
1457 std::unique_ptr<C2Work> work,
1458 const sp<AMessage> &outputFormat,
1459 const C2StreamInitDataInfo::output *initData) {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001460 if (outputFormat != nullptr) {
1461 Mutexed<Output>::Locked output(mOutput);
1462 ALOGD("[%s] onWorkDone: output format changed to %s",
1463 mName, outputFormat->debugString().c_str());
1464 output->buffers->setFormat(outputFormat);
1465
1466 AString mediaType;
1467 if (outputFormat->findString(KEY_MIME, &mediaType)
1468 && mediaType == MIMETYPE_AUDIO_RAW) {
1469 int32_t channelCount;
1470 int32_t sampleRate;
1471 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1472 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1473 output->buffers->updateSkipCutBuffer(sampleRate, channelCount);
1474 }
1475 }
1476 }
1477
Pawin Vongmasa36653902018-11-15 00:10:25 -08001478 if ((work->input.ordinal.frameIndex - mFirstValidFrameIndex.load()).peek() < 0) {
1479 // Discard frames from previous generation.
1480 ALOGD("[%s] Discard frames from previous generation.", mName);
1481 return false;
1482 }
1483
Wonsik Kim524b0582019-03-12 11:28:57 -07001484 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001485 || !work->worklets.front()
Wonsik Kim524b0582019-03-12 11:28:57 -07001486 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE))) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001487 mPipelineWatcher.lock()->onWorkDone(work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001488 }
1489
1490 if (work->result == C2_NOT_FOUND) {
1491 ALOGD("[%s] flushed work; ignored.", mName);
1492 return true;
1493 }
1494
1495 if (work->result != C2_OK) {
1496 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1497 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1498 return false;
1499 }
1500
1501 // NOTE: MediaCodec usage supposedly have only one worklet
1502 if (work->worklets.size() != 1u) {
1503 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1504 mName, work->worklets.size());
1505 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1506 return false;
1507 }
1508
1509 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1510
1511 std::shared_ptr<C2Buffer> buffer;
1512 // NOTE: MediaCodec usage supposedly have only one output stream.
1513 if (worklet->output.buffers.size() > 1u) {
1514 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1515 mName, worklet->output.buffers.size());
1516 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1517 return false;
1518 } else if (worklet->output.buffers.size() == 1u) {
1519 buffer = worklet->output.buffers[0];
1520 if (!buffer) {
1521 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1522 }
1523 }
1524
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001525 std::optional<uint32_t> newInputDelay, newPipelineDelay;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001526 while (!worklet->output.configUpdate.empty()) {
1527 std::unique_ptr<C2Param> param;
1528 worklet->output.configUpdate.back().swap(param);
1529 worklet->output.configUpdate.pop_back();
1530 switch (param->coreIndex().coreIndex()) {
1531 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1532 C2PortReorderBufferDepthTuning::output reorderDepth;
1533 if (reorderDepth.updateFrom(*param)) {
Sungtak Leed7463d12019-09-04 16:01:00 -07001534 bool secure = mComponent->getName().find(".secure") != std::string::npos;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001535 mReorderStash.lock()->setDepth(reorderDepth.value);
1536 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1537 mName, reorderDepth.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001538 size_t numOutputSlots = mOutput.lock()->numSlots;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001539 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001540 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001541 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001542 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001543 if (!secure) {
1544 output->maxDequeueBuffers += numInputSlots;
1545 }
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001546 if (output->surface) {
1547 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1548 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001549 } else {
1550 ALOGD("[%s] onWorkDone: failed to read reorder depth", mName);
1551 }
1552 break;
1553 }
1554 case C2PortReorderKeySetting::CORE_INDEX: {
1555 C2PortReorderKeySetting::output reorderKey;
1556 if (reorderKey.updateFrom(*param)) {
1557 mReorderStash.lock()->setKey(reorderKey.value);
1558 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1559 mName, reorderKey.value);
1560 } else {
1561 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1562 }
1563 break;
1564 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001565 case C2PortActualDelayTuning::CORE_INDEX: {
1566 if (param->isGlobal()) {
1567 C2ActualPipelineDelayTuning pipelineDelay;
1568 if (pipelineDelay.updateFrom(*param)) {
1569 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1570 mName, pipelineDelay.value);
1571 newPipelineDelay = pipelineDelay.value;
1572 (void)mPipelineWatcher.lock()->pipelineDelay(pipelineDelay.value);
1573 }
1574 }
1575 if (param->forInput()) {
1576 C2PortActualDelayTuning::input inputDelay;
1577 if (inputDelay.updateFrom(*param)) {
1578 ALOGV("[%s] onWorkDone: updating input delay %u",
1579 mName, inputDelay.value);
1580 newInputDelay = inputDelay.value;
1581 (void)mPipelineWatcher.lock()->inputDelay(inputDelay.value);
1582 }
1583 }
1584 if (param->forOutput()) {
1585 C2PortActualDelayTuning::output outputDelay;
1586 if (outputDelay.updateFrom(*param)) {
1587 ALOGV("[%s] onWorkDone: updating output delay %u",
1588 mName, outputDelay.value);
Sungtak Leed7463d12019-09-04 16:01:00 -07001589 bool secure = mComponent->getName().find(".secure") != std::string::npos;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001590 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
1591
1592 bool outputBuffersChanged = false;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001593 size_t numOutputSlots = 0;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001594 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001595 {
1596 Mutexed<Output>::Locked output(mOutput);
1597 output->outputDelay = outputDelay.value;
1598 numOutputSlots = outputDelay.value + kSmoothnessFactor;
1599 if (output->numSlots < numOutputSlots) {
1600 output->numSlots = numOutputSlots;
1601 if (output->buffers->isArrayMode()) {
1602 OutputBuffersArray *array =
1603 (OutputBuffersArray *)output->buffers.get();
1604 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1605 mName, numOutputSlots);
1606 array->grow(numOutputSlots);
1607 outputBuffersChanged = true;
1608 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001609 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001610 numOutputSlots = output->numSlots;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001611 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001612
1613 if (outputBuffersChanged) {
1614 mCCodecCallback->onOutputBuffersChanged();
1615 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001616
1617 uint32_t depth = mReorderStash.lock()->depth();
1618 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001619 output->maxDequeueBuffers = numOutputSlots + depth + kRenderingDepth;
1620 if (!secure) {
1621 output->maxDequeueBuffers += numInputSlots;
1622 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001623 if (output->surface) {
1624 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1625 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001626 }
1627 }
1628 break;
1629 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001630 default:
1631 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1632 mName, param->index());
1633 break;
1634 }
1635 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001636 if (newInputDelay || newPipelineDelay) {
1637 Mutexed<Input>::Locked input(mInput);
1638 size_t newNumSlots =
1639 newInputDelay.value_or(input->inputDelay) +
1640 newPipelineDelay.value_or(input->pipelineDelay) +
1641 kSmoothnessFactor;
1642 if (input->buffers->isArrayMode()) {
1643 if (input->numSlots >= newNumSlots) {
1644 input->numExtraSlots = 0;
1645 } else {
1646 input->numExtraSlots = newNumSlots - input->numSlots;
1647 }
1648 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1649 mName, input->numExtraSlots);
1650 } else {
1651 input->numSlots = newNumSlots;
1652 }
1653 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001654
Pawin Vongmasa36653902018-11-15 00:10:25 -08001655 int32_t flags = 0;
1656 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1657 flags |= MediaCodec::BUFFER_FLAG_EOS;
1658 ALOGV("[%s] onWorkDone: output EOS", mName);
1659 }
1660
1661 sp<MediaCodecBuffer> outBuffer;
1662 size_t index;
1663
1664 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1665 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1666 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1667 // shall correspond to the client input timesamp (in customOrdinal). By using the
1668 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1669 // produces multiple output.
1670 c2_cntr64_t timestamp =
1671 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1672 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001673 if (mInputSurface != nullptr) {
1674 // When using input surface we need to restore the original input timestamp.
1675 timestamp = work->input.ordinal.customOrdinal;
1676 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001677 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1678 mName,
1679 work->input.ordinal.customOrdinal.peekll(),
1680 work->input.ordinal.timestamp.peekll(),
1681 worklet->output.ordinal.timestamp.peekll(),
1682 timestamp.peekll());
1683
1684 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001685 Mutexed<Output>::Locked output(mOutput);
1686 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001687 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1688 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1689 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1690
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001691 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001692 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001693 } else {
1694 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001695 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001696 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001697 return false;
1698 }
1699 }
1700
1701 if (!buffer && !flags) {
1702 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1703 mName, work->input.ordinal.frameIndex.peekull());
1704 return true;
1705 }
1706
1707 if (buffer) {
1708 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1709 // TODO: properly translate these to metadata
1710 switch (info->coreIndex().coreIndex()) {
1711 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001712 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001713 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1714 }
1715 break;
1716 default:
1717 break;
1718 }
1719 }
1720 }
1721
1722 {
1723 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1724 reorder->emplace(buffer, timestamp.peek(), flags, worklet->output.ordinal);
1725 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
1726 // Flush reorder stash
1727 reorder->setDepth(0);
1728 }
1729 }
1730 sendOutputBuffers();
1731 return true;
1732}
1733
1734void CCodecBufferChannel::sendOutputBuffers() {
1735 ReorderStash::Entry entry;
1736 sp<MediaCodecBuffer> outBuffer;
1737 size_t index;
1738
1739 while (true) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001740 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1741 if (!reorder->hasPending()) {
1742 break;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001743 }
Wonsik Kim38ad3412019-02-01 15:13:23 -08001744 if (!reorder->pop(&entry)) {
1745 break;
1746 }
1747
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001748 Mutexed<Output>::Locked output(mOutput);
1749 status_t err = output->buffers->registerBuffer(entry.buffer, &index, &outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001750 if (err != OK) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001751 bool outputBuffersChanged = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001752 if (err != WOULD_BLOCK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001753 if (!output->buffers->isArrayMode()) {
1754 output->buffers = output->buffers->toArrayMode(output->numSlots);
Wonsik Kim186fdbf2019-01-29 13:30:01 -08001755 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001756 OutputBuffersArray *array = (OutputBuffersArray *)output->buffers.get();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001757 array->realloc(entry.buffer);
Wonsik Kim38ad3412019-02-01 15:13:23 -08001758 outputBuffersChanged = true;
1759 }
1760 ALOGV("[%s] sendOutputBuffers: unable to register output buffer", mName);
1761 reorder->defer(entry);
1762
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001763 output.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08001764 reorder.unlock();
1765
1766 if (outputBuffersChanged) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001767 mCCodecCallback->onOutputBuffersChanged();
1768 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001769 return;
1770 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001771 output.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08001772 reorder.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001773
1774 outBuffer->meta()->setInt64("timeUs", entry.timestamp);
1775 outBuffer->meta()->setInt32("flags", entry.flags);
Wonsik Kim66427432019-03-21 15:06:22 -07001776 ALOGV("[%s] sendOutputBuffers: out buffer index = %zu [%p] => %p + %zu (%lld)",
1777 mName, index, outBuffer.get(), outBuffer->data(), outBuffer->size(),
1778 (long long)entry.timestamp);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001779 mCallback->onOutputBufferAvailable(index, outBuffer);
1780 }
1781}
1782
1783status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1784 static std::atomic_uint32_t surfaceGeneration{0};
1785 uint32_t generation = (getpid() << 10) |
1786 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1787 & ((1 << 10) - 1));
1788
1789 sp<IGraphicBufferProducer> producer;
1790 if (newSurface) {
1791 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001792 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Lee08515812019-06-05 11:16:32 -07001793 newSurface->setMaxDequeuedBufferCount(mOutputSurface.lock()->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001794 producer = newSurface->getIGraphicBufferProducer();
1795 producer->setGenerationNumber(generation);
1796 } else {
1797 ALOGE("[%s] setting output surface to null", mName);
1798 return INVALID_OPERATION;
1799 }
1800
1801 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1802 C2BlockPool::local_id_t outputPoolId;
1803 {
1804 Mutexed<BlockPools>::Locked pools(mBlockPools);
1805 outputPoolId = pools->outputPoolId;
1806 outputPoolIntf = pools->outputPoolIntf;
1807 }
1808
1809 if (outputPoolIntf) {
1810 if (mComponent->setOutputSurface(
1811 outputPoolId,
1812 producer,
1813 generation) != C2_OK) {
1814 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1815 return INVALID_OPERATION;
1816 }
1817 }
1818
1819 {
1820 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1821 output->surface = newSurface;
1822 output->generation = generation;
1823 }
1824
1825 return OK;
1826}
1827
Wonsik Kimab34ed62019-01-31 15:28:46 -08001828PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001829 // When client pushed EOS, we want all the work to be done quickly.
1830 // Otherwise, component may have stalled work due to input starvation up to
1831 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001832 size_t n = 0;
1833 if (!mInputMetEos) {
1834 size_t outputDelay = mOutput.lock()->outputDelay;
1835 Mutexed<Input>::Locked input(mInput);
1836 n = input->inputDelay + input->pipelineDelay + outputDelay;
1837 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001838 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001839}
1840
Pawin Vongmasa36653902018-11-15 00:10:25 -08001841void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1842 mMetaMode = mode;
1843}
1844
Wonsik Kim596187e2019-10-25 12:44:10 -07001845void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001846 if (mCrypto != nullptr) {
1847 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
1848 mCrypto->unsetHeap(entry.second);
1849 }
1850 mHeapSeqNumMap.clear();
1851 if (mHeapSeqNum >= 0) {
1852 mCrypto->unsetHeap(mHeapSeqNum);
1853 mHeapSeqNum = -1;
1854 }
1855 }
Wonsik Kim596187e2019-10-25 12:44:10 -07001856 mCrypto = crypto;
1857}
1858
1859void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
1860 mDescrambler = descrambler;
1861}
1862
Pawin Vongmasa36653902018-11-15 00:10:25 -08001863status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1864 // C2_OK is always translated to OK.
1865 if (c2s == C2_OK) {
1866 return OK;
1867 }
1868
1869 // Operation-dependent translation
1870 // TODO: Add as necessary
1871 switch (c2op) {
1872 case C2_OPERATION_Component_start:
1873 switch (c2s) {
1874 case C2_NO_MEMORY:
1875 return NO_MEMORY;
1876 default:
1877 return UNKNOWN_ERROR;
1878 }
1879 default:
1880 break;
1881 }
1882
1883 // Backup operation-agnostic translation
1884 switch (c2s) {
1885 case C2_BAD_INDEX:
1886 return BAD_INDEX;
1887 case C2_BAD_VALUE:
1888 return BAD_VALUE;
1889 case C2_BLOCKING:
1890 return WOULD_BLOCK;
1891 case C2_DUPLICATE:
1892 return ALREADY_EXISTS;
1893 case C2_NO_INIT:
1894 return NO_INIT;
1895 case C2_NO_MEMORY:
1896 return NO_MEMORY;
1897 case C2_NOT_FOUND:
1898 return NAME_NOT_FOUND;
1899 case C2_TIMED_OUT:
1900 return TIMED_OUT;
1901 case C2_BAD_STATE:
1902 case C2_CANCELED:
1903 case C2_CANNOT_DO:
1904 case C2_CORRUPTED:
1905 case C2_OMITTED:
1906 case C2_REFUSED:
1907 return UNKNOWN_ERROR;
1908 default:
1909 return -static_cast<status_t>(c2s);
1910 }
1911}
1912
1913} // namespace android