blob: 5fe7a9c051fed64aa6f32193514822afc6ce1b39 [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright 2017, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodecBufferChannel"
19#include <utils/Log.h>
20
21#include <numeric>
22
23#include <C2AllocatorGralloc.h>
24#include <C2PlatformSupport.h>
25#include <C2BlockInternal.h>
26#include <C2Config.h>
27#include <C2Debug.h>
28
29#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070030#include <android/hardware/drm/1.0/types.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080031#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080032#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080033#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070034#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080035#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070036#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080037#include <media/openmax/OMX_Core.h>
38#include <media/stagefright/foundation/ABuffer.h>
39#include <media/stagefright/foundation/ALookup.h>
40#include <media/stagefright/foundation/AMessage.h>
41#include <media/stagefright/foundation/AUtils.h>
42#include <media/stagefright/foundation/hexdump.h>
43#include <media/stagefright/MediaCodec.h>
44#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070045#include <media/stagefright/SkipCutBuffer.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080046#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070047#include <mediadrm/ICrypto.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080048#include <system/window.h>
49
50#include "CCodecBufferChannel.h"
51#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080052
53namespace android {
54
55using android::base::StringPrintf;
56using hardware::hidl_handle;
57using hardware::hidl_string;
58using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070059using hardware::fromHeap;
60using hardware::HidlMemory;
61
Pawin Vongmasa36653902018-11-15 00:10:25 -080062using namespace hardware::cas::V1_0;
63using namespace hardware::cas::native::V1_0;
64
65using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070066using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080067
Pawin Vongmasa36653902018-11-15 00:10:25 -080068namespace {
69
Wonsik Kim469c8342019-04-11 16:46:09 -070070constexpr size_t kSmoothnessFactor = 4;
71constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080072
Sungtak Leeab6f2f32019-02-15 14:43:51 -080073// This is for keeping IGBP's buffer dropping logic in legacy mode other
74// than making it non-blocking. Do not change this value.
75const static size_t kDequeueTimeoutNs = 0;
76
Pawin Vongmasa36653902018-11-15 00:10:25 -080077} // namespace
78
79CCodecBufferChannel::QueueGuard::QueueGuard(
80 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
81 Mutex::Autolock l(mSync.mGuardLock);
82 // At this point it's guaranteed that mSync is not under state transition,
83 // as we are holding its mutex.
84
85 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
86 if (count->value == -1) {
87 mRunning = false;
88 } else {
89 ++count->value;
90 mRunning = true;
91 }
92}
93
94CCodecBufferChannel::QueueGuard::~QueueGuard() {
95 if (mRunning) {
96 // We are not holding mGuardLock at this point so that QueueSync::stop() can
97 // keep holding the lock until mCount reaches zero.
98 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
99 --count->value;
100 count->cond.broadcast();
101 }
102}
103
104void CCodecBufferChannel::QueueSync::start() {
105 Mutex::Autolock l(mGuardLock);
106 // If stopped, it goes to running state; otherwise no-op.
107 Mutexed<Counter>::Locked count(mCount);
108 if (count->value == -1) {
109 count->value = 0;
110 }
111}
112
113void CCodecBufferChannel::QueueSync::stop() {
114 Mutex::Autolock l(mGuardLock);
115 Mutexed<Counter>::Locked count(mCount);
116 if (count->value == -1) {
117 // no-op
118 return;
119 }
120 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
121 // mCount can only decrement. In other words, threads that acquired the lock
122 // are allowed to finish execution but additional threads trying to acquire
123 // the lock at this point will block, and then get QueueGuard at STOPPED
124 // state.
125 while (count->value != 0) {
126 count.waitForCondition(count->cond);
127 }
128 count->value = -1;
129}
130
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700131// Input
132
133CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
134
Pawin Vongmasa36653902018-11-15 00:10:25 -0800135// CCodecBufferChannel
136
137CCodecBufferChannel::CCodecBufferChannel(
138 const std::shared_ptr<CCodecCallback> &callback)
139 : mHeapSeqNum(-1),
140 mCCodecCallback(callback),
141 mFrameIndex(0u),
142 mFirstValidFrameIndex(0u),
143 mMetaMode(MODE_NONE),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800144 mInputMetEos(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700145 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700146 {
147 Mutexed<Input>::Locked input(mInput);
148 input->buffers.reset(new DummyInputBuffers(""));
149 input->extraBuffers.flush();
150 input->inputDelay = 0u;
151 input->pipelineDelay = 0u;
152 input->numSlots = kSmoothnessFactor;
153 input->numExtraSlots = 0u;
154 }
155 {
156 Mutexed<Output>::Locked output(mOutput);
157 output->outputDelay = 0u;
158 output->numSlots = kSmoothnessFactor;
159 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800160}
161
162CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800163 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800164 mCrypto->unsetHeap(mHeapSeqNum);
165 }
166}
167
168void CCodecBufferChannel::setComponent(
169 const std::shared_ptr<Codec2Client::Component> &component) {
170 mComponent = component;
171 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
172 mName = mComponentName.c_str();
173}
174
175status_t CCodecBufferChannel::setInputSurface(
176 const std::shared_ptr<InputSurfaceWrapper> &surface) {
177 ALOGV("[%s] setInputSurface", mName);
178 mInputSurface = surface;
179 return mInputSurface->connect(mComponent);
180}
181
182status_t CCodecBufferChannel::signalEndOfInputStream() {
183 if (mInputSurface == nullptr) {
184 return INVALID_OPERATION;
185 }
186 return mInputSurface->signalEndOfInputStream();
187}
188
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700189status_t CCodecBufferChannel::queueInputBufferInternal(sp<MediaCodecBuffer> buffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800190 int64_t timeUs;
191 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
192
193 if (mInputMetEos) {
194 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
195 return OK;
196 }
197
198 int32_t flags = 0;
199 int32_t tmp = 0;
200 bool eos = false;
201 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
202 eos = true;
203 mInputMetEos = true;
204 ALOGV("[%s] input EOS", mName);
205 }
206 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
207 flags |= C2FrameData::FLAG_CODEC_CONFIG;
208 }
209 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
210 std::unique_ptr<C2Work> work(new C2Work);
211 work->input.ordinal.timestamp = timeUs;
212 work->input.ordinal.frameIndex = mFrameIndex++;
213 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
214 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
215 // Keep client timestamp in customOrdinal
216 work->input.ordinal.customOrdinal = timeUs;
217 work->input.buffers.clear();
218
Wonsik Kimab34ed62019-01-31 15:28:46 -0800219 uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
220 std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700221 sp<Codec2Buffer> copy;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800222
Pawin Vongmasa36653902018-11-15 00:10:25 -0800223 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700224 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800225 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700226 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800227 return -ENOENT;
228 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700229 // TODO: we want to delay copying buffers.
230 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
231 copy = input->buffers->cloneAndReleaseBuffer(buffer);
232 if (copy != nullptr) {
233 (void)input->extraBuffers.assignSlot(copy);
234 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
235 return UNKNOWN_ERROR;
236 }
237 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
238 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
239 mName, released ? "" : "not ");
240 buffer.clear();
241 } else {
242 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
243 "buffer starvation on component.", mName);
244 }
245 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800246 work->input.buffers.push_back(c2buffer);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800247 queuedBuffers.push_back(c2buffer);
248 } else if (eos) {
249 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800250 }
251 work->input.flags = (C2FrameData::flags_t)flags;
252 // TODO: fill info's
253
254 work->input.configUpdate = std::move(mParamsToBeSet);
255 work->worklets.clear();
256 work->worklets.emplace_back(new C2Worklet);
257
258 std::list<std::unique_ptr<C2Work>> items;
259 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800260 mPipelineWatcher.lock()->onWorkQueued(
261 queuedFrameIndex,
262 std::move(queuedBuffers),
263 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800264 c2_status_t err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800265 if (err != C2_OK) {
266 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
267 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800268
269 if (err == C2_OK && eos && buffer->size() > 0u) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800270 work.reset(new C2Work);
271 work->input.ordinal.timestamp = timeUs;
272 work->input.ordinal.frameIndex = mFrameIndex++;
273 // WORKAROUND: keep client timestamp in customOrdinal
274 work->input.ordinal.customOrdinal = timeUs;
275 work->input.buffers.clear();
276 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800277 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800278
Wonsik Kimab34ed62019-01-31 15:28:46 -0800279 queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
280 queuedBuffers.clear();
281
Pawin Vongmasa36653902018-11-15 00:10:25 -0800282 items.clear();
283 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800284
285 mPipelineWatcher.lock()->onWorkQueued(
286 queuedFrameIndex,
287 std::move(queuedBuffers),
288 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800289 err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800290 if (err != C2_OK) {
291 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
292 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800293 }
294 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700295 Mutexed<Input>::Locked input(mInput);
296 bool released = false;
297 if (buffer) {
298 released = input->buffers->releaseBuffer(buffer, nullptr, true);
299 } else if (copy) {
300 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
301 }
302 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
303 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800304 }
305
306 feedInputBufferIfAvailableInternal();
307 return err;
308}
309
310status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
311 QueueGuard guard(mSync);
312 if (!guard.isRunning()) {
313 ALOGD("[%s] setParameters is only supported in the running state.", mName);
314 return -ENOSYS;
315 }
316 mParamsToBeSet.insert(mParamsToBeSet.end(),
317 std::make_move_iterator(params.begin()),
318 std::make_move_iterator(params.end()));
319 params.clear();
320 return OK;
321}
322
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800323status_t CCodecBufferChannel::attachBuffer(
324 const std::shared_ptr<C2Buffer> &c2Buffer,
325 const sp<MediaCodecBuffer> &buffer) {
326 if (!buffer->copy(c2Buffer)) {
327 return -ENOSYS;
328 }
329 return OK;
330}
331
332void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
333 if (!mDecryptDestination || mDecryptDestination->size() < size) {
334 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
335 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
336 mCrypto->unsetHeap(mHeapSeqNum);
337 }
338 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
339 if (mCrypto) {
340 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
341 }
342 }
343}
344
345int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
346 CHECK(mCrypto);
347 auto it = mHeapSeqNumMap.find(memory);
348 int32_t heapSeqNum = -1;
349 if (it == mHeapSeqNumMap.end()) {
350 heapSeqNum = mCrypto->setHeap(memory);
351 mHeapSeqNumMap.emplace(memory, heapSeqNum);
352 } else {
353 heapSeqNum = it->second;
354 }
355 return heapSeqNum;
356}
357
358status_t CCodecBufferChannel::attachEncryptedBuffer(
359 const sp<hardware::HidlMemory> &memory,
360 bool secure,
361 const uint8_t *key,
362 const uint8_t *iv,
363 CryptoPlugin::Mode mode,
364 CryptoPlugin::Pattern pattern,
365 size_t offset,
366 const CryptoPlugin::SubSample *subSamples,
367 size_t numSubSamples,
368 const sp<MediaCodecBuffer> &buffer) {
369 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
370 static const C2MemoryUsage kDefaultReadWriteUsage{
371 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
372
373 size_t size = 0;
374 for (size_t i = 0; i < numSubSamples; ++i) {
375 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
376 }
377 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
378 std::shared_ptr<C2LinearBlock> block;
379 c2_status_t err = pool->fetchLinearBlock(
380 size,
381 secure ? kSecureUsage : kDefaultReadWriteUsage,
382 &block);
383 if (err != C2_OK) {
384 return NO_MEMORY;
385 }
386 if (!secure) {
387 ensureDecryptDestination(size);
388 }
389 ssize_t result = -1;
390 ssize_t codecDataOffset = 0;
391 if (mCrypto) {
392 AString errorDetailMsg;
393 int32_t heapSeqNum = getHeapSeqNum(memory);
394 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
395 hardware::drm::V1_0::DestinationBuffer dst;
396 if (secure) {
397 dst.type = DrmBufferType::NATIVE_HANDLE;
398 dst.secureMemory = hardware::hidl_handle(block->handle());
399 } else {
400 dst.type = DrmBufferType::SHARED_MEMORY;
401 IMemoryToSharedBuffer(
402 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
403 }
404 result = mCrypto->decrypt(
405 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
406 dst, &errorDetailMsg);
407 if (result < 0) {
408 return result;
409 }
410 if (dst.type == DrmBufferType::SHARED_MEMORY) {
411 C2WriteView view = block->map().get();
412 if (view.error() != C2_OK) {
413 return false;
414 }
415 if (view.size() < result) {
416 return false;
417 }
418 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
419 }
420 } else {
421 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
422 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
423 hidl_vec<SubSample> hidlSubSamples;
424 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
425
426 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
427 hardware::cas::native::V1_0::DestinationBuffer dst;
428 if (secure) {
429 dst.type = BufferType::NATIVE_HANDLE;
430 dst.secureMemory = hardware::hidl_handle(block->handle());
431 } else {
432 dst.type = BufferType::SHARED_MEMORY;
433 dst.nonsecureMemory = src;
434 }
435
436 CasStatus status = CasStatus::OK;
437 hidl_string detailedError;
438 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
439
440 if (key != nullptr) {
441 sctrl = (ScramblingControl)key[0];
442 // Adjust for the PES offset
443 codecDataOffset = key[2] | (key[3] << 8);
444 }
445
446 auto returnVoid = mDescrambler->descramble(
447 sctrl,
448 hidlSubSamples,
449 src,
450 0,
451 dst,
452 0,
453 [&status, &result, &detailedError] (
454 CasStatus _status, uint32_t _bytesWritten,
455 const hidl_string& _detailedError) {
456 status = _status;
457 result = (ssize_t)_bytesWritten;
458 detailedError = _detailedError;
459 });
460
461 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
462 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
463 mName, returnVoid.description().c_str(), status, result);
464 return UNKNOWN_ERROR;
465 }
466
467 if (result < codecDataOffset) {
468 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
469 return BAD_VALUE;
470 }
471 }
472 if (!secure) {
473 C2WriteView view = block->map().get();
474 if (view.error() != C2_OK) {
475 return UNKNOWN_ERROR;
476 }
477 if (view.size() < result) {
478 return UNKNOWN_ERROR;
479 }
480 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
481 }
482 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
483 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
484 if (!buffer->copy(c2Buffer)) {
485 return -ENOSYS;
486 }
487 return OK;
488}
489
Pawin Vongmasa36653902018-11-15 00:10:25 -0800490status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
491 QueueGuard guard(mSync);
492 if (!guard.isRunning()) {
493 ALOGD("[%s] No more buffers should be queued at current state.", mName);
494 return -ENOSYS;
495 }
496 return queueInputBufferInternal(buffer);
497}
498
499status_t CCodecBufferChannel::queueSecureInputBuffer(
500 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
501 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
502 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
503 AString *errorDetailMsg) {
504 QueueGuard guard(mSync);
505 if (!guard.isRunning()) {
506 ALOGD("[%s] No more buffers should be queued at current state.", mName);
507 return -ENOSYS;
508 }
509
510 if (!hasCryptoOrDescrambler()) {
511 return -ENOSYS;
512 }
513 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
514
515 ssize_t result = -1;
516 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700517 if (numSubSamples == 1
518 && subSamples[0].mNumBytesOfClearData == 0
519 && subSamples[0].mNumBytesOfEncryptedData == 0) {
520 // We don't need to go through crypto or descrambler if the input is empty.
521 result = 0;
522 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700523 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800524 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700525 destination.type = DrmBufferType::NATIVE_HANDLE;
526 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800527 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700528 destination.type = DrmBufferType::SHARED_MEMORY;
529 IMemoryToSharedBuffer(
530 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800531 }
Robert Shih895fba92019-07-16 16:29:44 -0700532 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800533 encryptedBuffer->fillSourceBuffer(&source);
534 result = mCrypto->decrypt(
535 key, iv, mode, pattern, source, buffer->offset(),
536 subSamples, numSubSamples, destination, errorDetailMsg);
537 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700538 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800539 return result;
540 }
Robert Shih895fba92019-07-16 16:29:44 -0700541 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800542 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
543 }
544 } else {
545 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
546 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
547 hidl_vec<SubSample> hidlSubSamples;
548 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
549
550 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
551 encryptedBuffer->fillSourceBuffer(&srcBuffer);
552
553 DestinationBuffer dstBuffer;
554 if (secure) {
555 dstBuffer.type = BufferType::NATIVE_HANDLE;
556 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
557 } else {
558 dstBuffer.type = BufferType::SHARED_MEMORY;
559 dstBuffer.nonsecureMemory = srcBuffer;
560 }
561
562 CasStatus status = CasStatus::OK;
563 hidl_string detailedError;
564 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
565
566 if (key != nullptr) {
567 sctrl = (ScramblingControl)key[0];
568 // Adjust for the PES offset
569 codecDataOffset = key[2] | (key[3] << 8);
570 }
571
572 auto returnVoid = mDescrambler->descramble(
573 sctrl,
574 hidlSubSamples,
575 srcBuffer,
576 0,
577 dstBuffer,
578 0,
579 [&status, &result, &detailedError] (
580 CasStatus _status, uint32_t _bytesWritten,
581 const hidl_string& _detailedError) {
582 status = _status;
583 result = (ssize_t)_bytesWritten;
584 detailedError = _detailedError;
585 });
586
587 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
588 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
589 mName, returnVoid.description().c_str(), status, result);
590 return UNKNOWN_ERROR;
591 }
592
593 if (result < codecDataOffset) {
594 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
595 return BAD_VALUE;
596 }
597
598 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
599
600 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
601 encryptedBuffer->copyDecryptedContentFromMemory(result);
602 }
603 }
604
605 buffer->setRange(codecDataOffset, result - codecDataOffset);
606 return queueInputBufferInternal(buffer);
607}
608
609void CCodecBufferChannel::feedInputBufferIfAvailable() {
610 QueueGuard guard(mSync);
611 if (!guard.isRunning()) {
612 ALOGV("[%s] We're not running --- no input buffer reported", mName);
613 return;
614 }
615 feedInputBufferIfAvailableInternal();
616}
617
618void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800619 if (mInputMetEos ||
Pawin Vongmasab18c1af2020-04-11 05:07:15 -0700620 mOutput.lock()->buffers->hasPending() ||
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800621 mPipelineWatcher.lock()->pipelineFull()) {
622 return;
623 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700624 Mutexed<Output>::Locked output(mOutput);
625 if (output->buffers->numClientBuffers() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800626 return;
627 }
628 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700629 size_t numInputSlots = mInput.lock()->numSlots;
630 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800631 sp<MediaCodecBuffer> inBuffer;
632 size_t index;
633 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700634 Mutexed<Input>::Locked input(mInput);
635 if (input->buffers->numClientBuffers() >= input->numSlots) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800636 return;
637 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700638 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800639 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800640 break;
641 }
642 }
643 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
644 mCallback->onInputBufferAvailable(index, inBuffer);
645 }
646}
647
648status_t CCodecBufferChannel::renderOutputBuffer(
649 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800650 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800651 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800652 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800653 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700654 Mutexed<Output>::Locked output(mOutput);
655 if (output->buffers) {
656 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800657 }
658 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800659 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
660 // set to true.
661 sendOutputBuffers();
662 // input buffer feeding may have been gated by pending output buffers
663 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800664 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800665 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700666 std::call_once(mRenderWarningFlag, [this] {
667 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
668 "timestamp or render=true with non-video buffers. Apps should "
669 "call releaseOutputBuffer() with render=false for those.",
670 mName);
671 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800672 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800673 return INVALID_OPERATION;
674 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800675
676#if 0
677 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
678 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
679 for (const std::shared_ptr<const C2Info> &info : infoParams) {
680 AString res;
681 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
682 if (ix) res.append(", ");
683 res.append(*((int32_t*)info.get() + (ix / 4)));
684 }
685 ALOGV(" [%s]", res.c_str());
686 }
687#endif
688 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
689 std::static_pointer_cast<const C2StreamRotationInfo::output>(
690 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
691 bool flip = rotation && (rotation->flip & 1);
692 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
693 uint32_t transform = 0;
694 switch (quarters) {
695 case 0: // no rotation
696 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
697 break;
698 case 1: // 90 degrees counter-clockwise
699 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
700 : HAL_TRANSFORM_ROT_270;
701 break;
702 case 2: // 180 degrees
703 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
704 break;
705 case 3: // 90 degrees clockwise
706 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
707 : HAL_TRANSFORM_ROT_90;
708 break;
709 }
710
711 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
712 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
713 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
714 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
715 if (surfaceScaling) {
716 videoScalingMode = surfaceScaling->value;
717 }
718
719 // Use dataspace from format as it has the default aspects already applied
720 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
721 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
722
723 // HDR static info
724 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
725 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
726 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
727
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800728 // HDR10 plus info
729 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
730 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
731 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
732
Pawin Vongmasa36653902018-11-15 00:10:25 -0800733 {
734 Mutexed<OutputSurface>::Locked output(mOutputSurface);
735 if (output->surface == nullptr) {
736 ALOGI("[%s] cannot render buffer without surface", mName);
737 return OK;
738 }
739 }
740
741 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
742 if (blocks.size() != 1u) {
743 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
744 return UNKNOWN_ERROR;
745 }
746 const C2ConstGraphicBlock &block = blocks.front();
747
748 // TODO: revisit this after C2Fence implementation.
749 android::IGraphicBufferProducer::QueueBufferInput qbi(
750 timestampNs,
751 false, // droppable
752 dataSpace,
753 Rect(blocks.front().crop().left,
754 blocks.front().crop().top,
755 blocks.front().crop().right(),
756 blocks.front().crop().bottom()),
757 videoScalingMode,
758 transform,
759 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800760 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800761 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800762 if (hdrStaticInfo) {
763 struct android_smpte2086_metadata smpte2086_meta = {
764 .displayPrimaryRed = {
765 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
766 },
767 .displayPrimaryGreen = {
768 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
769 },
770 .displayPrimaryBlue = {
771 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
772 },
773 .whitePoint = {
774 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
775 },
776 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
777 .minLuminance = hdrStaticInfo->mastering.minLuminance,
778 };
779
780 struct android_cta861_3_metadata cta861_meta = {
781 .maxContentLightLevel = hdrStaticInfo->maxCll,
782 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
783 };
784
785 hdr.validTypes = HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3;
786 hdr.smpte2086 = smpte2086_meta;
787 hdr.cta8613 = cta861_meta;
788 }
789 if (hdr10PlusInfo) {
790 hdr.validTypes |= HdrMetadata::HDR10PLUS;
791 hdr.hdr10plus.assign(
792 hdr10PlusInfo->m.value,
793 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
794 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800795 qbi.setHdrMetadata(hdr);
796 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800797 // we don't have dirty regions
798 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800799 android::IGraphicBufferProducer::QueueBufferOutput qbo;
800 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
801 if (result != OK) {
802 ALOGI("[%s] queueBuffer failed: %d", mName, result);
803 return result;
804 }
805 ALOGV("[%s] queue buffer successful", mName);
806
807 int64_t mediaTimeUs = 0;
808 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
809 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
810
811 return OK;
812}
813
814status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
815 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
816 bool released = false;
817 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700818 Mutexed<Input>::Locked input(mInput);
819 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800820 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800821 }
822 }
823 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700824 Mutexed<Output>::Locked output(mOutput);
825 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800826 released = true;
827 }
828 }
829 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800830 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800831 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800832 } else {
833 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
834 }
835 return OK;
836}
837
838void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
839 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700840 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800841
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700842 if (!input->buffers->isArrayMode()) {
843 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800844 }
845
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700846 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800847}
848
849void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
850 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700851 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800852
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700853 if (!output->buffers->isArrayMode()) {
854 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800855 }
856
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700857 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800858}
859
860status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800861 const sp<AMessage> &inputFormat,
862 const sp<AMessage> &outputFormat,
863 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800864 C2StreamBufferTypeSetting::input iStreamFormat(0u);
865 C2StreamBufferTypeSetting::output oStreamFormat(0u);
866 C2PortReorderBufferDepthTuning::output reorderDepth;
867 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800868 C2PortActualDelayTuning::input inputDelay(0);
869 C2PortActualDelayTuning::output outputDelay(0);
870 C2ActualPipelineDelayTuning pipelineDelay(0);
871
Pawin Vongmasa36653902018-11-15 00:10:25 -0800872 c2_status_t err = mComponent->query(
873 {
874 &iStreamFormat,
875 &oStreamFormat,
876 &reorderDepth,
877 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800878 &inputDelay,
879 &pipelineDelay,
880 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800881 },
882 {},
883 C2_DONT_BLOCK,
884 nullptr);
885 if (err == C2_BAD_INDEX) {
886 if (!iStreamFormat || !oStreamFormat) {
887 return UNKNOWN_ERROR;
888 }
889 } else if (err != C2_OK) {
890 return UNKNOWN_ERROR;
891 }
892
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800893 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
894 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
895 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
896
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700897 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
898 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800899
Pawin Vongmasa36653902018-11-15 00:10:25 -0800900 // TODO: get this from input format
901 bool secure = mComponent->getName().find(".secure") != std::string::npos;
902
903 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +0800904 int poolMask = GetCodec2PoolMask();
905 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800906
907 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800908 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800909 std::shared_ptr<C2BlockPool> pool;
910 {
911 Mutexed<BlockPools>::Locked pools(mBlockPools);
912
913 // set default allocator ID.
914 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +0800915 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800916
917 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
918 // from component, create the input block pool with given ID. Otherwise, use default IDs.
919 std::vector<std::unique_ptr<C2Param>> params;
920 err = mComponent->query({ },
921 { C2PortAllocatorsTuning::input::PARAM_TYPE },
922 C2_DONT_BLOCK,
923 &params);
924 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
925 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
926 mName, params.size(), asString(err), err);
927 } else if (err == C2_OK && params.size() == 1) {
928 C2PortAllocatorsTuning::input *inputAllocators =
929 C2PortAllocatorsTuning::input::From(params[0].get());
930 if (inputAllocators && inputAllocators->flexCount() > 0) {
931 std::shared_ptr<C2Allocator> allocator;
932 // verify allocator IDs and resolve default allocator
933 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
934 if (allocator) {
935 pools->inputAllocatorId = allocator->getId();
936 } else {
937 ALOGD("[%s] component requested invalid input allocator ID %u",
938 mName, inputAllocators->m.values[0]);
939 }
940 }
941 }
942
943 // TODO: use C2Component wrapper to associate this pool with ourselves
944 if ((poolMask >> pools->inputAllocatorId) & 1) {
945 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
946 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
947 mName, pools->inputAllocatorId,
948 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
949 asString(err), err);
950 } else {
951 err = C2_NOT_FOUND;
952 }
953 if (err != C2_OK) {
954 C2BlockPool::local_id_t inputPoolId =
955 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
956 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
957 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
958 mName, (unsigned long long)inputPoolId,
959 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
960 asString(err), err);
961 if (err != C2_OK) {
962 return NO_MEMORY;
963 }
964 }
965 pools->inputPool = pool;
966 }
967
Wonsik Kim51051262018-11-28 13:59:05 -0800968 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700969 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -0700970 input->inputDelay = inputDelayValue;
971 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700972 input->numSlots = numInputSlots;
973 input->extraBuffers.flush();
974 input->numExtraSlots = 0u;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800975 if (!buffersBoundToCodec) {
976 input->buffers.reset(new SlotInputBuffers(mName));
977 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800978 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700979 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800980 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700981 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -0700982 // This is to ensure buffers do not get released prematurely.
983 // TODO: handle this without going into array mode
984 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800985 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -0700986 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800987 }
988 } else {
989 if (hasCryptoOrDescrambler()) {
990 int32_t capacity = kLinearBufferSize;
991 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
992 if ((size_t)capacity > kMaxLinearBufferSize) {
993 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
994 capacity = kMaxLinearBufferSize;
995 }
996 if (mDealer == nullptr) {
997 mDealer = new MemoryDealer(
998 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700999 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001000 "EncryptedLinearInputBuffers");
1001 mDecryptDestination = mDealer->allocate((size_t)capacity);
1002 }
1003 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001004 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1005 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001006 } else {
1007 mHeapSeqNum = -1;
1008 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001009 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001010 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001011 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001012 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001013 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001014 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001015 }
1016 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001017 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001018
1019 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001020 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001021 } else {
1022 // TODO: error
1023 }
Wonsik Kim51051262018-11-28 13:59:05 -08001024
1025 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001026 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001027 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001028 }
1029
1030 if (outputFormat != nullptr) {
1031 sp<IGraphicBufferProducer> outputSurface;
1032 uint32_t outputGeneration;
1033 {
1034 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001035 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001036 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001037 if (!secure) {
1038 output->maxDequeueBuffers += numInputSlots;
1039 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001040 outputSurface = output->surface ?
1041 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001042 if (outputSurface) {
1043 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1044 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001045 outputGeneration = output->generation;
1046 }
1047
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001048 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001049 C2BlockPool::local_id_t outputPoolId_;
1050
1051 {
1052 Mutexed<BlockPools>::Locked pools(mBlockPools);
1053
1054 // set default allocator ID.
1055 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001056 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001057
1058 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1059 // unsuccessful.
1060 std::vector<std::unique_ptr<C2Param>> params;
1061 err = mComponent->query({ },
1062 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1063 C2_DONT_BLOCK,
1064 &params);
1065 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1066 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1067 mName, params.size(), asString(err), err);
1068 } else if (err == C2_OK && params.size() == 1) {
1069 C2PortAllocatorsTuning::output *outputAllocators =
1070 C2PortAllocatorsTuning::output::From(params[0].get());
1071 if (outputAllocators && outputAllocators->flexCount() > 0) {
1072 std::shared_ptr<C2Allocator> allocator;
1073 // verify allocator IDs and resolve default allocator
1074 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1075 if (allocator) {
1076 pools->outputAllocatorId = allocator->getId();
1077 } else {
1078 ALOGD("[%s] component requested invalid output allocator ID %u",
1079 mName, outputAllocators->m.values[0]);
1080 }
1081 }
1082 }
1083
1084 // use bufferqueue if outputting to a surface.
1085 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1086 // if unsuccessful.
1087 if (outputSurface) {
1088 params.clear();
1089 err = mComponent->query({ },
1090 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1091 C2_DONT_BLOCK,
1092 &params);
1093 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1094 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1095 mName, params.size(), asString(err), err);
1096 } else if (err == C2_OK && params.size() == 1) {
1097 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1098 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1099 if (surfaceAllocator) {
1100 std::shared_ptr<C2Allocator> allocator;
1101 // verify allocator IDs and resolve default allocator
1102 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1103 if (allocator) {
1104 pools->outputAllocatorId = allocator->getId();
1105 } else {
1106 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1107 mName, surfaceAllocator->value);
1108 err = C2_BAD_VALUE;
1109 }
1110 }
1111 }
1112 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1113 && err != C2_OK
1114 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1115 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1116 }
1117 }
1118
1119 if ((poolMask >> pools->outputAllocatorId) & 1) {
1120 err = mComponent->createBlockPool(
1121 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1122 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1123 mName, pools->outputAllocatorId,
1124 (unsigned long long)pools->outputPoolId,
1125 asString(err));
1126 } else {
1127 err = C2_NOT_FOUND;
1128 }
1129 if (err != C2_OK) {
1130 // use basic pool instead
1131 pools->outputPoolId =
1132 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1133 }
1134
1135 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1136 // component.
1137 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1138 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1139
1140 std::vector<std::unique_ptr<C2SettingResult>> failures;
1141 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1142 ALOGD("[%s] Configured output block pool ids %llu => %s",
1143 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1144 outputPoolId_ = pools->outputPoolId;
1145 }
1146
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001147 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001148 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001149 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001150 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001151 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001152 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001153 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001154 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001155 }
1156 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001157 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001158 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001159 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001160
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001161 output->buffers->clearStash();
1162 if (reorderDepth) {
1163 output->buffers->setReorderDepth(reorderDepth.value);
1164 }
1165 if (reorderKey) {
1166 output->buffers->setReorderKey(reorderKey.value);
1167 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001168
1169 // Try to set output surface to created block pool if given.
1170 if (outputSurface) {
1171 mComponent->setOutputSurface(
1172 outputPoolId_,
1173 outputSurface,
1174 outputGeneration);
1175 }
1176
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001177 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001178 if (buffersBoundToCodec) {
1179 // WORKAROUND: if we're using early CSD workaround we convert to
1180 // array mode, to appease apps assuming the output
1181 // buffers to be of the same size.
1182 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1183 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001184
1185 int32_t channelCount;
1186 int32_t sampleRate;
1187 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1188 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1189 int32_t delay = 0;
1190 int32_t padding = 0;;
1191 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1192 delay = 0;
1193 }
1194 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1195 padding = 0;
1196 }
1197 if (delay || padding) {
1198 // We need write access to the buffers, and we're already in
1199 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001200 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001201 }
1202 }
1203 }
1204 }
1205
1206 // Set up pipeline control. This has to be done after mInputBuffers and
1207 // mOutputBuffers are initialized to make sure that lingering callbacks
1208 // about buffers from the previous generation do not interfere with the
1209 // newly initialized pipeline capacity.
1210
Wonsik Kimab34ed62019-01-31 15:28:46 -08001211 {
1212 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001213 watcher->inputDelay(inputDelayValue)
1214 .pipelineDelay(pipelineDelayValue)
1215 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001216 .smoothnessFactor(kSmoothnessFactor);
1217 watcher->flush();
1218 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001219
1220 mInputMetEos = false;
1221 mSync.start();
1222 return OK;
1223}
1224
1225status_t CCodecBufferChannel::requestInitialInputBuffers() {
1226 if (mInputSurface) {
1227 return OK;
1228 }
1229
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001230 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001231 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1232 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1233 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001234 return UNKNOWN_ERROR;
1235 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001236 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001237 std::vector<sp<MediaCodecBuffer>> toBeQueued;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001238 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001239 size_t index;
1240 sp<MediaCodecBuffer> buffer;
1241 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001242 Mutexed<Input>::Locked input(mInput);
1243 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001244 if (i == 0) {
1245 ALOGW("[%s] start: cannot allocate memory at all", mName);
1246 return NO_MEMORY;
1247 } else {
1248 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
1249 mName, i);
1250 }
1251 break;
1252 }
1253 }
1254 if (buffer) {
1255 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1256 ALOGV("[%s] input buffer %zu available", mName, index);
1257 bool post = true;
1258 if (!configs->empty()) {
1259 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001260 configs->pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001261 if (buffer->capacity() >= config->size()) {
1262 memcpy(buffer->base(), config->data(), config->size());
1263 buffer->setRange(0, config->size());
1264 buffer->meta()->clear();
1265 buffer->meta()->setInt64("timeUs", 0);
1266 buffer->meta()->setInt32("csd", 1);
1267 post = false;
1268 } else {
1269 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
1270 mName, buffer->capacity(), config->size());
1271 }
1272 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001273 && (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001274 // WORKAROUND: Some apps expect CSD available without queueing
1275 // any input. Queue an empty buffer to get the CSD.
1276 buffer->setRange(0, 0);
1277 buffer->meta()->clear();
1278 buffer->meta()->setInt64("timeUs", 0);
1279 post = false;
1280 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001281 if (post) {
1282 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001283 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001284 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001285 }
1286 }
1287 }
1288 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
1289 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001290 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001291 }
1292 }
1293 return OK;
1294}
1295
1296void CCodecBufferChannel::stop() {
1297 mSync.stop();
1298 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1299 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001300 mInputSurface.reset();
1301 }
1302}
1303
1304void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1305 ALOGV("[%s] flush", mName);
1306 {
1307 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1308 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1309 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1310 continue;
1311 }
1312 if (work->input.buffers.empty()
1313 || work->input.buffers.front()->data().linearBlocks().empty()) {
1314 ALOGD("[%s] no linear codec config data found", mName);
1315 continue;
1316 }
1317 C2ReadView view =
1318 work->input.buffers.front()->data().linearBlocks().front().map().get();
1319 if (view.error() != C2_OK) {
1320 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1321 continue;
1322 }
1323 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1324 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1325 }
1326 }
1327 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001328 Mutexed<Input>::Locked input(mInput);
1329 input->buffers->flush();
1330 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001331 }
1332 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001333 Mutexed<Output>::Locked output(mOutput);
1334 output->buffers->flush(flushedWork);
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001335 output->buffers->flushStash();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001336 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001337 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001338}
1339
1340void CCodecBufferChannel::onWorkDone(
1341 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001342 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001343 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001344 feedInputBufferIfAvailable();
1345 }
1346}
1347
1348void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001349 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001350 if (mInputSurface) {
1351 return;
1352 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001353 std::shared_ptr<C2Buffer> buffer =
1354 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001355 bool newInputSlotAvailable;
1356 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001357 Mutexed<Input>::Locked input(mInput);
1358 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1359 if (!newInputSlotAvailable) {
1360 (void)input->extraBuffers.expireComponentBuffer(buffer);
1361 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001362 }
1363 if (newInputSlotAvailable) {
1364 feedInputBufferIfAvailable();
1365 }
1366}
1367
1368bool CCodecBufferChannel::handleWork(
1369 std::unique_ptr<C2Work> work,
1370 const sp<AMessage> &outputFormat,
1371 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001372 // Whether the output buffer should be reported to the client or not.
1373 bool notifyClient = false;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001374
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001375 if (work->result == C2_OK){
1376 notifyClient = true;
1377 } else if (work->result == C2_NOT_FOUND) {
1378 ALOGD("[%s] flushed work; ignored.", mName);
1379 } else {
1380 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1381 // the config update.
1382 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1383 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1384 return false;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001385 }
1386
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001387 if ((work->input.ordinal.frameIndex -
1388 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001389 // Discard frames from previous generation.
1390 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001391 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001392 }
1393
Wonsik Kim524b0582019-03-12 11:28:57 -07001394 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001395 || !work->worklets.front()
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001396 || !(work->worklets.front()->output.flags &
1397 C2FrameData::FLAG_INCOMPLETE))) {
1398 mPipelineWatcher.lock()->onWorkDone(
1399 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001400 }
1401
1402 // NOTE: MediaCodec usage supposedly have only one worklet
1403 if (work->worklets.size() != 1u) {
1404 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1405 mName, work->worklets.size());
1406 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1407 return false;
1408 }
1409
1410 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1411
1412 std::shared_ptr<C2Buffer> buffer;
1413 // NOTE: MediaCodec usage supposedly have only one output stream.
1414 if (worklet->output.buffers.size() > 1u) {
1415 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1416 mName, worklet->output.buffers.size());
1417 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1418 return false;
1419 } else if (worklet->output.buffers.size() == 1u) {
1420 buffer = worklet->output.buffers[0];
1421 if (!buffer) {
1422 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1423 }
1424 }
1425
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001426 std::optional<uint32_t> newInputDelay, newPipelineDelay;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001427 while (!worklet->output.configUpdate.empty()) {
1428 std::unique_ptr<C2Param> param;
1429 worklet->output.configUpdate.back().swap(param);
1430 worklet->output.configUpdate.pop_back();
1431 switch (param->coreIndex().coreIndex()) {
1432 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1433 C2PortReorderBufferDepthTuning::output reorderDepth;
1434 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001435 bool secure = mComponent->getName().find(".secure") !=
1436 std::string::npos;
1437 mOutput.lock()->buffers->setReorderDepth(
1438 reorderDepth.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001439 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1440 mName, reorderDepth.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001441 size_t numOutputSlots = mOutput.lock()->numSlots;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001442 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001443 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001444 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001445 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001446 if (!secure) {
1447 output->maxDequeueBuffers += numInputSlots;
1448 }
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001449 if (output->surface) {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001450 output->surface->setMaxDequeuedBufferCount(
1451 output->maxDequeueBuffers);
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001452 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001453 } else {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001454 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1455 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001456 }
1457 break;
1458 }
1459 case C2PortReorderKeySetting::CORE_INDEX: {
1460 C2PortReorderKeySetting::output reorderKey;
1461 if (reorderKey.updateFrom(*param)) {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001462 mOutput.lock()->buffers->setReorderKey(reorderKey.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001463 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1464 mName, reorderKey.value);
1465 } else {
1466 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1467 }
1468 break;
1469 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001470 case C2PortActualDelayTuning::CORE_INDEX: {
1471 if (param->isGlobal()) {
1472 C2ActualPipelineDelayTuning pipelineDelay;
1473 if (pipelineDelay.updateFrom(*param)) {
1474 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1475 mName, pipelineDelay.value);
1476 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001477 (void)mPipelineWatcher.lock()->pipelineDelay(
1478 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001479 }
1480 }
1481 if (param->forInput()) {
1482 C2PortActualDelayTuning::input inputDelay;
1483 if (inputDelay.updateFrom(*param)) {
1484 ALOGV("[%s] onWorkDone: updating input delay %u",
1485 mName, inputDelay.value);
1486 newInputDelay = inputDelay.value;
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001487 (void)mPipelineWatcher.lock()->inputDelay(
1488 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001489 }
1490 }
1491 if (param->forOutput()) {
1492 C2PortActualDelayTuning::output outputDelay;
1493 if (outputDelay.updateFrom(*param)) {
1494 ALOGV("[%s] onWorkDone: updating output delay %u",
1495 mName, outputDelay.value);
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001496 bool secure = mComponent->getName().find(".secure") !=
1497 std::string::npos;
1498 (void)mPipelineWatcher.lock()->outputDelay(
1499 outputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001500
1501 bool outputBuffersChanged = false;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001502 size_t numOutputSlots = 0;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001503 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001504 {
1505 Mutexed<Output>::Locked output(mOutput);
1506 output->outputDelay = outputDelay.value;
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001507 numOutputSlots = outputDelay.value +
1508 kSmoothnessFactor;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001509 if (output->numSlots < numOutputSlots) {
1510 output->numSlots = numOutputSlots;
1511 if (output->buffers->isArrayMode()) {
1512 OutputBuffersArray *array =
1513 (OutputBuffersArray *)output->buffers.get();
1514 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1515 mName, numOutputSlots);
1516 array->grow(numOutputSlots);
1517 outputBuffersChanged = true;
1518 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001519 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001520 numOutputSlots = output->numSlots;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001521 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001522
1523 if (outputBuffersChanged) {
1524 mCCodecCallback->onOutputBuffersChanged();
1525 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001526
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001527 uint32_t depth = mOutput.lock()->buffers->getReorderDepth();
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001528 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001529 output->maxDequeueBuffers = numOutputSlots + depth + kRenderingDepth;
1530 if (!secure) {
1531 output->maxDequeueBuffers += numInputSlots;
1532 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001533 if (output->surface) {
1534 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1535 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001536 }
1537 }
1538 break;
1539 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001540 default:
1541 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1542 mName, param->index());
1543 break;
1544 }
1545 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001546 if (newInputDelay || newPipelineDelay) {
1547 Mutexed<Input>::Locked input(mInput);
1548 size_t newNumSlots =
1549 newInputDelay.value_or(input->inputDelay) +
1550 newPipelineDelay.value_or(input->pipelineDelay) +
1551 kSmoothnessFactor;
1552 if (input->buffers->isArrayMode()) {
1553 if (input->numSlots >= newNumSlots) {
1554 input->numExtraSlots = 0;
1555 } else {
1556 input->numExtraSlots = newNumSlots - input->numSlots;
1557 }
1558 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1559 mName, input->numExtraSlots);
1560 } else {
1561 input->numSlots = newNumSlots;
1562 }
1563 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001564
Pawin Vongmasa36653902018-11-15 00:10:25 -08001565 int32_t flags = 0;
1566 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1567 flags |= MediaCodec::BUFFER_FLAG_EOS;
1568 ALOGV("[%s] onWorkDone: output EOS", mName);
1569 }
1570
Pawin Vongmasa36653902018-11-15 00:10:25 -08001571 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1572 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1573 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1574 // shall correspond to the client input timesamp (in customOrdinal). By using the
1575 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1576 // produces multiple output.
1577 c2_cntr64_t timestamp =
1578 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1579 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001580 if (mInputSurface != nullptr) {
1581 // When using input surface we need to restore the original input timestamp.
1582 timestamp = work->input.ordinal.customOrdinal;
1583 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001584 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1585 mName,
1586 work->input.ordinal.customOrdinal.peekll(),
1587 work->input.ordinal.timestamp.peekll(),
1588 worklet->output.ordinal.timestamp.peekll(),
1589 timestamp.peekll());
1590
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001591 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001592 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001593 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001594 if (outputFormat) {
1595 output->buffers->updateSkipCutBuffer(outputFormat);
1596 output->buffers->setFormat(outputFormat);
1597 }
1598 if (!notifyClient) {
1599 return false;
1600 }
1601 size_t index;
1602 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001603 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001604 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1605 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1606 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1607
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001608 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001609 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001610 } else {
1611 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001612 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001613 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001614 return false;
1615 }
1616 }
1617
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001618 if (notifyClient && !buffer && !flags) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001619 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1620 mName, work->input.ordinal.frameIndex.peekull());
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001621 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001622 }
1623
1624 if (buffer) {
1625 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1626 // TODO: properly translate these to metadata
1627 switch (info->coreIndex().coreIndex()) {
1628 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001629 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001630 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1631 }
1632 break;
1633 default:
1634 break;
1635 }
1636 }
1637 }
1638
1639 {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001640 Mutexed<Output>::Locked output(mOutput);
1641 output->buffers->pushToStash(
1642 buffer,
1643 notifyClient,
1644 timestamp.peek(),
1645 flags,
1646 outputFormat,
1647 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001648 }
1649 sendOutputBuffers();
1650 return true;
1651}
1652
1653void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001654 OutputBuffers::BufferAction action;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001655 size_t index;
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001656 sp<MediaCodecBuffer> outBuffer;
1657 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001658
1659 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001660 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001661 action = output->buffers->popFromStashAndRegister(
1662 &c2Buffer, &index, &outBuffer);
1663 switch (action) {
1664 case OutputBuffers::SKIP:
1665 return;
1666 case OutputBuffers::DISCARD:
1667 break;
1668 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001669 output.unlock();
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001670 mCallback->onOutputBufferAvailable(index, outBuffer);
1671 break;
1672 case OutputBuffers::REALLOCATE: {
1673 if (!output->buffers->isArrayMode()) {
1674 output->buffers =
1675 output->buffers->toArrayMode(output->numSlots);
1676 }
1677 static_cast<OutputBuffersArray*>(output->buffers.get())->
1678 realloc(c2Buffer);
1679 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001680 mCCodecCallback->onOutputBuffersChanged();
1681 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001682 return;
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001683 case OutputBuffers::RETRY:
1684 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
1685 mName);
1686 return;
1687 default:
1688 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
1689 "corrupted BufferAction value (%d) "
1690 "returned from popFromStashAndRegister.",
1691 mName, int(action));
1692 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001693 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001694 }
1695}
1696
1697status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1698 static std::atomic_uint32_t surfaceGeneration{0};
1699 uint32_t generation = (getpid() << 10) |
1700 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1701 & ((1 << 10) - 1));
1702
1703 sp<IGraphicBufferProducer> producer;
1704 if (newSurface) {
1705 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001706 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Lee08515812019-06-05 11:16:32 -07001707 newSurface->setMaxDequeuedBufferCount(mOutputSurface.lock()->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001708 producer = newSurface->getIGraphicBufferProducer();
1709 producer->setGenerationNumber(generation);
1710 } else {
1711 ALOGE("[%s] setting output surface to null", mName);
1712 return INVALID_OPERATION;
1713 }
1714
1715 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1716 C2BlockPool::local_id_t outputPoolId;
1717 {
1718 Mutexed<BlockPools>::Locked pools(mBlockPools);
1719 outputPoolId = pools->outputPoolId;
1720 outputPoolIntf = pools->outputPoolIntf;
1721 }
1722
1723 if (outputPoolIntf) {
1724 if (mComponent->setOutputSurface(
1725 outputPoolId,
1726 producer,
1727 generation) != C2_OK) {
1728 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1729 return INVALID_OPERATION;
1730 }
1731 }
1732
1733 {
1734 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1735 output->surface = newSurface;
1736 output->generation = generation;
1737 }
1738
1739 return OK;
1740}
1741
Wonsik Kimab34ed62019-01-31 15:28:46 -08001742PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001743 // When client pushed EOS, we want all the work to be done quickly.
1744 // Otherwise, component may have stalled work due to input starvation up to
1745 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001746 size_t n = 0;
1747 if (!mInputMetEos) {
1748 size_t outputDelay = mOutput.lock()->outputDelay;
1749 Mutexed<Input>::Locked input(mInput);
1750 n = input->inputDelay + input->pipelineDelay + outputDelay;
1751 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001752 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001753}
1754
Pawin Vongmasa36653902018-11-15 00:10:25 -08001755void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1756 mMetaMode = mode;
1757}
1758
Wonsik Kim596187e2019-10-25 12:44:10 -07001759void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001760 if (mCrypto != nullptr) {
1761 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
1762 mCrypto->unsetHeap(entry.second);
1763 }
1764 mHeapSeqNumMap.clear();
1765 if (mHeapSeqNum >= 0) {
1766 mCrypto->unsetHeap(mHeapSeqNum);
1767 mHeapSeqNum = -1;
1768 }
1769 }
Wonsik Kim596187e2019-10-25 12:44:10 -07001770 mCrypto = crypto;
1771}
1772
1773void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
1774 mDescrambler = descrambler;
1775}
1776
Pawin Vongmasa36653902018-11-15 00:10:25 -08001777status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1778 // C2_OK is always translated to OK.
1779 if (c2s == C2_OK) {
1780 return OK;
1781 }
1782
1783 // Operation-dependent translation
1784 // TODO: Add as necessary
1785 switch (c2op) {
1786 case C2_OPERATION_Component_start:
1787 switch (c2s) {
1788 case C2_NO_MEMORY:
1789 return NO_MEMORY;
1790 default:
1791 return UNKNOWN_ERROR;
1792 }
1793 default:
1794 break;
1795 }
1796
1797 // Backup operation-agnostic translation
1798 switch (c2s) {
1799 case C2_BAD_INDEX:
1800 return BAD_INDEX;
1801 case C2_BAD_VALUE:
1802 return BAD_VALUE;
1803 case C2_BLOCKING:
1804 return WOULD_BLOCK;
1805 case C2_DUPLICATE:
1806 return ALREADY_EXISTS;
1807 case C2_NO_INIT:
1808 return NO_INIT;
1809 case C2_NO_MEMORY:
1810 return NO_MEMORY;
1811 case C2_NOT_FOUND:
1812 return NAME_NOT_FOUND;
1813 case C2_TIMED_OUT:
1814 return TIMED_OUT;
1815 case C2_BAD_STATE:
1816 case C2_CANCELED:
1817 case C2_CANNOT_DO:
1818 case C2_CORRUPTED:
1819 case C2_OMITTED:
1820 case C2_REFUSED:
1821 return UNKNOWN_ERROR;
1822 default:
1823 return -static_cast<status_t>(c2s);
1824 }
1825}
1826
1827} // namespace android