blob: 7d80ef3e8c34564f83f9655d262c7c2405576ed2 [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);
Wonsik Kim936a89c2020-05-08 16:07:50 -0700716 if (!output->buffers || 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
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700871 hdr.validTypes = HdrMetadata::SMPTE2086;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800872 hdr.smpte2086 = smpte2086_meta;
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700873
874 // If the content light level fields are 0, do not use them, it
875 // indicates the value may not be present in the stream.
876 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
877 struct android_cta861_3_metadata cta861_meta = {
878 .maxContentLightLevel = hdrStaticInfo->maxCll,
879 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
880 };
881 hdr.validTypes |= HdrMetadata::CTA861_3;
882 hdr.cta8613 = cta861_meta;
883 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800884 }
885 if (hdr10PlusInfo) {
886 hdr.validTypes |= HdrMetadata::HDR10PLUS;
887 hdr.hdr10plus.assign(
888 hdr10PlusInfo->m.value,
889 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
890 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800891 qbi.setHdrMetadata(hdr);
892 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800893 // we don't have dirty regions
894 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800895 android::IGraphicBufferProducer::QueueBufferOutput qbo;
896 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
897 if (result != OK) {
898 ALOGI("[%s] queueBuffer failed: %d", mName, result);
899 return result;
900 }
901 ALOGV("[%s] queue buffer successful", mName);
902
903 int64_t mediaTimeUs = 0;
904 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
905 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
906
907 return OK;
908}
909
910status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
911 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
912 bool released = false;
913 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700914 Mutexed<Input>::Locked input(mInput);
915 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800916 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800917 }
918 }
919 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700920 Mutexed<Output>::Locked output(mOutput);
921 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800922 released = true;
923 }
924 }
925 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800926 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800927 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800928 } else {
929 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
930 }
931 return OK;
932}
933
934void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
935 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700936 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800937
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700938 if (!input->buffers->isArrayMode()) {
939 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800940 }
941
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700942 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800943}
944
945void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
946 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700947 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800948
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700949 if (!output->buffers->isArrayMode()) {
950 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800951 }
952
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700953 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800954}
955
956status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800957 const sp<AMessage> &inputFormat,
958 const sp<AMessage> &outputFormat,
959 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800960 C2StreamBufferTypeSetting::input iStreamFormat(0u);
961 C2StreamBufferTypeSetting::output oStreamFormat(0u);
962 C2PortReorderBufferDepthTuning::output reorderDepth;
963 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800964 C2PortActualDelayTuning::input inputDelay(0);
965 C2PortActualDelayTuning::output outputDelay(0);
966 C2ActualPipelineDelayTuning pipelineDelay(0);
967
Pawin Vongmasa36653902018-11-15 00:10:25 -0800968 c2_status_t err = mComponent->query(
969 {
970 &iStreamFormat,
971 &oStreamFormat,
972 &reorderDepth,
973 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800974 &inputDelay,
975 &pipelineDelay,
976 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800977 },
978 {},
979 C2_DONT_BLOCK,
980 nullptr);
981 if (err == C2_BAD_INDEX) {
982 if (!iStreamFormat || !oStreamFormat) {
983 return UNKNOWN_ERROR;
984 }
985 } else if (err != C2_OK) {
986 return UNKNOWN_ERROR;
987 }
988
Wonsik Kima4e049d2020-04-28 19:42:23 +0000989 {
990 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
991 reorder->clear();
992 if (reorderDepth) {
993 reorder->setDepth(reorderDepth.value);
994 }
995 if (reorderKey) {
996 reorder->setKey(reorderKey.value);
997 }
998 }
999
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001000 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1001 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1002 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1003
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001004 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1005 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001006
Pawin Vongmasa36653902018-11-15 00:10:25 -08001007 // TODO: get this from input format
1008 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1009
1010 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001011 int poolMask = GetCodec2PoolMask();
1012 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001013
1014 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001015 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001016 std::shared_ptr<C2BlockPool> pool;
1017 {
1018 Mutexed<BlockPools>::Locked pools(mBlockPools);
1019
1020 // set default allocator ID.
1021 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001022 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001023
1024 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1025 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1026 std::vector<std::unique_ptr<C2Param>> params;
1027 err = mComponent->query({ },
1028 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1029 C2_DONT_BLOCK,
1030 &params);
1031 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1032 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1033 mName, params.size(), asString(err), err);
1034 } else if (err == C2_OK && params.size() == 1) {
1035 C2PortAllocatorsTuning::input *inputAllocators =
1036 C2PortAllocatorsTuning::input::From(params[0].get());
1037 if (inputAllocators && inputAllocators->flexCount() > 0) {
1038 std::shared_ptr<C2Allocator> allocator;
1039 // verify allocator IDs and resolve default allocator
1040 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1041 if (allocator) {
1042 pools->inputAllocatorId = allocator->getId();
1043 } else {
1044 ALOGD("[%s] component requested invalid input allocator ID %u",
1045 mName, inputAllocators->m.values[0]);
1046 }
1047 }
1048 }
1049
1050 // TODO: use C2Component wrapper to associate this pool with ourselves
1051 if ((poolMask >> pools->inputAllocatorId) & 1) {
1052 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1053 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1054 mName, pools->inputAllocatorId,
1055 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1056 asString(err), err);
1057 } else {
1058 err = C2_NOT_FOUND;
1059 }
1060 if (err != C2_OK) {
1061 C2BlockPool::local_id_t inputPoolId =
1062 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1063 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1064 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1065 mName, (unsigned long long)inputPoolId,
1066 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1067 asString(err), err);
1068 if (err != C2_OK) {
1069 return NO_MEMORY;
1070 }
1071 }
1072 pools->inputPool = pool;
1073 }
1074
Wonsik Kim51051262018-11-28 13:59:05 -08001075 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001076 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001077 input->inputDelay = inputDelayValue;
1078 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001079 input->numSlots = numInputSlots;
1080 input->extraBuffers.flush();
1081 input->numExtraSlots = 0u;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001082 if (!buffersBoundToCodec) {
1083 input->buffers.reset(new SlotInputBuffers(mName));
1084 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001085 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001086 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001087 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001088 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001089 // This is to ensure buffers do not get released prematurely.
1090 // TODO: handle this without going into array mode
1091 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001092 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001093 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001094 }
1095 } else {
1096 if (hasCryptoOrDescrambler()) {
1097 int32_t capacity = kLinearBufferSize;
1098 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1099 if ((size_t)capacity > kMaxLinearBufferSize) {
1100 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1101 capacity = kMaxLinearBufferSize;
1102 }
1103 if (mDealer == nullptr) {
1104 mDealer = new MemoryDealer(
1105 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001106 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001107 "EncryptedLinearInputBuffers");
1108 mDecryptDestination = mDealer->allocate((size_t)capacity);
1109 }
1110 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001111 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1112 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001113 } else {
1114 mHeapSeqNum = -1;
1115 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001116 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001117 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001118 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001119 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001120 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001121 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001122 }
1123 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001124 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001125
1126 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001127 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001128 } else {
1129 // TODO: error
1130 }
Wonsik Kim51051262018-11-28 13:59:05 -08001131
1132 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001133 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001134 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001135 }
1136
1137 if (outputFormat != nullptr) {
1138 sp<IGraphicBufferProducer> outputSurface;
1139 uint32_t outputGeneration;
1140 {
1141 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001142 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001143 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001144 if (!secure) {
1145 output->maxDequeueBuffers += numInputSlots;
1146 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001147 outputSurface = output->surface ?
1148 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001149 if (outputSurface) {
1150 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1151 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001152 outputGeneration = output->generation;
1153 }
1154
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001155 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001156 C2BlockPool::local_id_t outputPoolId_;
1157
1158 {
1159 Mutexed<BlockPools>::Locked pools(mBlockPools);
1160
1161 // set default allocator ID.
1162 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001163 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001164
1165 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1166 // unsuccessful.
1167 std::vector<std::unique_ptr<C2Param>> params;
1168 err = mComponent->query({ },
1169 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1170 C2_DONT_BLOCK,
1171 &params);
1172 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1173 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1174 mName, params.size(), asString(err), err);
1175 } else if (err == C2_OK && params.size() == 1) {
1176 C2PortAllocatorsTuning::output *outputAllocators =
1177 C2PortAllocatorsTuning::output::From(params[0].get());
1178 if (outputAllocators && outputAllocators->flexCount() > 0) {
1179 std::shared_ptr<C2Allocator> allocator;
1180 // verify allocator IDs and resolve default allocator
1181 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1182 if (allocator) {
1183 pools->outputAllocatorId = allocator->getId();
1184 } else {
1185 ALOGD("[%s] component requested invalid output allocator ID %u",
1186 mName, outputAllocators->m.values[0]);
1187 }
1188 }
1189 }
1190
1191 // use bufferqueue if outputting to a surface.
1192 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1193 // if unsuccessful.
1194 if (outputSurface) {
1195 params.clear();
1196 err = mComponent->query({ },
1197 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1198 C2_DONT_BLOCK,
1199 &params);
1200 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1201 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1202 mName, params.size(), asString(err), err);
1203 } else if (err == C2_OK && params.size() == 1) {
1204 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1205 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1206 if (surfaceAllocator) {
1207 std::shared_ptr<C2Allocator> allocator;
1208 // verify allocator IDs and resolve default allocator
1209 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1210 if (allocator) {
1211 pools->outputAllocatorId = allocator->getId();
1212 } else {
1213 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1214 mName, surfaceAllocator->value);
1215 err = C2_BAD_VALUE;
1216 }
1217 }
1218 }
1219 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1220 && err != C2_OK
1221 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1222 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1223 }
1224 }
1225
1226 if ((poolMask >> pools->outputAllocatorId) & 1) {
1227 err = mComponent->createBlockPool(
1228 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1229 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1230 mName, pools->outputAllocatorId,
1231 (unsigned long long)pools->outputPoolId,
1232 asString(err));
1233 } else {
1234 err = C2_NOT_FOUND;
1235 }
1236 if (err != C2_OK) {
1237 // use basic pool instead
1238 pools->outputPoolId =
1239 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1240 }
1241
1242 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1243 // component.
1244 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1245 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1246
1247 std::vector<std::unique_ptr<C2SettingResult>> failures;
1248 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1249 ALOGD("[%s] Configured output block pool ids %llu => %s",
1250 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1251 outputPoolId_ = pools->outputPoolId;
1252 }
1253
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001254 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001255 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001256 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001257 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001258 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001259 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001260 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001261 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001262 }
1263 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001264 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001265 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001266 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001267
1268
1269 // Try to set output surface to created block pool if given.
1270 if (outputSurface) {
1271 mComponent->setOutputSurface(
1272 outputPoolId_,
1273 outputSurface,
1274 outputGeneration);
1275 }
1276
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001277 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001278 if (buffersBoundToCodec) {
1279 // WORKAROUND: if we're using early CSD workaround we convert to
1280 // array mode, to appease apps assuming the output
1281 // buffers to be of the same size.
1282 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1283 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001284
1285 int32_t channelCount;
1286 int32_t sampleRate;
1287 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1288 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1289 int32_t delay = 0;
1290 int32_t padding = 0;;
1291 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1292 delay = 0;
1293 }
1294 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1295 padding = 0;
1296 }
1297 if (delay || padding) {
1298 // We need write access to the buffers, and we're already in
1299 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001300 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001301 }
1302 }
1303 }
1304 }
1305
1306 // Set up pipeline control. This has to be done after mInputBuffers and
1307 // mOutputBuffers are initialized to make sure that lingering callbacks
1308 // about buffers from the previous generation do not interfere with the
1309 // newly initialized pipeline capacity.
1310
Wonsik Kimab34ed62019-01-31 15:28:46 -08001311 {
1312 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001313 watcher->inputDelay(inputDelayValue)
1314 .pipelineDelay(pipelineDelayValue)
1315 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001316 .smoothnessFactor(kSmoothnessFactor);
1317 watcher->flush();
1318 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001319
1320 mInputMetEos = false;
1321 mSync.start();
1322 return OK;
1323}
1324
1325status_t CCodecBufferChannel::requestInitialInputBuffers() {
1326 if (mInputSurface) {
1327 return OK;
1328 }
1329
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001330 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001331 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1332 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1333 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001334 return UNKNOWN_ERROR;
1335 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001336 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001337 std::vector<sp<MediaCodecBuffer>> toBeQueued;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001338 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001339 size_t index;
1340 sp<MediaCodecBuffer> buffer;
1341 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001342 Mutexed<Input>::Locked input(mInput);
1343 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001344 if (i == 0) {
1345 ALOGW("[%s] start: cannot allocate memory at all", mName);
1346 return NO_MEMORY;
1347 } else {
1348 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
1349 mName, i);
1350 }
1351 break;
1352 }
1353 }
1354 if (buffer) {
1355 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1356 ALOGV("[%s] input buffer %zu available", mName, index);
1357 bool post = true;
1358 if (!configs->empty()) {
1359 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001360 configs->pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001361 if (buffer->capacity() >= config->size()) {
1362 memcpy(buffer->base(), config->data(), config->size());
1363 buffer->setRange(0, config->size());
1364 buffer->meta()->clear();
1365 buffer->meta()->setInt64("timeUs", 0);
1366 buffer->meta()->setInt32("csd", 1);
1367 post = false;
1368 } else {
1369 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
1370 mName, buffer->capacity(), config->size());
1371 }
1372 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001373 && (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001374 // WORKAROUND: Some apps expect CSD available without queueing
1375 // any input. Queue an empty buffer to get the CSD.
1376 buffer->setRange(0, 0);
1377 buffer->meta()->clear();
1378 buffer->meta()->setInt64("timeUs", 0);
1379 post = false;
1380 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001381 if (post) {
1382 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001383 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001384 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001385 }
1386 }
1387 }
1388 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
1389 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001390 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001391 }
1392 }
1393 return OK;
1394}
1395
1396void CCodecBufferChannel::stop() {
1397 mSync.stop();
1398 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1399 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001400 mInputSurface.reset();
1401 }
1402}
1403
Wonsik Kim936a89c2020-05-08 16:07:50 -07001404void CCodecBufferChannel::reset() {
1405 stop();
1406 {
1407 Mutexed<Input>::Locked input(mInput);
1408 input->buffers.reset(new DummyInputBuffers(""));
1409 }
1410 {
1411 Mutexed<Output>::Locked output(mOutput);
1412 output->buffers.reset();
1413 }
1414}
1415
1416void CCodecBufferChannel::release() {
1417 mComponent.reset();
1418 mInputAllocator.reset();
1419 mOutputSurface.lock()->surface.clear();
1420 {
1421 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1422 blockPools->inputPool.reset();
1423 blockPools->outputPoolIntf.reset();
1424 }
1425}
1426
1427
Pawin Vongmasa36653902018-11-15 00:10:25 -08001428void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1429 ALOGV("[%s] flush", mName);
1430 {
1431 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1432 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1433 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1434 continue;
1435 }
1436 if (work->input.buffers.empty()
1437 || work->input.buffers.front()->data().linearBlocks().empty()) {
1438 ALOGD("[%s] no linear codec config data found", mName);
1439 continue;
1440 }
1441 C2ReadView view =
1442 work->input.buffers.front()->data().linearBlocks().front().map().get();
1443 if (view.error() != C2_OK) {
1444 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1445 continue;
1446 }
1447 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1448 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1449 }
1450 }
1451 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001452 Mutexed<Input>::Locked input(mInput);
1453 input->buffers->flush();
1454 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001455 }
1456 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001457 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001458 if (output->buffers) {
1459 output->buffers->flush(flushedWork);
1460 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001461 }
Wonsik Kima4e049d2020-04-28 19:42:23 +00001462 mReorderStash.lock()->flush();
Wonsik Kimab34ed62019-01-31 15:28:46 -08001463 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001464}
1465
1466void CCodecBufferChannel::onWorkDone(
1467 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001468 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001469 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001470 feedInputBufferIfAvailable();
1471 }
1472}
1473
1474void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001475 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001476 if (mInputSurface) {
1477 return;
1478 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001479 std::shared_ptr<C2Buffer> buffer =
1480 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001481 bool newInputSlotAvailable;
1482 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001483 Mutexed<Input>::Locked input(mInput);
1484 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1485 if (!newInputSlotAvailable) {
1486 (void)input->extraBuffers.expireComponentBuffer(buffer);
1487 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001488 }
1489 if (newInputSlotAvailable) {
1490 feedInputBufferIfAvailable();
1491 }
1492}
1493
1494bool CCodecBufferChannel::handleWork(
1495 std::unique_ptr<C2Work> work,
1496 const sp<AMessage> &outputFormat,
1497 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001498 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001499 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001500 if (!output->buffers) {
1501 return false;
1502 }
1503 if (outputFormat != nullptr) {
1504 ALOGD("[%s] onWorkDone: output format changed to %s",
1505 mName, outputFormat->debugString().c_str());
1506 output->buffers->setFormat(outputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001507
Wonsik Kim936a89c2020-05-08 16:07:50 -07001508 AString mediaType;
1509 if (outputFormat->findString(KEY_MIME, &mediaType)
1510 && mediaType == MIMETYPE_AUDIO_RAW) {
1511 int32_t channelCount;
1512 int32_t sampleRate;
1513 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1514 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1515 output->buffers->updateSkipCutBuffer(sampleRate, channelCount);
1516 }
Wonsik Kima4e049d2020-04-28 19:42:23 +00001517 }
1518 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001519 }
1520
Wonsik Kima4e049d2020-04-28 19:42:23 +00001521 if ((work->input.ordinal.frameIndex - mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001522 // Discard frames from previous generation.
1523 ALOGD("[%s] Discard frames from previous generation.", mName);
Wonsik Kima4e049d2020-04-28 19:42:23 +00001524 return false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001525 }
1526
Wonsik Kim524b0582019-03-12 11:28:57 -07001527 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001528 || !work->worklets.front()
Wonsik Kima4e049d2020-04-28 19:42:23 +00001529 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE))) {
1530 mPipelineWatcher.lock()->onWorkDone(work->input.ordinal.frameIndex.peeku());
1531 }
1532
1533 if (work->result == C2_NOT_FOUND) {
1534 ALOGD("[%s] flushed work; ignored.", mName);
1535 return true;
1536 }
1537
1538 if (work->result != C2_OK) {
1539 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1540 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1541 return false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001542 }
1543
1544 // NOTE: MediaCodec usage supposedly have only one worklet
1545 if (work->worklets.size() != 1u) {
1546 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1547 mName, work->worklets.size());
1548 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1549 return false;
1550 }
1551
1552 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1553
1554 std::shared_ptr<C2Buffer> buffer;
1555 // NOTE: MediaCodec usage supposedly have only one output stream.
1556 if (worklet->output.buffers.size() > 1u) {
1557 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1558 mName, worklet->output.buffers.size());
1559 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1560 return false;
1561 } else if (worklet->output.buffers.size() == 1u) {
1562 buffer = worklet->output.buffers[0];
1563 if (!buffer) {
1564 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1565 }
1566 }
1567
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001568 std::optional<uint32_t> newInputDelay, newPipelineDelay;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001569 while (!worklet->output.configUpdate.empty()) {
1570 std::unique_ptr<C2Param> param;
1571 worklet->output.configUpdate.back().swap(param);
1572 worklet->output.configUpdate.pop_back();
1573 switch (param->coreIndex().coreIndex()) {
1574 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1575 C2PortReorderBufferDepthTuning::output reorderDepth;
1576 if (reorderDepth.updateFrom(*param)) {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001577 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1578 mReorderStash.lock()->setDepth(reorderDepth.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001579 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1580 mName, reorderDepth.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001581 size_t numOutputSlots = mOutput.lock()->numSlots;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001582 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001583 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001584 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001585 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001586 if (!secure) {
1587 output->maxDequeueBuffers += numInputSlots;
1588 }
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001589 if (output->surface) {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001590 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001591 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001592 } else {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001593 ALOGD("[%s] onWorkDone: failed to read reorder depth", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001594 }
1595 break;
1596 }
1597 case C2PortReorderKeySetting::CORE_INDEX: {
1598 C2PortReorderKeySetting::output reorderKey;
1599 if (reorderKey.updateFrom(*param)) {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001600 mReorderStash.lock()->setKey(reorderKey.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001601 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1602 mName, reorderKey.value);
1603 } else {
1604 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1605 }
1606 break;
1607 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001608 case C2PortActualDelayTuning::CORE_INDEX: {
1609 if (param->isGlobal()) {
1610 C2ActualPipelineDelayTuning pipelineDelay;
1611 if (pipelineDelay.updateFrom(*param)) {
1612 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1613 mName, pipelineDelay.value);
1614 newPipelineDelay = pipelineDelay.value;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001615 (void)mPipelineWatcher.lock()->pipelineDelay(pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001616 }
1617 }
1618 if (param->forInput()) {
1619 C2PortActualDelayTuning::input inputDelay;
1620 if (inputDelay.updateFrom(*param)) {
1621 ALOGV("[%s] onWorkDone: updating input delay %u",
1622 mName, inputDelay.value);
1623 newInputDelay = inputDelay.value;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001624 (void)mPipelineWatcher.lock()->inputDelay(inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001625 }
1626 }
1627 if (param->forOutput()) {
1628 C2PortActualDelayTuning::output outputDelay;
1629 if (outputDelay.updateFrom(*param)) {
1630 ALOGV("[%s] onWorkDone: updating output delay %u",
1631 mName, outputDelay.value);
Wonsik Kima4e049d2020-04-28 19:42:23 +00001632 bool secure = mComponent->getName().find(".secure") != std::string::npos;
1633 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001634
1635 bool outputBuffersChanged = false;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001636 size_t numOutputSlots = 0;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001637 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001638 {
1639 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001640 if (!output->buffers) {
1641 return false;
1642 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001643 output->outputDelay = outputDelay.value;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001644 numOutputSlots = outputDelay.value + kSmoothnessFactor;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001645 if (output->numSlots < numOutputSlots) {
1646 output->numSlots = numOutputSlots;
1647 if (output->buffers->isArrayMode()) {
1648 OutputBuffersArray *array =
1649 (OutputBuffersArray *)output->buffers.get();
1650 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1651 mName, numOutputSlots);
1652 array->grow(numOutputSlots);
1653 outputBuffersChanged = true;
1654 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001655 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001656 numOutputSlots = output->numSlots;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001657 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001658
1659 if (outputBuffersChanged) {
1660 mCCodecCallback->onOutputBuffersChanged();
1661 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001662
Wonsik Kima4e049d2020-04-28 19:42:23 +00001663 uint32_t depth = mReorderStash.lock()->depth();
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001664 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001665 output->maxDequeueBuffers = numOutputSlots + depth + kRenderingDepth;
1666 if (!secure) {
1667 output->maxDequeueBuffers += numInputSlots;
1668 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001669 if (output->surface) {
1670 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1671 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001672 }
1673 }
1674 break;
1675 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001676 default:
1677 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1678 mName, param->index());
1679 break;
1680 }
1681 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001682 if (newInputDelay || newPipelineDelay) {
1683 Mutexed<Input>::Locked input(mInput);
1684 size_t newNumSlots =
1685 newInputDelay.value_or(input->inputDelay) +
1686 newPipelineDelay.value_or(input->pipelineDelay) +
1687 kSmoothnessFactor;
1688 if (input->buffers->isArrayMode()) {
1689 if (input->numSlots >= newNumSlots) {
1690 input->numExtraSlots = 0;
1691 } else {
1692 input->numExtraSlots = newNumSlots - input->numSlots;
1693 }
1694 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1695 mName, input->numExtraSlots);
1696 } else {
1697 input->numSlots = newNumSlots;
1698 }
1699 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001700
Pawin Vongmasa36653902018-11-15 00:10:25 -08001701 int32_t flags = 0;
1702 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1703 flags |= MediaCodec::BUFFER_FLAG_EOS;
1704 ALOGV("[%s] onWorkDone: output EOS", mName);
1705 }
1706
Wonsik Kima4e049d2020-04-28 19:42:23 +00001707 sp<MediaCodecBuffer> outBuffer;
1708 size_t index;
1709
Pawin Vongmasa36653902018-11-15 00:10:25 -08001710 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1711 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1712 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1713 // shall correspond to the client input timesamp (in customOrdinal). By using the
1714 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1715 // produces multiple output.
1716 c2_cntr64_t timestamp =
1717 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1718 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001719 if (mInputSurface != nullptr) {
1720 // When using input surface we need to restore the original input timestamp.
1721 timestamp = work->input.ordinal.customOrdinal;
1722 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001723 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1724 mName,
1725 work->input.ordinal.customOrdinal.peekll(),
1726 work->input.ordinal.timestamp.peekll(),
1727 worklet->output.ordinal.timestamp.peekll(),
1728 timestamp.peekll());
1729
1730 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001731 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001732 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001733 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1734 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1735 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1736
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001737 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001738 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001739 } else {
1740 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001741 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001742 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001743 return false;
1744 }
1745 }
1746
Wonsik Kim910a3172020-04-29 16:58:16 -07001747 if (!buffer && !flags && outputFormat == nullptr) {
1748 ALOGV("[%s] onWorkDone: nothing to report from the work (%lld)",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001749 mName, work->input.ordinal.frameIndex.peekull());
Wonsik Kima4e049d2020-04-28 19:42:23 +00001750 return true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001751 }
1752
1753 if (buffer) {
1754 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1755 // TODO: properly translate these to metadata
1756 switch (info->coreIndex().coreIndex()) {
1757 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001758 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001759 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1760 }
1761 break;
1762 default:
1763 break;
1764 }
1765 }
1766 }
1767
1768 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001769 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1770 reorder->emplace(buffer, timestamp.peek(), flags, worklet->output.ordinal);
1771 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
1772 // Flush reorder stash
1773 reorder->setDepth(0);
1774 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001775 }
1776 sendOutputBuffers();
1777 return true;
1778}
1779
1780void CCodecBufferChannel::sendOutputBuffers() {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001781 ReorderStash::Entry entry;
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001782 sp<MediaCodecBuffer> outBuffer;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001783 size_t index;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001784
1785 while (true) {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001786 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1787 if (!reorder->hasPending()) {
1788 break;
1789 }
1790 if (!reorder->pop(&entry)) {
1791 break;
1792 }
1793
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001794 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001795 if (!output->buffers) {
1796 return;
1797 }
Wonsik Kima4e049d2020-04-28 19:42:23 +00001798 status_t err = output->buffers->registerBuffer(entry.buffer, &index, &outBuffer);
1799 if (err != OK) {
1800 bool outputBuffersChanged = false;
1801 if (err != WOULD_BLOCK) {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001802 if (!output->buffers->isArrayMode()) {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001803 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001804 }
Wonsik Kima4e049d2020-04-28 19:42:23 +00001805 OutputBuffersArray *array = (OutputBuffersArray *)output->buffers.get();
1806 array->realloc(entry.buffer);
1807 outputBuffersChanged = true;
1808 }
1809 ALOGV("[%s] sendOutputBuffers: unable to register output buffer", mName);
1810 reorder->defer(entry);
1811
1812 output.unlock();
1813 reorder.unlock();
1814
1815 if (outputBuffersChanged) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001816 mCCodecCallback->onOutputBuffersChanged();
1817 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001818 return;
1819 }
Wonsik Kima4e049d2020-04-28 19:42:23 +00001820 output.unlock();
1821 reorder.unlock();
1822
1823 outBuffer->meta()->setInt64("timeUs", entry.timestamp);
1824 outBuffer->meta()->setInt32("flags", entry.flags);
1825 ALOGV("[%s] sendOutputBuffers: out buffer index = %zu [%p] => %p + %zu (%lld)",
1826 mName, index, outBuffer.get(), outBuffer->data(), outBuffer->size(),
1827 (long long)entry.timestamp);
1828 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001829 }
1830}
1831
1832status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1833 static std::atomic_uint32_t surfaceGeneration{0};
1834 uint32_t generation = (getpid() << 10) |
1835 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1836 & ((1 << 10) - 1));
1837
1838 sp<IGraphicBufferProducer> producer;
1839 if (newSurface) {
1840 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001841 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Lee08515812019-06-05 11:16:32 -07001842 newSurface->setMaxDequeuedBufferCount(mOutputSurface.lock()->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001843 producer = newSurface->getIGraphicBufferProducer();
1844 producer->setGenerationNumber(generation);
1845 } else {
1846 ALOGE("[%s] setting output surface to null", mName);
1847 return INVALID_OPERATION;
1848 }
1849
1850 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1851 C2BlockPool::local_id_t outputPoolId;
1852 {
1853 Mutexed<BlockPools>::Locked pools(mBlockPools);
1854 outputPoolId = pools->outputPoolId;
1855 outputPoolIntf = pools->outputPoolIntf;
1856 }
1857
1858 if (outputPoolIntf) {
1859 if (mComponent->setOutputSurface(
1860 outputPoolId,
1861 producer,
1862 generation) != C2_OK) {
1863 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1864 return INVALID_OPERATION;
1865 }
1866 }
1867
1868 {
1869 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1870 output->surface = newSurface;
1871 output->generation = generation;
1872 }
1873
1874 return OK;
1875}
1876
Wonsik Kimab34ed62019-01-31 15:28:46 -08001877PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001878 // When client pushed EOS, we want all the work to be done quickly.
1879 // Otherwise, component may have stalled work due to input starvation up to
1880 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001881 size_t n = 0;
1882 if (!mInputMetEos) {
1883 size_t outputDelay = mOutput.lock()->outputDelay;
1884 Mutexed<Input>::Locked input(mInput);
1885 n = input->inputDelay + input->pipelineDelay + outputDelay;
1886 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001887 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001888}
1889
Pawin Vongmasa36653902018-11-15 00:10:25 -08001890void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1891 mMetaMode = mode;
1892}
1893
Wonsik Kim596187e2019-10-25 12:44:10 -07001894void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001895 if (mCrypto != nullptr) {
1896 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
1897 mCrypto->unsetHeap(entry.second);
1898 }
1899 mHeapSeqNumMap.clear();
1900 if (mHeapSeqNum >= 0) {
1901 mCrypto->unsetHeap(mHeapSeqNum);
1902 mHeapSeqNum = -1;
1903 }
1904 }
Wonsik Kim596187e2019-10-25 12:44:10 -07001905 mCrypto = crypto;
1906}
1907
1908void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
1909 mDescrambler = descrambler;
1910}
1911
Pawin Vongmasa36653902018-11-15 00:10:25 -08001912status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1913 // C2_OK is always translated to OK.
1914 if (c2s == C2_OK) {
1915 return OK;
1916 }
1917
1918 // Operation-dependent translation
1919 // TODO: Add as necessary
1920 switch (c2op) {
1921 case C2_OPERATION_Component_start:
1922 switch (c2s) {
1923 case C2_NO_MEMORY:
1924 return NO_MEMORY;
1925 default:
1926 return UNKNOWN_ERROR;
1927 }
1928 default:
1929 break;
1930 }
1931
1932 // Backup operation-agnostic translation
1933 switch (c2s) {
1934 case C2_BAD_INDEX:
1935 return BAD_INDEX;
1936 case C2_BAD_VALUE:
1937 return BAD_VALUE;
1938 case C2_BLOCKING:
1939 return WOULD_BLOCK;
1940 case C2_DUPLICATE:
1941 return ALREADY_EXISTS;
1942 case C2_NO_INIT:
1943 return NO_INIT;
1944 case C2_NO_MEMORY:
1945 return NO_MEMORY;
1946 case C2_NOT_FOUND:
1947 return NAME_NOT_FOUND;
1948 case C2_TIMED_OUT:
1949 return TIMED_OUT;
1950 case C2_BAD_STATE:
1951 case C2_CANCELED:
1952 case C2_CANNOT_DO:
1953 case C2_CORRUPTED:
1954 case C2_OMITTED:
1955 case C2_REFUSED:
1956 return UNKNOWN_ERROR;
1957 default:
1958 return -static_cast<status_t>(c2s);
1959 }
1960}
1961
1962} // namespace android