blob: d80bfd2ac9f9fa16c789267ce9eec19c37aef57f [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
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070021#include <algorithm>
22#include <list>
Pawin Vongmasa36653902018-11-15 00:10:25 -080023#include <numeric>
24
25#include <C2AllocatorGralloc.h>
26#include <C2PlatformSupport.h>
27#include <C2BlockInternal.h>
28#include <C2Config.h>
29#include <C2Debug.h>
30
31#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070032#include <android/hardware/drm/1.0/types.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080033#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080034#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080035#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070036#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080037#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070038#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080039#include <media/openmax/OMX_Core.h>
40#include <media/stagefright/foundation/ABuffer.h>
41#include <media/stagefright/foundation/ALookup.h>
42#include <media/stagefright/foundation/AMessage.h>
43#include <media/stagefright/foundation/AUtils.h>
44#include <media/stagefright/foundation/hexdump.h>
45#include <media/stagefright/MediaCodec.h>
46#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070047#include <media/stagefright/SkipCutBuffer.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080048#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070049#include <mediadrm/ICrypto.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080050#include <system/window.h>
51
52#include "CCodecBufferChannel.h"
53#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080054
55namespace android {
56
57using android::base::StringPrintf;
58using hardware::hidl_handle;
59using hardware::hidl_string;
60using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070061using hardware::fromHeap;
62using hardware::HidlMemory;
63
Pawin Vongmasa36653902018-11-15 00:10:25 -080064using namespace hardware::cas::V1_0;
65using namespace hardware::cas::native::V1_0;
66
67using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070068using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080069
Pawin Vongmasa36653902018-11-15 00:10:25 -080070namespace {
71
Wonsik Kim469c8342019-04-11 16:46:09 -070072constexpr size_t kSmoothnessFactor = 4;
73constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080074
Sungtak Leeab6f2f32019-02-15 14:43:51 -080075// This is for keeping IGBP's buffer dropping logic in legacy mode other
76// than making it non-blocking. Do not change this value.
77const static size_t kDequeueTimeoutNs = 0;
78
Pawin Vongmasa36653902018-11-15 00:10:25 -080079} // namespace
80
81CCodecBufferChannel::QueueGuard::QueueGuard(
82 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
83 Mutex::Autolock l(mSync.mGuardLock);
84 // At this point it's guaranteed that mSync is not under state transition,
85 // as we are holding its mutex.
86
87 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
88 if (count->value == -1) {
89 mRunning = false;
90 } else {
91 ++count->value;
92 mRunning = true;
93 }
94}
95
96CCodecBufferChannel::QueueGuard::~QueueGuard() {
97 if (mRunning) {
98 // We are not holding mGuardLock at this point so that QueueSync::stop() can
99 // keep holding the lock until mCount reaches zero.
100 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
101 --count->value;
102 count->cond.broadcast();
103 }
104}
105
106void CCodecBufferChannel::QueueSync::start() {
107 Mutex::Autolock l(mGuardLock);
108 // If stopped, it goes to running state; otherwise no-op.
109 Mutexed<Counter>::Locked count(mCount);
110 if (count->value == -1) {
111 count->value = 0;
112 }
113}
114
115void CCodecBufferChannel::QueueSync::stop() {
116 Mutex::Autolock l(mGuardLock);
117 Mutexed<Counter>::Locked count(mCount);
118 if (count->value == -1) {
119 // no-op
120 return;
121 }
122 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
123 // mCount can only decrement. In other words, threads that acquired the lock
124 // are allowed to finish execution but additional threads trying to acquire
125 // the lock at this point will block, and then get QueueGuard at STOPPED
126 // state.
127 while (count->value != 0) {
128 count.waitForCondition(count->cond);
129 }
130 count->value = -1;
131}
132
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700133// Input
134
135CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
136
Pawin Vongmasa36653902018-11-15 00:10:25 -0800137// CCodecBufferChannel
138
139CCodecBufferChannel::CCodecBufferChannel(
140 const std::shared_ptr<CCodecCallback> &callback)
141 : mHeapSeqNum(-1),
142 mCCodecCallback(callback),
143 mFrameIndex(0u),
144 mFirstValidFrameIndex(0u),
145 mMetaMode(MODE_NONE),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800146 mInputMetEos(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700147 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700148 {
149 Mutexed<Input>::Locked input(mInput);
150 input->buffers.reset(new DummyInputBuffers(""));
151 input->extraBuffers.flush();
152 input->inputDelay = 0u;
153 input->pipelineDelay = 0u;
154 input->numSlots = kSmoothnessFactor;
155 input->numExtraSlots = 0u;
156 }
157 {
158 Mutexed<Output>::Locked output(mOutput);
159 output->outputDelay = 0u;
160 output->numSlots = kSmoothnessFactor;
161 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800162}
163
164CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800165 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800166 mCrypto->unsetHeap(mHeapSeqNum);
167 }
168}
169
170void CCodecBufferChannel::setComponent(
171 const std::shared_ptr<Codec2Client::Component> &component) {
172 mComponent = component;
173 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
174 mName = mComponentName.c_str();
175}
176
177status_t CCodecBufferChannel::setInputSurface(
178 const std::shared_ptr<InputSurfaceWrapper> &surface) {
179 ALOGV("[%s] setInputSurface", mName);
180 mInputSurface = surface;
181 return mInputSurface->connect(mComponent);
182}
183
184status_t CCodecBufferChannel::signalEndOfInputStream() {
185 if (mInputSurface == nullptr) {
186 return INVALID_OPERATION;
187 }
188 return mInputSurface->signalEndOfInputStream();
189}
190
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700191status_t CCodecBufferChannel::queueInputBufferInternal(sp<MediaCodecBuffer> buffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800192 int64_t timeUs;
193 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
194
195 if (mInputMetEos) {
196 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
197 return OK;
198 }
199
200 int32_t flags = 0;
201 int32_t tmp = 0;
202 bool eos = false;
203 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
204 eos = true;
205 mInputMetEos = true;
206 ALOGV("[%s] input EOS", mName);
207 }
208 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
209 flags |= C2FrameData::FLAG_CODEC_CONFIG;
210 }
211 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
212 std::unique_ptr<C2Work> work(new C2Work);
213 work->input.ordinal.timestamp = timeUs;
214 work->input.ordinal.frameIndex = mFrameIndex++;
215 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
216 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
217 // Keep client timestamp in customOrdinal
218 work->input.ordinal.customOrdinal = timeUs;
219 work->input.buffers.clear();
220
Wonsik Kimab34ed62019-01-31 15:28:46 -0800221 uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
222 std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700223 sp<Codec2Buffer> copy;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800224
Pawin Vongmasa36653902018-11-15 00:10:25 -0800225 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700226 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800227 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700228 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800229 return -ENOENT;
230 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700231 // TODO: we want to delay copying buffers.
232 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
233 copy = input->buffers->cloneAndReleaseBuffer(buffer);
234 if (copy != nullptr) {
235 (void)input->extraBuffers.assignSlot(copy);
236 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
237 return UNKNOWN_ERROR;
238 }
239 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
240 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
241 mName, released ? "" : "not ");
242 buffer.clear();
243 } else {
244 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
245 "buffer starvation on component.", mName);
246 }
247 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800248 work->input.buffers.push_back(c2buffer);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800249 queuedBuffers.push_back(c2buffer);
250 } else if (eos) {
251 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800252 }
253 work->input.flags = (C2FrameData::flags_t)flags;
254 // TODO: fill info's
255
256 work->input.configUpdate = std::move(mParamsToBeSet);
257 work->worklets.clear();
258 work->worklets.emplace_back(new C2Worklet);
259
260 std::list<std::unique_ptr<C2Work>> items;
261 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800262 mPipelineWatcher.lock()->onWorkQueued(
263 queuedFrameIndex,
264 std::move(queuedBuffers),
265 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800266 c2_status_t err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800267 if (err != C2_OK) {
268 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
269 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800270
271 if (err == C2_OK && eos && buffer->size() > 0u) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800272 work.reset(new C2Work);
273 work->input.ordinal.timestamp = timeUs;
274 work->input.ordinal.frameIndex = mFrameIndex++;
275 // WORKAROUND: keep client timestamp in customOrdinal
276 work->input.ordinal.customOrdinal = timeUs;
277 work->input.buffers.clear();
278 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800279 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800280
Wonsik Kimab34ed62019-01-31 15:28:46 -0800281 queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
282 queuedBuffers.clear();
283
Pawin Vongmasa36653902018-11-15 00:10:25 -0800284 items.clear();
285 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800286
287 mPipelineWatcher.lock()->onWorkQueued(
288 queuedFrameIndex,
289 std::move(queuedBuffers),
290 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800291 err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800292 if (err != C2_OK) {
293 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
294 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800295 }
296 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700297 Mutexed<Input>::Locked input(mInput);
298 bool released = false;
299 if (buffer) {
300 released = input->buffers->releaseBuffer(buffer, nullptr, true);
301 } else if (copy) {
302 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
303 }
304 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
305 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800306 }
307
308 feedInputBufferIfAvailableInternal();
309 return err;
310}
311
312status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
313 QueueGuard guard(mSync);
314 if (!guard.isRunning()) {
315 ALOGD("[%s] setParameters is only supported in the running state.", mName);
316 return -ENOSYS;
317 }
318 mParamsToBeSet.insert(mParamsToBeSet.end(),
319 std::make_move_iterator(params.begin()),
320 std::make_move_iterator(params.end()));
321 params.clear();
322 return OK;
323}
324
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800325status_t CCodecBufferChannel::attachBuffer(
326 const std::shared_ptr<C2Buffer> &c2Buffer,
327 const sp<MediaCodecBuffer> &buffer) {
328 if (!buffer->copy(c2Buffer)) {
329 return -ENOSYS;
330 }
331 return OK;
332}
333
334void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
335 if (!mDecryptDestination || mDecryptDestination->size() < size) {
336 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
337 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
338 mCrypto->unsetHeap(mHeapSeqNum);
339 }
340 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
341 if (mCrypto) {
342 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
343 }
344 }
345}
346
347int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
348 CHECK(mCrypto);
349 auto it = mHeapSeqNumMap.find(memory);
350 int32_t heapSeqNum = -1;
351 if (it == mHeapSeqNumMap.end()) {
352 heapSeqNum = mCrypto->setHeap(memory);
353 mHeapSeqNumMap.emplace(memory, heapSeqNum);
354 } else {
355 heapSeqNum = it->second;
356 }
357 return heapSeqNum;
358}
359
360status_t CCodecBufferChannel::attachEncryptedBuffer(
361 const sp<hardware::HidlMemory> &memory,
362 bool secure,
363 const uint8_t *key,
364 const uint8_t *iv,
365 CryptoPlugin::Mode mode,
366 CryptoPlugin::Pattern pattern,
367 size_t offset,
368 const CryptoPlugin::SubSample *subSamples,
369 size_t numSubSamples,
370 const sp<MediaCodecBuffer> &buffer) {
371 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
372 static const C2MemoryUsage kDefaultReadWriteUsage{
373 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
374
375 size_t size = 0;
376 for (size_t i = 0; i < numSubSamples; ++i) {
377 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
378 }
379 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
380 std::shared_ptr<C2LinearBlock> block;
381 c2_status_t err = pool->fetchLinearBlock(
382 size,
383 secure ? kSecureUsage : kDefaultReadWriteUsage,
384 &block);
385 if (err != C2_OK) {
386 return NO_MEMORY;
387 }
388 if (!secure) {
389 ensureDecryptDestination(size);
390 }
391 ssize_t result = -1;
392 ssize_t codecDataOffset = 0;
393 if (mCrypto) {
394 AString errorDetailMsg;
395 int32_t heapSeqNum = getHeapSeqNum(memory);
396 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
397 hardware::drm::V1_0::DestinationBuffer dst;
398 if (secure) {
399 dst.type = DrmBufferType::NATIVE_HANDLE;
400 dst.secureMemory = hardware::hidl_handle(block->handle());
401 } else {
402 dst.type = DrmBufferType::SHARED_MEMORY;
403 IMemoryToSharedBuffer(
404 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
405 }
406 result = mCrypto->decrypt(
407 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
408 dst, &errorDetailMsg);
409 if (result < 0) {
410 return result;
411 }
412 if (dst.type == DrmBufferType::SHARED_MEMORY) {
413 C2WriteView view = block->map().get();
414 if (view.error() != C2_OK) {
415 return false;
416 }
417 if (view.size() < result) {
418 return false;
419 }
420 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
421 }
422 } else {
423 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
424 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
425 hidl_vec<SubSample> hidlSubSamples;
426 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
427
428 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
429 hardware::cas::native::V1_0::DestinationBuffer dst;
430 if (secure) {
431 dst.type = BufferType::NATIVE_HANDLE;
432 dst.secureMemory = hardware::hidl_handle(block->handle());
433 } else {
434 dst.type = BufferType::SHARED_MEMORY;
435 dst.nonsecureMemory = src;
436 }
437
438 CasStatus status = CasStatus::OK;
439 hidl_string detailedError;
440 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
441
442 if (key != nullptr) {
443 sctrl = (ScramblingControl)key[0];
444 // Adjust for the PES offset
445 codecDataOffset = key[2] | (key[3] << 8);
446 }
447
448 auto returnVoid = mDescrambler->descramble(
449 sctrl,
450 hidlSubSamples,
451 src,
452 0,
453 dst,
454 0,
455 [&status, &result, &detailedError] (
456 CasStatus _status, uint32_t _bytesWritten,
457 const hidl_string& _detailedError) {
458 status = _status;
459 result = (ssize_t)_bytesWritten;
460 detailedError = _detailedError;
461 });
462
463 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
464 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
465 mName, returnVoid.description().c_str(), status, result);
466 return UNKNOWN_ERROR;
467 }
468
469 if (result < codecDataOffset) {
470 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
471 return BAD_VALUE;
472 }
473 }
474 if (!secure) {
475 C2WriteView view = block->map().get();
476 if (view.error() != C2_OK) {
477 return UNKNOWN_ERROR;
478 }
479 if (view.size() < result) {
480 return UNKNOWN_ERROR;
481 }
482 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
483 }
484 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
485 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
486 if (!buffer->copy(c2Buffer)) {
487 return -ENOSYS;
488 }
489 return OK;
490}
491
Pawin Vongmasa36653902018-11-15 00:10:25 -0800492status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
493 QueueGuard guard(mSync);
494 if (!guard.isRunning()) {
495 ALOGD("[%s] No more buffers should be queued at current state.", mName);
496 return -ENOSYS;
497 }
498 return queueInputBufferInternal(buffer);
499}
500
501status_t CCodecBufferChannel::queueSecureInputBuffer(
502 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
503 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
504 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
505 AString *errorDetailMsg) {
506 QueueGuard guard(mSync);
507 if (!guard.isRunning()) {
508 ALOGD("[%s] No more buffers should be queued at current state.", mName);
509 return -ENOSYS;
510 }
511
512 if (!hasCryptoOrDescrambler()) {
513 return -ENOSYS;
514 }
515 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
516
517 ssize_t result = -1;
518 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700519 if (numSubSamples == 1
520 && subSamples[0].mNumBytesOfClearData == 0
521 && subSamples[0].mNumBytesOfEncryptedData == 0) {
522 // We don't need to go through crypto or descrambler if the input is empty.
523 result = 0;
524 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700525 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800526 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700527 destination.type = DrmBufferType::NATIVE_HANDLE;
528 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800529 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700530 destination.type = DrmBufferType::SHARED_MEMORY;
531 IMemoryToSharedBuffer(
532 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800533 }
Robert Shih895fba92019-07-16 16:29:44 -0700534 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800535 encryptedBuffer->fillSourceBuffer(&source);
536 result = mCrypto->decrypt(
537 key, iv, mode, pattern, source, buffer->offset(),
538 subSamples, numSubSamples, destination, errorDetailMsg);
539 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700540 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800541 return result;
542 }
Robert Shih895fba92019-07-16 16:29:44 -0700543 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800544 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
545 }
546 } else {
547 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
548 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
549 hidl_vec<SubSample> hidlSubSamples;
550 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
551
552 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
553 encryptedBuffer->fillSourceBuffer(&srcBuffer);
554
555 DestinationBuffer dstBuffer;
556 if (secure) {
557 dstBuffer.type = BufferType::NATIVE_HANDLE;
558 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
559 } else {
560 dstBuffer.type = BufferType::SHARED_MEMORY;
561 dstBuffer.nonsecureMemory = srcBuffer;
562 }
563
564 CasStatus status = CasStatus::OK;
565 hidl_string detailedError;
566 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
567
568 if (key != nullptr) {
569 sctrl = (ScramblingControl)key[0];
570 // Adjust for the PES offset
571 codecDataOffset = key[2] | (key[3] << 8);
572 }
573
574 auto returnVoid = mDescrambler->descramble(
575 sctrl,
576 hidlSubSamples,
577 srcBuffer,
578 0,
579 dstBuffer,
580 0,
581 [&status, &result, &detailedError] (
582 CasStatus _status, uint32_t _bytesWritten,
583 const hidl_string& _detailedError) {
584 status = _status;
585 result = (ssize_t)_bytesWritten;
586 detailedError = _detailedError;
587 });
588
589 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
590 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
591 mName, returnVoid.description().c_str(), status, result);
592 return UNKNOWN_ERROR;
593 }
594
595 if (result < codecDataOffset) {
596 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
597 return BAD_VALUE;
598 }
599
600 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
601
602 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
603 encryptedBuffer->copyDecryptedContentFromMemory(result);
604 }
605 }
606
607 buffer->setRange(codecDataOffset, result - codecDataOffset);
608 return queueInputBufferInternal(buffer);
609}
610
611void CCodecBufferChannel::feedInputBufferIfAvailable() {
612 QueueGuard guard(mSync);
613 if (!guard.isRunning()) {
614 ALOGV("[%s] We're not running --- no input buffer reported", mName);
615 return;
616 }
617 feedInputBufferIfAvailableInternal();
618}
619
620void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900621 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800622 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700623 }
624 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700625 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasac3c536d2020-06-12 04:00:04 -0700626 if (!output->buffers ||
627 output->buffers->hasPending() ||
628 output->buffers->numClientBuffers() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800629 return;
630 }
631 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700632 size_t numInputSlots = mInput.lock()->numSlots;
633 for (size_t i = 0; i < numInputSlots; ++i) {
Taehwan Kimda0517d2020-09-16 17:29:37 +0900634 if (mPipelineWatcher.lock()->pipelineFull()) {
635 return;
636 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800637 sp<MediaCodecBuffer> inBuffer;
638 size_t index;
639 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700640 Mutexed<Input>::Locked input(mInput);
641 if (input->buffers->numClientBuffers() >= input->numSlots) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800642 return;
643 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700644 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800645 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800646 break;
647 }
648 }
649 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
650 mCallback->onInputBufferAvailable(index, inBuffer);
651 }
652}
653
654status_t CCodecBufferChannel::renderOutputBuffer(
655 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800656 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800657 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800658 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800659 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700660 Mutexed<Output>::Locked output(mOutput);
661 if (output->buffers) {
662 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800663 }
664 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800665 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
666 // set to true.
667 sendOutputBuffers();
668 // input buffer feeding may have been gated by pending output buffers
669 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800670 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800671 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700672 std::call_once(mRenderWarningFlag, [this] {
673 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
674 "timestamp or render=true with non-video buffers. Apps should "
675 "call releaseOutputBuffer() with render=false for those.",
676 mName);
677 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800678 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800679 return INVALID_OPERATION;
680 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800681
682#if 0
683 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
684 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
685 for (const std::shared_ptr<const C2Info> &info : infoParams) {
686 AString res;
687 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
688 if (ix) res.append(", ");
689 res.append(*((int32_t*)info.get() + (ix / 4)));
690 }
691 ALOGV(" [%s]", res.c_str());
692 }
693#endif
694 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
695 std::static_pointer_cast<const C2StreamRotationInfo::output>(
696 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
697 bool flip = rotation && (rotation->flip & 1);
698 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
699 uint32_t transform = 0;
700 switch (quarters) {
701 case 0: // no rotation
702 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
703 break;
704 case 1: // 90 degrees counter-clockwise
705 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
706 : HAL_TRANSFORM_ROT_270;
707 break;
708 case 2: // 180 degrees
709 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
710 break;
711 case 3: // 90 degrees clockwise
712 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
713 : HAL_TRANSFORM_ROT_90;
714 break;
715 }
716
717 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
718 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
719 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
720 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
721 if (surfaceScaling) {
722 videoScalingMode = surfaceScaling->value;
723 }
724
725 // Use dataspace from format as it has the default aspects already applied
726 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
727 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
728
729 // HDR static info
730 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
731 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
732 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
733
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800734 // HDR10 plus info
735 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
736 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
737 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +0800738 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
739 hdr10PlusInfo.reset();
740 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800741
Pawin Vongmasa36653902018-11-15 00:10:25 -0800742 {
743 Mutexed<OutputSurface>::Locked output(mOutputSurface);
744 if (output->surface == nullptr) {
745 ALOGI("[%s] cannot render buffer without surface", mName);
746 return OK;
747 }
748 }
749
750 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
751 if (blocks.size() != 1u) {
752 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
753 return UNKNOWN_ERROR;
754 }
755 const C2ConstGraphicBlock &block = blocks.front();
756
757 // TODO: revisit this after C2Fence implementation.
758 android::IGraphicBufferProducer::QueueBufferInput qbi(
759 timestampNs,
760 false, // droppable
761 dataSpace,
762 Rect(blocks.front().crop().left,
763 blocks.front().crop().top,
764 blocks.front().crop().right(),
765 blocks.front().crop().bottom()),
766 videoScalingMode,
767 transform,
768 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800769 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800770 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800771 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +0800772 // If mastering max and min luminance fields are 0, do not use them.
773 // It indicates the value may not be present in the stream.
774 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
775 hdrStaticInfo->mastering.minLuminance > 0.0f) {
776 struct android_smpte2086_metadata smpte2086_meta = {
777 .displayPrimaryRed = {
778 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
779 },
780 .displayPrimaryGreen = {
781 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
782 },
783 .displayPrimaryBlue = {
784 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
785 },
786 .whitePoint = {
787 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
788 },
789 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
790 .minLuminance = hdrStaticInfo->mastering.minLuminance,
791 };
Yichi Chen54be23c2020-06-15 14:30:53 +0800792 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +0800793 hdr.smpte2086 = smpte2086_meta;
794 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -0700795 // If the content light level fields are 0, do not use them, it
796 // indicates the value may not be present in the stream.
797 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
798 struct android_cta861_3_metadata cta861_meta = {
799 .maxContentLightLevel = hdrStaticInfo->maxCll,
800 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
801 };
802 hdr.validTypes |= HdrMetadata::CTA861_3;
803 hdr.cta8613 = cta861_meta;
804 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800805 }
806 if (hdr10PlusInfo) {
807 hdr.validTypes |= HdrMetadata::HDR10PLUS;
808 hdr.hdr10plus.assign(
809 hdr10PlusInfo->m.value,
810 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
811 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800812 qbi.setHdrMetadata(hdr);
813 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800814 // we don't have dirty regions
815 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800816 android::IGraphicBufferProducer::QueueBufferOutput qbo;
817 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
818 if (result != OK) {
819 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -0800820 if (result == NO_INIT) {
821 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
822 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800823 return result;
824 }
825 ALOGV("[%s] queue buffer successful", mName);
826
827 int64_t mediaTimeUs = 0;
828 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
829 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
830
831 return OK;
832}
833
834status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
835 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
836 bool released = false;
837 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700838 Mutexed<Input>::Locked input(mInput);
839 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800840 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800841 }
842 }
843 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700844 Mutexed<Output>::Locked output(mOutput);
845 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800846 released = true;
847 }
848 }
849 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800850 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800851 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800852 } else {
853 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
854 }
855 return OK;
856}
857
858void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
859 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700860 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800861
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700862 if (!input->buffers->isArrayMode()) {
863 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800864 }
865
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700866 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800867}
868
869void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
870 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700871 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800872
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700873 if (!output->buffers->isArrayMode()) {
874 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800875 }
876
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700877 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800878}
879
880status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800881 const sp<AMessage> &inputFormat,
882 const sp<AMessage> &outputFormat,
883 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800884 C2StreamBufferTypeSetting::input iStreamFormat(0u);
885 C2StreamBufferTypeSetting::output oStreamFormat(0u);
886 C2PortReorderBufferDepthTuning::output reorderDepth;
887 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800888 C2PortActualDelayTuning::input inputDelay(0);
889 C2PortActualDelayTuning::output outputDelay(0);
890 C2ActualPipelineDelayTuning pipelineDelay(0);
891
Pawin Vongmasa36653902018-11-15 00:10:25 -0800892 c2_status_t err = mComponent->query(
893 {
894 &iStreamFormat,
895 &oStreamFormat,
896 &reorderDepth,
897 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800898 &inputDelay,
899 &pipelineDelay,
900 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800901 },
902 {},
903 C2_DONT_BLOCK,
904 nullptr);
905 if (err == C2_BAD_INDEX) {
906 if (!iStreamFormat || !oStreamFormat) {
907 return UNKNOWN_ERROR;
908 }
909 } else if (err != C2_OK) {
910 return UNKNOWN_ERROR;
911 }
912
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800913 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
914 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
915 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
916
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700917 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
918 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800919
Pawin Vongmasa36653902018-11-15 00:10:25 -0800920 // TODO: get this from input format
921 bool secure = mComponent->getName().find(".secure") != std::string::npos;
922
923 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +0800924 int poolMask = GetCodec2PoolMask();
925 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800926
927 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800928 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kimffb889a2020-05-28 11:32:25 -0700929 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
930 API_REFLECTION |
931 API_VALUES |
932 API_CURRENT_VALUES |
933 API_DEPENDENCY |
934 API_SAME_INPUT_BUFFER);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800935 std::shared_ptr<C2BlockPool> pool;
936 {
937 Mutexed<BlockPools>::Locked pools(mBlockPools);
938
939 // set default allocator ID.
940 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +0800941 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800942
943 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
944 // from component, create the input block pool with given ID. Otherwise, use default IDs.
945 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -0700946 C2ApiFeaturesSetting featuresSetting{apiFeatures};
947 err = mComponent->query({ &featuresSetting },
Pawin Vongmasa36653902018-11-15 00:10:25 -0800948 { C2PortAllocatorsTuning::input::PARAM_TYPE },
949 C2_DONT_BLOCK,
950 &params);
951 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
952 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
953 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -0700954 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800955 C2PortAllocatorsTuning::input *inputAllocators =
956 C2PortAllocatorsTuning::input::From(params[0].get());
957 if (inputAllocators && inputAllocators->flexCount() > 0) {
958 std::shared_ptr<C2Allocator> allocator;
959 // verify allocator IDs and resolve default allocator
960 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
961 if (allocator) {
962 pools->inputAllocatorId = allocator->getId();
963 } else {
964 ALOGD("[%s] component requested invalid input allocator ID %u",
965 mName, inputAllocators->m.values[0]);
966 }
967 }
968 }
Wonsik Kimffb889a2020-05-28 11:32:25 -0700969 if (featuresSetting) {
970 apiFeatures = featuresSetting.value;
971 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800972
973 // TODO: use C2Component wrapper to associate this pool with ourselves
974 if ((poolMask >> pools->inputAllocatorId) & 1) {
975 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
976 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
977 mName, pools->inputAllocatorId,
978 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
979 asString(err), err);
980 } else {
981 err = C2_NOT_FOUND;
982 }
983 if (err != C2_OK) {
984 C2BlockPool::local_id_t inputPoolId =
985 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
986 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
987 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
988 mName, (unsigned long long)inputPoolId,
989 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
990 asString(err), err);
991 if (err != C2_OK) {
992 return NO_MEMORY;
993 }
994 }
995 pools->inputPool = pool;
996 }
997
Wonsik Kim51051262018-11-28 13:59:05 -0800998 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700999 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001000 input->inputDelay = inputDelayValue;
1001 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001002 input->numSlots = numInputSlots;
1003 input->extraBuffers.flush();
1004 input->numExtraSlots = 0u;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001005 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1006 // For encrypted content, framework decrypts source buffer (ashmem) into
1007 // C2Buffers. Thus non-conforming codecs can process these.
1008 if (!buffersBoundToCodec && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001009 input->buffers.reset(new SlotInputBuffers(mName));
1010 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001011 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001012 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001013 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001014 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001015 // This is to ensure buffers do not get released prematurely.
1016 // TODO: handle this without going into array mode
1017 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001018 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001019 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001020 }
1021 } else {
1022 if (hasCryptoOrDescrambler()) {
1023 int32_t capacity = kLinearBufferSize;
1024 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1025 if ((size_t)capacity > kMaxLinearBufferSize) {
1026 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1027 capacity = kMaxLinearBufferSize;
1028 }
1029 if (mDealer == nullptr) {
1030 mDealer = new MemoryDealer(
1031 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001032 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001033 "EncryptedLinearInputBuffers");
1034 mDecryptDestination = mDealer->allocate((size_t)capacity);
1035 }
1036 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001037 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1038 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001039 } else {
1040 mHeapSeqNum = -1;
1041 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001042 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001043 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001044 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001045 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001046 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001047 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001048 }
1049 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001050 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001051
1052 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001053 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001054 } else {
1055 // TODO: error
1056 }
Wonsik Kim51051262018-11-28 13:59:05 -08001057
1058 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001059 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001060 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001061 }
1062
1063 if (outputFormat != nullptr) {
1064 sp<IGraphicBufferProducer> outputSurface;
1065 uint32_t outputGeneration;
1066 {
1067 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001068 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001069 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001070 if (!secure) {
1071 output->maxDequeueBuffers += numInputSlots;
1072 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001073 outputSurface = output->surface ?
1074 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001075 if (outputSurface) {
1076 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1077 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001078 outputGeneration = output->generation;
1079 }
1080
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001081 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001082 C2BlockPool::local_id_t outputPoolId_;
1083
1084 {
1085 Mutexed<BlockPools>::Locked pools(mBlockPools);
1086
1087 // set default allocator ID.
1088 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001089 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001090
1091 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1092 // unsuccessful.
1093 std::vector<std::unique_ptr<C2Param>> params;
1094 err = mComponent->query({ },
1095 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1096 C2_DONT_BLOCK,
1097 &params);
1098 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1099 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1100 mName, params.size(), asString(err), err);
1101 } else if (err == C2_OK && params.size() == 1) {
1102 C2PortAllocatorsTuning::output *outputAllocators =
1103 C2PortAllocatorsTuning::output::From(params[0].get());
1104 if (outputAllocators && outputAllocators->flexCount() > 0) {
1105 std::shared_ptr<C2Allocator> allocator;
1106 // verify allocator IDs and resolve default allocator
1107 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1108 if (allocator) {
1109 pools->outputAllocatorId = allocator->getId();
1110 } else {
1111 ALOGD("[%s] component requested invalid output allocator ID %u",
1112 mName, outputAllocators->m.values[0]);
1113 }
1114 }
1115 }
1116
1117 // use bufferqueue if outputting to a surface.
1118 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1119 // if unsuccessful.
1120 if (outputSurface) {
1121 params.clear();
1122 err = mComponent->query({ },
1123 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1124 C2_DONT_BLOCK,
1125 &params);
1126 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1127 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1128 mName, params.size(), asString(err), err);
1129 } else if (err == C2_OK && params.size() == 1) {
1130 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1131 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1132 if (surfaceAllocator) {
1133 std::shared_ptr<C2Allocator> allocator;
1134 // verify allocator IDs and resolve default allocator
1135 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1136 if (allocator) {
1137 pools->outputAllocatorId = allocator->getId();
1138 } else {
1139 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1140 mName, surfaceAllocator->value);
1141 err = C2_BAD_VALUE;
1142 }
1143 }
1144 }
1145 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1146 && err != C2_OK
1147 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1148 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1149 }
1150 }
1151
1152 if ((poolMask >> pools->outputAllocatorId) & 1) {
1153 err = mComponent->createBlockPool(
1154 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1155 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1156 mName, pools->outputAllocatorId,
1157 (unsigned long long)pools->outputPoolId,
1158 asString(err));
1159 } else {
1160 err = C2_NOT_FOUND;
1161 }
1162 if (err != C2_OK) {
1163 // use basic pool instead
1164 pools->outputPoolId =
1165 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1166 }
1167
1168 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1169 // component.
1170 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1171 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1172
1173 std::vector<std::unique_ptr<C2SettingResult>> failures;
1174 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1175 ALOGD("[%s] Configured output block pool ids %llu => %s",
1176 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1177 outputPoolId_ = pools->outputPoolId;
1178 }
1179
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001180 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001181 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001182 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001183 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001184 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001185 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001186 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001187 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001188 }
1189 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001190 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001191 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001192 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001193
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001194 output->buffers->clearStash();
1195 if (reorderDepth) {
1196 output->buffers->setReorderDepth(reorderDepth.value);
1197 }
1198 if (reorderKey) {
1199 output->buffers->setReorderKey(reorderKey.value);
1200 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001201
1202 // Try to set output surface to created block pool if given.
1203 if (outputSurface) {
1204 mComponent->setOutputSurface(
1205 outputPoolId_,
1206 outputSurface,
1207 outputGeneration);
1208 }
1209
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001210 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001211 if (buffersBoundToCodec) {
1212 // WORKAROUND: if we're using early CSD workaround we convert to
1213 // array mode, to appease apps assuming the output
1214 // buffers to be of the same size.
1215 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1216 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001217
1218 int32_t channelCount;
1219 int32_t sampleRate;
1220 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1221 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1222 int32_t delay = 0;
1223 int32_t padding = 0;;
1224 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1225 delay = 0;
1226 }
1227 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1228 padding = 0;
1229 }
1230 if (delay || padding) {
1231 // We need write access to the buffers, and we're already in
1232 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001233 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001234 }
1235 }
1236 }
1237 }
1238
1239 // Set up pipeline control. This has to be done after mInputBuffers and
1240 // mOutputBuffers are initialized to make sure that lingering callbacks
1241 // about buffers from the previous generation do not interfere with the
1242 // newly initialized pipeline capacity.
1243
Wonsik Kimab34ed62019-01-31 15:28:46 -08001244 {
1245 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001246 watcher->inputDelay(inputDelayValue)
1247 .pipelineDelay(pipelineDelayValue)
1248 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001249 .smoothnessFactor(kSmoothnessFactor);
1250 watcher->flush();
1251 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001252
1253 mInputMetEos = false;
1254 mSync.start();
1255 return OK;
1256}
1257
1258status_t CCodecBufferChannel::requestInitialInputBuffers() {
1259 if (mInputSurface) {
1260 return OK;
1261 }
1262
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001263 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001264 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1265 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1266 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001267 return UNKNOWN_ERROR;
1268 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001269 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001270
1271 struct ClientInputBuffer {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001272 size_t index;
1273 sp<MediaCodecBuffer> buffer;
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001274 size_t capacity;
1275 };
1276 std::list<ClientInputBuffer> clientInputBuffers;
1277
1278 {
1279 Mutexed<Input>::Locked input(mInput);
1280 while (clientInputBuffers.size() < numInputSlots) {
1281 ClientInputBuffer clientInputBuffer;
1282 if (!input->buffers->requestNewBuffer(&clientInputBuffer.index,
1283 &clientInputBuffer.buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001284 break;
1285 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001286 clientInputBuffer.capacity = clientInputBuffer.buffer->capacity();
1287 clientInputBuffers.emplace_back(std::move(clientInputBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001288 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001289 }
1290 if (clientInputBuffers.empty()) {
1291 ALOGW("[%s] start: cannot allocate memory at all", mName);
1292 return NO_MEMORY;
1293 } else if (clientInputBuffers.size() < numInputSlots) {
1294 ALOGD("[%s] start: cannot allocate memory for all slots, "
1295 "only %zu buffers allocated",
1296 mName, clientInputBuffers.size());
1297 } else {
1298 ALOGV("[%s] %zu initial input buffers available",
1299 mName, clientInputBuffers.size());
1300 }
1301 // Sort input buffers by their capacities in increasing order.
1302 clientInputBuffers.sort(
1303 [](const ClientInputBuffer& a, const ClientInputBuffer& b) {
1304 return a.capacity < b.capacity;
1305 });
1306
1307 {
1308 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1309 if (!configs->empty()) {
1310 while (!configs->empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001311 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001312 configs->pop_front();
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001313 // Find the smallest input buffer that can fit the config.
1314 auto i = std::find_if(
1315 clientInputBuffers.begin(),
1316 clientInputBuffers.end(),
1317 [cfgSize = config->size()](const ClientInputBuffer& b) {
1318 return b.capacity >= cfgSize;
1319 });
1320 if (i == clientInputBuffers.end()) {
1321 ALOGW("[%s] no input buffer large enough for the config "
1322 "(%zu bytes)",
1323 mName, config->size());
1324 return NO_MEMORY;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001325 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001326 sp<MediaCodecBuffer> buffer = i->buffer;
1327 memcpy(buffer->base(), config->data(), config->size());
1328 buffer->setRange(0, config->size());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001329 buffer->meta()->clear();
1330 buffer->meta()->setInt64("timeUs", 0);
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001331 buffer->meta()->setInt32("csd", 1);
1332 if (queueInputBufferInternal(buffer) != OK) {
1333 ALOGW("[%s] Error while queueing a flushed config",
1334 mName);
1335 return UNKNOWN_ERROR;
1336 }
1337 clientInputBuffers.erase(i);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001338 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001339 } else if (oStreamFormat.value == C2BufferData::LINEAR &&
1340 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
1341 sp<MediaCodecBuffer> buffer = clientInputBuffers.front().buffer;
1342 // WORKAROUND: Some apps expect CSD available without queueing
1343 // any input. Queue an empty buffer to get the CSD.
1344 buffer->setRange(0, 0);
1345 buffer->meta()->clear();
1346 buffer->meta()->setInt64("timeUs", 0);
1347 if (queueInputBufferInternal(buffer) != OK) {
1348 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
1349 mName);
1350 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001351 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001352 clientInputBuffers.pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001353 }
1354 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001355
1356 for (const ClientInputBuffer& clientInputBuffer: clientInputBuffers) {
1357 mCallback->onInputBufferAvailable(
1358 clientInputBuffer.index,
1359 clientInputBuffer.buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001360 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07001361
Pawin Vongmasa36653902018-11-15 00:10:25 -08001362 return OK;
1363}
1364
1365void CCodecBufferChannel::stop() {
1366 mSync.stop();
1367 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1368 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001369 mInputSurface.reset();
1370 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001371 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001372}
1373
Wonsik Kim936a89c2020-05-08 16:07:50 -07001374void CCodecBufferChannel::reset() {
1375 stop();
1376 {
1377 Mutexed<Input>::Locked input(mInput);
1378 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001379 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001380 }
1381 {
1382 Mutexed<Output>::Locked output(mOutput);
1383 output->buffers.reset();
1384 }
1385}
1386
1387void CCodecBufferChannel::release() {
1388 mComponent.reset();
1389 mInputAllocator.reset();
1390 mOutputSurface.lock()->surface.clear();
1391 {
1392 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
1393 blockPools->inputPool.reset();
1394 blockPools->outputPoolIntf.reset();
1395 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07001396 setCrypto(nullptr);
1397 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001398}
1399
1400
Pawin Vongmasa36653902018-11-15 00:10:25 -08001401void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1402 ALOGV("[%s] flush", mName);
1403 {
1404 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1405 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1406 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1407 continue;
1408 }
1409 if (work->input.buffers.empty()
1410 || work->input.buffers.front()->data().linearBlocks().empty()) {
1411 ALOGD("[%s] no linear codec config data found", mName);
1412 continue;
1413 }
1414 C2ReadView view =
1415 work->input.buffers.front()->data().linearBlocks().front().map().get();
1416 if (view.error() != C2_OK) {
1417 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1418 continue;
1419 }
1420 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1421 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1422 }
1423 }
1424 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001425 Mutexed<Input>::Locked input(mInput);
1426 input->buffers->flush();
1427 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001428 }
1429 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001430 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001431 if (output->buffers) {
1432 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001433 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07001434 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001435 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001436 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001437}
1438
1439void CCodecBufferChannel::onWorkDone(
1440 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001441 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001442 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001443 feedInputBufferIfAvailable();
1444 }
1445}
1446
1447void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001448 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001449 if (mInputSurface) {
1450 return;
1451 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001452 std::shared_ptr<C2Buffer> buffer =
1453 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001454 bool newInputSlotAvailable;
1455 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001456 Mutexed<Input>::Locked input(mInput);
1457 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1458 if (!newInputSlotAvailable) {
1459 (void)input->extraBuffers.expireComponentBuffer(buffer);
1460 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001461 }
1462 if (newInputSlotAvailable) {
1463 feedInputBufferIfAvailable();
1464 }
1465}
1466
1467bool CCodecBufferChannel::handleWork(
1468 std::unique_ptr<C2Work> work,
1469 const sp<AMessage> &outputFormat,
1470 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07001471 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00001472 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001473 if (!output->buffers) {
1474 return false;
1475 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08001476 }
1477
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001478 // Whether the output buffer should be reported to the client or not.
1479 bool notifyClient = false;
1480
1481 if (work->result == C2_OK){
1482 notifyClient = true;
1483 } else if (work->result == C2_NOT_FOUND) {
1484 ALOGD("[%s] flushed work; ignored.", mName);
1485 } else {
1486 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1487 // the config update.
1488 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1489 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1490 return false;
1491 }
1492
1493 if ((work->input.ordinal.frameIndex -
1494 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001495 // Discard frames from previous generation.
1496 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001497 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001498 }
1499
Wonsik Kim524b0582019-03-12 11:28:57 -07001500 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001501 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001502 || !(work->worklets.front()->output.flags &
1503 C2FrameData::FLAG_INCOMPLETE))) {
1504 mPipelineWatcher.lock()->onWorkDone(
1505 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001506 }
1507
1508 // NOTE: MediaCodec usage supposedly have only one worklet
1509 if (work->worklets.size() != 1u) {
1510 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1511 mName, work->worklets.size());
1512 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1513 return false;
1514 }
1515
1516 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1517
1518 std::shared_ptr<C2Buffer> buffer;
1519 // NOTE: MediaCodec usage supposedly have only one output stream.
1520 if (worklet->output.buffers.size() > 1u) {
1521 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1522 mName, worklet->output.buffers.size());
1523 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1524 return false;
1525 } else if (worklet->output.buffers.size() == 1u) {
1526 buffer = worklet->output.buffers[0];
1527 if (!buffer) {
1528 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1529 }
1530 }
1531
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001532 std::optional<uint32_t> newInputDelay, newPipelineDelay;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001533 while (!worklet->output.configUpdate.empty()) {
1534 std::unique_ptr<C2Param> param;
1535 worklet->output.configUpdate.back().swap(param);
1536 worklet->output.configUpdate.pop_back();
1537 switch (param->coreIndex().coreIndex()) {
1538 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1539 C2PortReorderBufferDepthTuning::output reorderDepth;
1540 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001541 bool secure = mComponent->getName().find(".secure") !=
1542 std::string::npos;
1543 mOutput.lock()->buffers->setReorderDepth(
1544 reorderDepth.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001545 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1546 mName, reorderDepth.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001547 size_t numOutputSlots = mOutput.lock()->numSlots;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001548 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001549 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001550 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001551 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001552 if (!secure) {
1553 output->maxDequeueBuffers += numInputSlots;
1554 }
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001555 if (output->surface) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001556 output->surface->setMaxDequeuedBufferCount(
1557 output->maxDequeueBuffers);
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001558 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001559 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001560 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1561 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001562 }
1563 break;
1564 }
1565 case C2PortReorderKeySetting::CORE_INDEX: {
1566 C2PortReorderKeySetting::output reorderKey;
1567 if (reorderKey.updateFrom(*param)) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001568 mOutput.lock()->buffers->setReorderKey(reorderKey.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001569 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1570 mName, reorderKey.value);
1571 } else {
1572 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1573 }
1574 break;
1575 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001576 case C2PortActualDelayTuning::CORE_INDEX: {
1577 if (param->isGlobal()) {
1578 C2ActualPipelineDelayTuning pipelineDelay;
1579 if (pipelineDelay.updateFrom(*param)) {
1580 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1581 mName, pipelineDelay.value);
1582 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001583 (void)mPipelineWatcher.lock()->pipelineDelay(
1584 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001585 }
1586 }
1587 if (param->forInput()) {
1588 C2PortActualDelayTuning::input inputDelay;
1589 if (inputDelay.updateFrom(*param)) {
1590 ALOGV("[%s] onWorkDone: updating input delay %u",
1591 mName, inputDelay.value);
1592 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001593 (void)mPipelineWatcher.lock()->inputDelay(
1594 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001595 }
1596 }
1597 if (param->forOutput()) {
1598 C2PortActualDelayTuning::output outputDelay;
1599 if (outputDelay.updateFrom(*param)) {
1600 ALOGV("[%s] onWorkDone: updating output delay %u",
1601 mName, outputDelay.value);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001602 bool secure = mComponent->getName().find(".secure") !=
1603 std::string::npos;
1604 (void)mPipelineWatcher.lock()->outputDelay(
1605 outputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001606
1607 bool outputBuffersChanged = false;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001608 size_t numOutputSlots = 0;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001609 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001610 {
1611 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001612 if (!output->buffers) {
1613 return false;
1614 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001615 output->outputDelay = outputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001616 numOutputSlots = outputDelay.value +
1617 kSmoothnessFactor;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001618 if (output->numSlots < numOutputSlots) {
1619 output->numSlots = numOutputSlots;
1620 if (output->buffers->isArrayMode()) {
1621 OutputBuffersArray *array =
1622 (OutputBuffersArray *)output->buffers.get();
1623 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1624 mName, numOutputSlots);
1625 array->grow(numOutputSlots);
1626 outputBuffersChanged = true;
1627 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001628 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001629 numOutputSlots = output->numSlots;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001630 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001631
1632 if (outputBuffersChanged) {
1633 mCCodecCallback->onOutputBuffersChanged();
1634 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001635
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001636 uint32_t depth = mOutput.lock()->buffers->getReorderDepth();
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001637 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001638 output->maxDequeueBuffers = numOutputSlots + depth + kRenderingDepth;
1639 if (!secure) {
1640 output->maxDequeueBuffers += numInputSlots;
1641 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001642 if (output->surface) {
1643 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1644 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001645 }
1646 }
1647 break;
1648 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001649 default:
1650 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1651 mName, param->index());
1652 break;
1653 }
1654 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001655 if (newInputDelay || newPipelineDelay) {
1656 Mutexed<Input>::Locked input(mInput);
1657 size_t newNumSlots =
1658 newInputDelay.value_or(input->inputDelay) +
1659 newPipelineDelay.value_or(input->pipelineDelay) +
1660 kSmoothnessFactor;
1661 if (input->buffers->isArrayMode()) {
1662 if (input->numSlots >= newNumSlots) {
1663 input->numExtraSlots = 0;
1664 } else {
1665 input->numExtraSlots = newNumSlots - input->numSlots;
1666 }
1667 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1668 mName, input->numExtraSlots);
1669 } else {
1670 input->numSlots = newNumSlots;
1671 }
1672 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001673
Pawin Vongmasa36653902018-11-15 00:10:25 -08001674 int32_t flags = 0;
1675 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1676 flags |= MediaCodec::BUFFER_FLAG_EOS;
1677 ALOGV("[%s] onWorkDone: output EOS", mName);
1678 }
1679
Pawin Vongmasa36653902018-11-15 00:10:25 -08001680 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1681 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1682 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1683 // shall correspond to the client input timesamp (in customOrdinal). By using the
1684 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1685 // produces multiple output.
1686 c2_cntr64_t timestamp =
1687 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1688 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001689 if (mInputSurface != nullptr) {
1690 // When using input surface we need to restore the original input timestamp.
1691 timestamp = work->input.ordinal.customOrdinal;
1692 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001693 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1694 mName,
1695 work->input.ordinal.customOrdinal.peekll(),
1696 work->input.ordinal.timestamp.peekll(),
1697 worklet->output.ordinal.timestamp.peekll(),
1698 timestamp.peekll());
1699
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001700 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001701 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001702 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001703 if (output->buffers && outputFormat) {
1704 output->buffers->updateSkipCutBuffer(outputFormat);
1705 output->buffers->setFormat(outputFormat);
1706 }
1707 if (!notifyClient) {
1708 return false;
1709 }
1710 size_t index;
1711 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim936a89c2020-05-08 16:07:50 -07001712 if (output->buffers && output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001713 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1714 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1715 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1716
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001717 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001718 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001719 } else {
1720 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001721 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001722 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001723 return false;
1724 }
1725 }
1726
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001727 if (notifyClient && !buffer && !flags) {
Wonsik Kim35bf5732020-05-14 17:40:29 +00001728 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001729 mName, work->input.ordinal.frameIndex.peekull());
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001730 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001731 }
1732
1733 if (buffer) {
1734 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1735 // TODO: properly translate these to metadata
1736 switch (info->coreIndex().coreIndex()) {
1737 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001738 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001739 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1740 }
1741 break;
1742 default:
1743 break;
1744 }
1745 }
1746 }
1747
1748 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001749 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07001750 if (!output->buffers) {
1751 return false;
1752 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001753 output->buffers->pushToStash(
1754 buffer,
1755 notifyClient,
1756 timestamp.peek(),
1757 flags,
1758 outputFormat,
1759 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001760 }
1761 sendOutputBuffers();
1762 return true;
1763}
1764
1765void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001766 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00001767 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001768 sp<MediaCodecBuffer> outBuffer;
1769 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001770
1771 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001772 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07001773 if (!output->buffers) {
1774 return;
1775 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001776 action = output->buffers->popFromStashAndRegister(
1777 &c2Buffer, &index, &outBuffer);
1778 switch (action) {
1779 case OutputBuffers::SKIP:
1780 return;
1781 case OutputBuffers::DISCARD:
1782 break;
1783 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kima4e049d2020-04-28 19:42:23 +00001784 output.unlock();
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001785 mCallback->onOutputBufferAvailable(index, outBuffer);
1786 break;
1787 case OutputBuffers::REALLOCATE:
1788 if (!output->buffers->isArrayMode()) {
1789 output->buffers =
1790 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001791 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001792 static_cast<OutputBuffersArray*>(output->buffers.get())->
1793 realloc(c2Buffer);
1794 output.unlock();
1795 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07001796 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001797 case OutputBuffers::RETRY:
1798 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
1799 mName);
1800 return;
1801 default:
1802 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
1803 "corrupted BufferAction value (%d) "
1804 "returned from popFromStashAndRegister.",
1805 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001806 return;
1807 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001808 }
1809}
1810
1811status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1812 static std::atomic_uint32_t surfaceGeneration{0};
1813 uint32_t generation = (getpid() << 10) |
1814 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1815 & ((1 << 10) - 1));
1816
1817 sp<IGraphicBufferProducer> producer;
1818 if (newSurface) {
1819 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001820 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Lee08515812019-06-05 11:16:32 -07001821 newSurface->setMaxDequeuedBufferCount(mOutputSurface.lock()->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001822 producer = newSurface->getIGraphicBufferProducer();
1823 producer->setGenerationNumber(generation);
1824 } else {
1825 ALOGE("[%s] setting output surface to null", mName);
1826 return INVALID_OPERATION;
1827 }
1828
1829 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1830 C2BlockPool::local_id_t outputPoolId;
1831 {
1832 Mutexed<BlockPools>::Locked pools(mBlockPools);
1833 outputPoolId = pools->outputPoolId;
1834 outputPoolIntf = pools->outputPoolIntf;
1835 }
1836
1837 if (outputPoolIntf) {
1838 if (mComponent->setOutputSurface(
1839 outputPoolId,
1840 producer,
1841 generation) != C2_OK) {
1842 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1843 return INVALID_OPERATION;
1844 }
1845 }
1846
1847 {
1848 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1849 output->surface = newSurface;
1850 output->generation = generation;
1851 }
1852
1853 return OK;
1854}
1855
Wonsik Kimab34ed62019-01-31 15:28:46 -08001856PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001857 // When client pushed EOS, we want all the work to be done quickly.
1858 // Otherwise, component may have stalled work due to input starvation up to
1859 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001860 size_t n = 0;
1861 if (!mInputMetEos) {
1862 size_t outputDelay = mOutput.lock()->outputDelay;
1863 Mutexed<Input>::Locked input(mInput);
1864 n = input->inputDelay + input->pipelineDelay + outputDelay;
1865 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001866 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001867}
1868
Pawin Vongmasa36653902018-11-15 00:10:25 -08001869void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1870 mMetaMode = mode;
1871}
1872
Wonsik Kim596187e2019-10-25 12:44:10 -07001873void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001874 if (mCrypto != nullptr) {
1875 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
1876 mCrypto->unsetHeap(entry.second);
1877 }
1878 mHeapSeqNumMap.clear();
1879 if (mHeapSeqNum >= 0) {
1880 mCrypto->unsetHeap(mHeapSeqNum);
1881 mHeapSeqNum = -1;
1882 }
1883 }
Wonsik Kim596187e2019-10-25 12:44:10 -07001884 mCrypto = crypto;
1885}
1886
1887void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
1888 mDescrambler = descrambler;
1889}
1890
Pawin Vongmasa36653902018-11-15 00:10:25 -08001891status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1892 // C2_OK is always translated to OK.
1893 if (c2s == C2_OK) {
1894 return OK;
1895 }
1896
1897 // Operation-dependent translation
1898 // TODO: Add as necessary
1899 switch (c2op) {
1900 case C2_OPERATION_Component_start:
1901 switch (c2s) {
1902 case C2_NO_MEMORY:
1903 return NO_MEMORY;
1904 default:
1905 return UNKNOWN_ERROR;
1906 }
1907 default:
1908 break;
1909 }
1910
1911 // Backup operation-agnostic translation
1912 switch (c2s) {
1913 case C2_BAD_INDEX:
1914 return BAD_INDEX;
1915 case C2_BAD_VALUE:
1916 return BAD_VALUE;
1917 case C2_BLOCKING:
1918 return WOULD_BLOCK;
1919 case C2_DUPLICATE:
1920 return ALREADY_EXISTS;
1921 case C2_NO_INIT:
1922 return NO_INIT;
1923 case C2_NO_MEMORY:
1924 return NO_MEMORY;
1925 case C2_NOT_FOUND:
1926 return NAME_NOT_FOUND;
1927 case C2_TIMED_OUT:
1928 return TIMED_OUT;
1929 case C2_BAD_STATE:
1930 case C2_CANCELED:
1931 case C2_CANNOT_DO:
1932 case C2_CORRUPTED:
1933 case C2_OMITTED:
1934 case C2_REFUSED:
1935 return UNKNOWN_ERROR;
1936 default:
1937 return -static_cast<status_t>(c2s);
1938 }
1939}
1940
1941} // namespace android