blob: e2be9911a2cad0ede69695932955e9d5e8a06b4c [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright 2017, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodecBufferChannel"
19#include <utils/Log.h>
20
21#include <numeric>
22
23#include <C2AllocatorGralloc.h>
24#include <C2PlatformSupport.h>
25#include <C2BlockInternal.h>
26#include <C2Config.h>
27#include <C2Debug.h>
28
29#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070030#include <android/hardware/drm/1.0/types.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080031#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080032#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080033#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070034#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080035#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070036#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080037#include <media/openmax/OMX_Core.h>
38#include <media/stagefright/foundation/ABuffer.h>
39#include <media/stagefright/foundation/ALookup.h>
40#include <media/stagefright/foundation/AMessage.h>
41#include <media/stagefright/foundation/AUtils.h>
42#include <media/stagefright/foundation/hexdump.h>
43#include <media/stagefright/MediaCodec.h>
44#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070045#include <media/stagefright/SkipCutBuffer.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080046#include <media/MediaCodecBuffer.h>
47#include <system/window.h>
48
49#include "CCodecBufferChannel.h"
50#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080051
52namespace android {
53
54using android::base::StringPrintf;
55using hardware::hidl_handle;
56using hardware::hidl_string;
57using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070058using hardware::fromHeap;
59using hardware::HidlMemory;
60
Pawin Vongmasa36653902018-11-15 00:10:25 -080061using namespace hardware::cas::V1_0;
62using namespace hardware::cas::native::V1_0;
63
64using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070065using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080066
Pawin Vongmasa36653902018-11-15 00:10:25 -080067namespace {
68
Wonsik Kim469c8342019-04-11 16:46:09 -070069constexpr size_t kSmoothnessFactor = 4;
70constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080071
Sungtak Leeab6f2f32019-02-15 14:43:51 -080072// This is for keeping IGBP's buffer dropping logic in legacy mode other
73// than making it non-blocking. Do not change this value.
74const static size_t kDequeueTimeoutNs = 0;
75
Pawin Vongmasa36653902018-11-15 00:10:25 -080076} // namespace
77
78CCodecBufferChannel::QueueGuard::QueueGuard(
79 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
80 Mutex::Autolock l(mSync.mGuardLock);
81 // At this point it's guaranteed that mSync is not under state transition,
82 // as we are holding its mutex.
83
84 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
85 if (count->value == -1) {
86 mRunning = false;
87 } else {
88 ++count->value;
89 mRunning = true;
90 }
91}
92
93CCodecBufferChannel::QueueGuard::~QueueGuard() {
94 if (mRunning) {
95 // We are not holding mGuardLock at this point so that QueueSync::stop() can
96 // keep holding the lock until mCount reaches zero.
97 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
98 --count->value;
99 count->cond.broadcast();
100 }
101}
102
103void CCodecBufferChannel::QueueSync::start() {
104 Mutex::Autolock l(mGuardLock);
105 // If stopped, it goes to running state; otherwise no-op.
106 Mutexed<Counter>::Locked count(mCount);
107 if (count->value == -1) {
108 count->value = 0;
109 }
110}
111
112void CCodecBufferChannel::QueueSync::stop() {
113 Mutex::Autolock l(mGuardLock);
114 Mutexed<Counter>::Locked count(mCount);
115 if (count->value == -1) {
116 // no-op
117 return;
118 }
119 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
120 // mCount can only decrement. In other words, threads that acquired the lock
121 // are allowed to finish execution but additional threads trying to acquire
122 // the lock at this point will block, and then get QueueGuard at STOPPED
123 // state.
124 while (count->value != 0) {
125 count.waitForCondition(count->cond);
126 }
127 count->value = -1;
128}
129
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700130// Input
131
132CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
133
Pawin Vongmasa36653902018-11-15 00:10:25 -0800134// CCodecBufferChannel
135
136CCodecBufferChannel::CCodecBufferChannel(
137 const std::shared_ptr<CCodecCallback> &callback)
138 : mHeapSeqNum(-1),
139 mCCodecCallback(callback),
140 mFrameIndex(0u),
141 mFirstValidFrameIndex(0u),
142 mMetaMode(MODE_NONE),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800143 mInputMetEos(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700144 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700145 {
146 Mutexed<Input>::Locked input(mInput);
147 input->buffers.reset(new DummyInputBuffers(""));
148 input->extraBuffers.flush();
149 input->inputDelay = 0u;
150 input->pipelineDelay = 0u;
151 input->numSlots = kSmoothnessFactor;
152 input->numExtraSlots = 0u;
153 }
154 {
155 Mutexed<Output>::Locked output(mOutput);
156 output->outputDelay = 0u;
157 output->numSlots = kSmoothnessFactor;
158 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800159}
160
161CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800162 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800163 mCrypto->unsetHeap(mHeapSeqNum);
164 }
165}
166
167void CCodecBufferChannel::setComponent(
168 const std::shared_ptr<Codec2Client::Component> &component) {
169 mComponent = component;
170 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
171 mName = mComponentName.c_str();
172}
173
174status_t CCodecBufferChannel::setInputSurface(
175 const std::shared_ptr<InputSurfaceWrapper> &surface) {
176 ALOGV("[%s] setInputSurface", mName);
177 mInputSurface = surface;
178 return mInputSurface->connect(mComponent);
179}
180
181status_t CCodecBufferChannel::signalEndOfInputStream() {
182 if (mInputSurface == nullptr) {
183 return INVALID_OPERATION;
184 }
185 return mInputSurface->signalEndOfInputStream();
186}
187
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700188status_t CCodecBufferChannel::queueInputBufferInternal(sp<MediaCodecBuffer> buffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800189 int64_t timeUs;
190 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
191
192 if (mInputMetEos) {
193 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
194 return OK;
195 }
196
197 int32_t flags = 0;
198 int32_t tmp = 0;
199 bool eos = false;
200 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
201 eos = true;
202 mInputMetEos = true;
203 ALOGV("[%s] input EOS", mName);
204 }
205 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
206 flags |= C2FrameData::FLAG_CODEC_CONFIG;
207 }
208 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
209 std::unique_ptr<C2Work> work(new C2Work);
210 work->input.ordinal.timestamp = timeUs;
211 work->input.ordinal.frameIndex = mFrameIndex++;
212 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
213 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
214 // Keep client timestamp in customOrdinal
215 work->input.ordinal.customOrdinal = timeUs;
216 work->input.buffers.clear();
217
Wonsik Kimab34ed62019-01-31 15:28:46 -0800218 uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
219 std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700220 sp<Codec2Buffer> copy;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800221
Pawin Vongmasa36653902018-11-15 00:10:25 -0800222 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700223 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800224 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700225 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800226 return -ENOENT;
227 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700228 // TODO: we want to delay copying buffers.
229 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
230 copy = input->buffers->cloneAndReleaseBuffer(buffer);
231 if (copy != nullptr) {
232 (void)input->extraBuffers.assignSlot(copy);
233 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
234 return UNKNOWN_ERROR;
235 }
236 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
237 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
238 mName, released ? "" : "not ");
239 buffer.clear();
240 } else {
241 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
242 "buffer starvation on component.", mName);
243 }
244 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800245 work->input.buffers.push_back(c2buffer);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800246 queuedBuffers.push_back(c2buffer);
247 } else if (eos) {
248 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800249 }
250 work->input.flags = (C2FrameData::flags_t)flags;
251 // TODO: fill info's
252
253 work->input.configUpdate = std::move(mParamsToBeSet);
254 work->worklets.clear();
255 work->worklets.emplace_back(new C2Worklet);
256
257 std::list<std::unique_ptr<C2Work>> items;
258 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800259 mPipelineWatcher.lock()->onWorkQueued(
260 queuedFrameIndex,
261 std::move(queuedBuffers),
262 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800263 c2_status_t err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800264 if (err != C2_OK) {
265 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
266 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800267
268 if (err == C2_OK && eos && buffer->size() > 0u) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800269 work.reset(new C2Work);
270 work->input.ordinal.timestamp = timeUs;
271 work->input.ordinal.frameIndex = mFrameIndex++;
272 // WORKAROUND: keep client timestamp in customOrdinal
273 work->input.ordinal.customOrdinal = timeUs;
274 work->input.buffers.clear();
275 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800276 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800277
Wonsik Kimab34ed62019-01-31 15:28:46 -0800278 queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
279 queuedBuffers.clear();
280
Pawin Vongmasa36653902018-11-15 00:10:25 -0800281 items.clear();
282 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800283
284 mPipelineWatcher.lock()->onWorkQueued(
285 queuedFrameIndex,
286 std::move(queuedBuffers),
287 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800288 err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800289 if (err != C2_OK) {
290 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
291 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800292 }
293 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700294 Mutexed<Input>::Locked input(mInput);
295 bool released = false;
296 if (buffer) {
297 released = input->buffers->releaseBuffer(buffer, nullptr, true);
298 } else if (copy) {
299 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
300 }
301 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
302 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800303 }
304
305 feedInputBufferIfAvailableInternal();
306 return err;
307}
308
309status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
310 QueueGuard guard(mSync);
311 if (!guard.isRunning()) {
312 ALOGD("[%s] setParameters is only supported in the running state.", mName);
313 return -ENOSYS;
314 }
315 mParamsToBeSet.insert(mParamsToBeSet.end(),
316 std::make_move_iterator(params.begin()),
317 std::make_move_iterator(params.end()));
318 params.clear();
319 return OK;
320}
321
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800322status_t CCodecBufferChannel::attachBuffer(
323 const std::shared_ptr<C2Buffer> &c2Buffer,
324 const sp<MediaCodecBuffer> &buffer) {
325 if (!buffer->copy(c2Buffer)) {
326 return -ENOSYS;
327 }
328 return OK;
329}
330
331void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
332 if (!mDecryptDestination || mDecryptDestination->size() < size) {
333 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
334 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
335 mCrypto->unsetHeap(mHeapSeqNum);
336 }
337 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
338 if (mCrypto) {
339 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
340 }
341 }
342}
343
344int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
345 CHECK(mCrypto);
346 auto it = mHeapSeqNumMap.find(memory);
347 int32_t heapSeqNum = -1;
348 if (it == mHeapSeqNumMap.end()) {
349 heapSeqNum = mCrypto->setHeap(memory);
350 mHeapSeqNumMap.emplace(memory, heapSeqNum);
351 } else {
352 heapSeqNum = it->second;
353 }
354 return heapSeqNum;
355}
356
357status_t CCodecBufferChannel::attachEncryptedBuffer(
358 const sp<hardware::HidlMemory> &memory,
359 bool secure,
360 const uint8_t *key,
361 const uint8_t *iv,
362 CryptoPlugin::Mode mode,
363 CryptoPlugin::Pattern pattern,
364 size_t offset,
365 const CryptoPlugin::SubSample *subSamples,
366 size_t numSubSamples,
367 const sp<MediaCodecBuffer> &buffer) {
368 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
369 static const C2MemoryUsage kDefaultReadWriteUsage{
370 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
371
372 size_t size = 0;
373 for (size_t i = 0; i < numSubSamples; ++i) {
374 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
375 }
376 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
377 std::shared_ptr<C2LinearBlock> block;
378 c2_status_t err = pool->fetchLinearBlock(
379 size,
380 secure ? kSecureUsage : kDefaultReadWriteUsage,
381 &block);
382 if (err != C2_OK) {
383 return NO_MEMORY;
384 }
385 if (!secure) {
386 ensureDecryptDestination(size);
387 }
388 ssize_t result = -1;
389 ssize_t codecDataOffset = 0;
390 if (mCrypto) {
391 AString errorDetailMsg;
392 int32_t heapSeqNum = getHeapSeqNum(memory);
393 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
394 hardware::drm::V1_0::DestinationBuffer dst;
395 if (secure) {
396 dst.type = DrmBufferType::NATIVE_HANDLE;
397 dst.secureMemory = hardware::hidl_handle(block->handle());
398 } else {
399 dst.type = DrmBufferType::SHARED_MEMORY;
400 IMemoryToSharedBuffer(
401 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
402 }
403 result = mCrypto->decrypt(
404 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
405 dst, &errorDetailMsg);
406 if (result < 0) {
407 return result;
408 }
409 if (dst.type == DrmBufferType::SHARED_MEMORY) {
410 C2WriteView view = block->map().get();
411 if (view.error() != C2_OK) {
412 return false;
413 }
414 if (view.size() < result) {
415 return false;
416 }
417 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
418 }
419 } else {
420 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
421 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
422 hidl_vec<SubSample> hidlSubSamples;
423 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
424
425 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
426 hardware::cas::native::V1_0::DestinationBuffer dst;
427 if (secure) {
428 dst.type = BufferType::NATIVE_HANDLE;
429 dst.secureMemory = hardware::hidl_handle(block->handle());
430 } else {
431 dst.type = BufferType::SHARED_MEMORY;
432 dst.nonsecureMemory = src;
433 }
434
435 CasStatus status = CasStatus::OK;
436 hidl_string detailedError;
437 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
438
439 if (key != nullptr) {
440 sctrl = (ScramblingControl)key[0];
441 // Adjust for the PES offset
442 codecDataOffset = key[2] | (key[3] << 8);
443 }
444
445 auto returnVoid = mDescrambler->descramble(
446 sctrl,
447 hidlSubSamples,
448 src,
449 0,
450 dst,
451 0,
452 [&status, &result, &detailedError] (
453 CasStatus _status, uint32_t _bytesWritten,
454 const hidl_string& _detailedError) {
455 status = _status;
456 result = (ssize_t)_bytesWritten;
457 detailedError = _detailedError;
458 });
459
460 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
461 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
462 mName, returnVoid.description().c_str(), status, result);
463 return UNKNOWN_ERROR;
464 }
465
466 if (result < codecDataOffset) {
467 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
468 return BAD_VALUE;
469 }
470 }
471 if (!secure) {
472 C2WriteView view = block->map().get();
473 if (view.error() != C2_OK) {
474 return UNKNOWN_ERROR;
475 }
476 if (view.size() < result) {
477 return UNKNOWN_ERROR;
478 }
479 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
480 }
481 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
482 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
483 if (!buffer->copy(c2Buffer)) {
484 return -ENOSYS;
485 }
486 return OK;
487}
488
Pawin Vongmasa36653902018-11-15 00:10:25 -0800489status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
490 QueueGuard guard(mSync);
491 if (!guard.isRunning()) {
492 ALOGD("[%s] No more buffers should be queued at current state.", mName);
493 return -ENOSYS;
494 }
495 return queueInputBufferInternal(buffer);
496}
497
498status_t CCodecBufferChannel::queueSecureInputBuffer(
499 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
500 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
501 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
502 AString *errorDetailMsg) {
503 QueueGuard guard(mSync);
504 if (!guard.isRunning()) {
505 ALOGD("[%s] No more buffers should be queued at current state.", mName);
506 return -ENOSYS;
507 }
508
509 if (!hasCryptoOrDescrambler()) {
510 return -ENOSYS;
511 }
512 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
513
514 ssize_t result = -1;
515 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700516 if (numSubSamples == 1
517 && subSamples[0].mNumBytesOfClearData == 0
518 && subSamples[0].mNumBytesOfEncryptedData == 0) {
519 // We don't need to go through crypto or descrambler if the input is empty.
520 result = 0;
521 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700522 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800523 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700524 destination.type = DrmBufferType::NATIVE_HANDLE;
525 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800526 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700527 destination.type = DrmBufferType::SHARED_MEMORY;
528 IMemoryToSharedBuffer(
529 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800530 }
Robert Shih895fba92019-07-16 16:29:44 -0700531 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800532 encryptedBuffer->fillSourceBuffer(&source);
533 result = mCrypto->decrypt(
534 key, iv, mode, pattern, source, buffer->offset(),
535 subSamples, numSubSamples, destination, errorDetailMsg);
536 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700537 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800538 return result;
539 }
Robert Shih895fba92019-07-16 16:29:44 -0700540 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800541 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
542 }
543 } else {
544 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
545 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
546 hidl_vec<SubSample> hidlSubSamples;
547 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
548
549 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
550 encryptedBuffer->fillSourceBuffer(&srcBuffer);
551
552 DestinationBuffer dstBuffer;
553 if (secure) {
554 dstBuffer.type = BufferType::NATIVE_HANDLE;
555 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
556 } else {
557 dstBuffer.type = BufferType::SHARED_MEMORY;
558 dstBuffer.nonsecureMemory = srcBuffer;
559 }
560
561 CasStatus status = CasStatus::OK;
562 hidl_string detailedError;
563 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
564
565 if (key != nullptr) {
566 sctrl = (ScramblingControl)key[0];
567 // Adjust for the PES offset
568 codecDataOffset = key[2] | (key[3] << 8);
569 }
570
571 auto returnVoid = mDescrambler->descramble(
572 sctrl,
573 hidlSubSamples,
574 srcBuffer,
575 0,
576 dstBuffer,
577 0,
578 [&status, &result, &detailedError] (
579 CasStatus _status, uint32_t _bytesWritten,
580 const hidl_string& _detailedError) {
581 status = _status;
582 result = (ssize_t)_bytesWritten;
583 detailedError = _detailedError;
584 });
585
586 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
587 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
588 mName, returnVoid.description().c_str(), status, result);
589 return UNKNOWN_ERROR;
590 }
591
592 if (result < codecDataOffset) {
593 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
594 return BAD_VALUE;
595 }
596
597 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
598
599 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
600 encryptedBuffer->copyDecryptedContentFromMemory(result);
601 }
602 }
603
604 buffer->setRange(codecDataOffset, result - codecDataOffset);
605 return queueInputBufferInternal(buffer);
606}
607
608void CCodecBufferChannel::feedInputBufferIfAvailable() {
609 QueueGuard guard(mSync);
610 if (!guard.isRunning()) {
611 ALOGV("[%s] We're not running --- no input buffer reported", mName);
612 return;
613 }
614 feedInputBufferIfAvailableInternal();
615}
616
617void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800618 if (mInputMetEos ||
Pawin Vongmasab18c1af2020-04-11 05:07:15 -0700619 mOutput.lock()->buffers->hasPending() ||
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800620 mPipelineWatcher.lock()->pipelineFull()) {
621 return;
622 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700623 Mutexed<Output>::Locked output(mOutput);
624 if (output->buffers->numClientBuffers() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800625 return;
626 }
627 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700628 size_t numInputSlots = mInput.lock()->numSlots;
629 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800630 sp<MediaCodecBuffer> inBuffer;
631 size_t index;
632 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700633 Mutexed<Input>::Locked input(mInput);
634 if (input->buffers->numClientBuffers() >= input->numSlots) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800635 return;
636 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700637 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800638 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800639 break;
640 }
641 }
642 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
643 mCallback->onInputBufferAvailable(index, inBuffer);
644 }
645}
646
647status_t CCodecBufferChannel::renderOutputBuffer(
648 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800649 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800650 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800651 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800652 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700653 Mutexed<Output>::Locked output(mOutput);
654 if (output->buffers) {
655 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800656 }
657 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800658 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
659 // set to true.
660 sendOutputBuffers();
661 // input buffer feeding may have been gated by pending output buffers
662 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800663 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800664 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700665 std::call_once(mRenderWarningFlag, [this] {
666 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
667 "timestamp or render=true with non-video buffers. Apps should "
668 "call releaseOutputBuffer() with render=false for those.",
669 mName);
670 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800671 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800672 return INVALID_OPERATION;
673 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800674
675#if 0
676 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
677 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
678 for (const std::shared_ptr<const C2Info> &info : infoParams) {
679 AString res;
680 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
681 if (ix) res.append(", ");
682 res.append(*((int32_t*)info.get() + (ix / 4)));
683 }
684 ALOGV(" [%s]", res.c_str());
685 }
686#endif
687 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
688 std::static_pointer_cast<const C2StreamRotationInfo::output>(
689 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
690 bool flip = rotation && (rotation->flip & 1);
691 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
692 uint32_t transform = 0;
693 switch (quarters) {
694 case 0: // no rotation
695 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
696 break;
697 case 1: // 90 degrees counter-clockwise
698 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
699 : HAL_TRANSFORM_ROT_270;
700 break;
701 case 2: // 180 degrees
702 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
703 break;
704 case 3: // 90 degrees clockwise
705 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
706 : HAL_TRANSFORM_ROT_90;
707 break;
708 }
709
710 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
711 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
712 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
713 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
714 if (surfaceScaling) {
715 videoScalingMode = surfaceScaling->value;
716 }
717
718 // Use dataspace from format as it has the default aspects already applied
719 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
720 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
721
722 // HDR static info
723 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
724 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
725 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
726
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800727 // HDR10 plus info
728 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
729 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
730 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
731
Pawin Vongmasa36653902018-11-15 00:10:25 -0800732 {
733 Mutexed<OutputSurface>::Locked output(mOutputSurface);
734 if (output->surface == nullptr) {
735 ALOGI("[%s] cannot render buffer without surface", mName);
736 return OK;
737 }
738 }
739
740 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
741 if (blocks.size() != 1u) {
742 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
743 return UNKNOWN_ERROR;
744 }
745 const C2ConstGraphicBlock &block = blocks.front();
746
747 // TODO: revisit this after C2Fence implementation.
748 android::IGraphicBufferProducer::QueueBufferInput qbi(
749 timestampNs,
750 false, // droppable
751 dataSpace,
752 Rect(blocks.front().crop().left,
753 blocks.front().crop().top,
754 blocks.front().crop().right(),
755 blocks.front().crop().bottom()),
756 videoScalingMode,
757 transform,
758 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800759 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800760 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800761 if (hdrStaticInfo) {
762 struct android_smpte2086_metadata smpte2086_meta = {
763 .displayPrimaryRed = {
764 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
765 },
766 .displayPrimaryGreen = {
767 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
768 },
769 .displayPrimaryBlue = {
770 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
771 },
772 .whitePoint = {
773 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
774 },
775 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
776 .minLuminance = hdrStaticInfo->mastering.minLuminance,
777 };
778
779 struct android_cta861_3_metadata cta861_meta = {
780 .maxContentLightLevel = hdrStaticInfo->maxCll,
781 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
782 };
783
784 hdr.validTypes = HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3;
785 hdr.smpte2086 = smpte2086_meta;
786 hdr.cta8613 = cta861_meta;
787 }
788 if (hdr10PlusInfo) {
789 hdr.validTypes |= HdrMetadata::HDR10PLUS;
790 hdr.hdr10plus.assign(
791 hdr10PlusInfo->m.value,
792 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
793 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800794 qbi.setHdrMetadata(hdr);
795 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800796 // we don't have dirty regions
797 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800798 android::IGraphicBufferProducer::QueueBufferOutput qbo;
799 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
800 if (result != OK) {
801 ALOGI("[%s] queueBuffer failed: %d", mName, result);
802 return result;
803 }
804 ALOGV("[%s] queue buffer successful", mName);
805
806 int64_t mediaTimeUs = 0;
807 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
808 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
809
810 return OK;
811}
812
813status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
814 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
815 bool released = false;
816 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700817 Mutexed<Input>::Locked input(mInput);
818 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800819 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800820 }
821 }
822 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700823 Mutexed<Output>::Locked output(mOutput);
824 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800825 released = true;
826 }
827 }
828 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800829 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800830 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800831 } else {
832 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
833 }
834 return OK;
835}
836
837void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
838 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700839 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800840
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700841 if (!input->buffers->isArrayMode()) {
842 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800843 }
844
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700845 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800846}
847
848void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
849 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700850 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800851
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700852 if (!output->buffers->isArrayMode()) {
853 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800854 }
855
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700856 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800857}
858
859status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800860 const sp<AMessage> &inputFormat,
861 const sp<AMessage> &outputFormat,
862 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800863 C2StreamBufferTypeSetting::input iStreamFormat(0u);
864 C2StreamBufferTypeSetting::output oStreamFormat(0u);
865 C2PortReorderBufferDepthTuning::output reorderDepth;
866 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800867 C2PortActualDelayTuning::input inputDelay(0);
868 C2PortActualDelayTuning::output outputDelay(0);
869 C2ActualPipelineDelayTuning pipelineDelay(0);
870
Pawin Vongmasa36653902018-11-15 00:10:25 -0800871 c2_status_t err = mComponent->query(
872 {
873 &iStreamFormat,
874 &oStreamFormat,
875 &reorderDepth,
876 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800877 &inputDelay,
878 &pipelineDelay,
879 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800880 },
881 {},
882 C2_DONT_BLOCK,
883 nullptr);
884 if (err == C2_BAD_INDEX) {
885 if (!iStreamFormat || !oStreamFormat) {
886 return UNKNOWN_ERROR;
887 }
888 } else if (err != C2_OK) {
889 return UNKNOWN_ERROR;
890 }
891
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800892 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
893 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
894 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
895
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700896 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
897 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800898
Pawin Vongmasa36653902018-11-15 00:10:25 -0800899 // TODO: get this from input format
900 bool secure = mComponent->getName().find(".secure") != std::string::npos;
901
902 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +0800903 int poolMask = GetCodec2PoolMask();
904 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800905
906 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800907 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800908 std::shared_ptr<C2BlockPool> pool;
909 {
910 Mutexed<BlockPools>::Locked pools(mBlockPools);
911
912 // set default allocator ID.
913 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +0800914 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800915
916 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
917 // from component, create the input block pool with given ID. Otherwise, use default IDs.
918 std::vector<std::unique_ptr<C2Param>> params;
919 err = mComponent->query({ },
920 { C2PortAllocatorsTuning::input::PARAM_TYPE },
921 C2_DONT_BLOCK,
922 &params);
923 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
924 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
925 mName, params.size(), asString(err), err);
926 } else if (err == C2_OK && params.size() == 1) {
927 C2PortAllocatorsTuning::input *inputAllocators =
928 C2PortAllocatorsTuning::input::From(params[0].get());
929 if (inputAllocators && inputAllocators->flexCount() > 0) {
930 std::shared_ptr<C2Allocator> allocator;
931 // verify allocator IDs and resolve default allocator
932 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
933 if (allocator) {
934 pools->inputAllocatorId = allocator->getId();
935 } else {
936 ALOGD("[%s] component requested invalid input allocator ID %u",
937 mName, inputAllocators->m.values[0]);
938 }
939 }
940 }
941
942 // TODO: use C2Component wrapper to associate this pool with ourselves
943 if ((poolMask >> pools->inputAllocatorId) & 1) {
944 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
945 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
946 mName, pools->inputAllocatorId,
947 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
948 asString(err), err);
949 } else {
950 err = C2_NOT_FOUND;
951 }
952 if (err != C2_OK) {
953 C2BlockPool::local_id_t inputPoolId =
954 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
955 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
956 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
957 mName, (unsigned long long)inputPoolId,
958 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
959 asString(err), err);
960 if (err != C2_OK) {
961 return NO_MEMORY;
962 }
963 }
964 pools->inputPool = pool;
965 }
966
Wonsik Kim51051262018-11-28 13:59:05 -0800967 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700968 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -0700969 input->inputDelay = inputDelayValue;
970 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700971 input->numSlots = numInputSlots;
972 input->extraBuffers.flush();
973 input->numExtraSlots = 0u;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800974 if (!buffersBoundToCodec) {
975 input->buffers.reset(new SlotInputBuffers(mName));
976 } else if (graphic) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800977 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700978 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800979 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700980 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -0700981 // This is to ensure buffers do not get released prematurely.
982 // TODO: handle this without going into array mode
983 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800984 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700985 input->buffers.reset(new GraphicInputBuffers(numInputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800986 }
987 } else {
988 if (hasCryptoOrDescrambler()) {
989 int32_t capacity = kLinearBufferSize;
990 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
991 if ((size_t)capacity > kMaxLinearBufferSize) {
992 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
993 capacity = kMaxLinearBufferSize;
994 }
995 if (mDealer == nullptr) {
996 mDealer = new MemoryDealer(
997 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700998 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800999 "EncryptedLinearInputBuffers");
1000 mDecryptDestination = mDealer->allocate((size_t)capacity);
1001 }
1002 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001003 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1004 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001005 } else {
1006 mHeapSeqNum = -1;
1007 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001008 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001009 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001010 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001011 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001012 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001013 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001014 }
1015 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001016 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001017
1018 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001019 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001020 } else {
1021 // TODO: error
1022 }
Wonsik Kim51051262018-11-28 13:59:05 -08001023
1024 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001025 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001026 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001027 }
1028
1029 if (outputFormat != nullptr) {
1030 sp<IGraphicBufferProducer> outputSurface;
1031 uint32_t outputGeneration;
1032 {
1033 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001034 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001035 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001036 if (!secure) {
1037 output->maxDequeueBuffers += numInputSlots;
1038 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001039 outputSurface = output->surface ?
1040 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001041 if (outputSurface) {
1042 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1043 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001044 outputGeneration = output->generation;
1045 }
1046
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001047 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001048 C2BlockPool::local_id_t outputPoolId_;
1049
1050 {
1051 Mutexed<BlockPools>::Locked pools(mBlockPools);
1052
1053 // set default allocator ID.
1054 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001055 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001056
1057 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1058 // unsuccessful.
1059 std::vector<std::unique_ptr<C2Param>> params;
1060 err = mComponent->query({ },
1061 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1062 C2_DONT_BLOCK,
1063 &params);
1064 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1065 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1066 mName, params.size(), asString(err), err);
1067 } else if (err == C2_OK && params.size() == 1) {
1068 C2PortAllocatorsTuning::output *outputAllocators =
1069 C2PortAllocatorsTuning::output::From(params[0].get());
1070 if (outputAllocators && outputAllocators->flexCount() > 0) {
1071 std::shared_ptr<C2Allocator> allocator;
1072 // verify allocator IDs and resolve default allocator
1073 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1074 if (allocator) {
1075 pools->outputAllocatorId = allocator->getId();
1076 } else {
1077 ALOGD("[%s] component requested invalid output allocator ID %u",
1078 mName, outputAllocators->m.values[0]);
1079 }
1080 }
1081 }
1082
1083 // use bufferqueue if outputting to a surface.
1084 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1085 // if unsuccessful.
1086 if (outputSurface) {
1087 params.clear();
1088 err = mComponent->query({ },
1089 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1090 C2_DONT_BLOCK,
1091 &params);
1092 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1093 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1094 mName, params.size(), asString(err), err);
1095 } else if (err == C2_OK && params.size() == 1) {
1096 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1097 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1098 if (surfaceAllocator) {
1099 std::shared_ptr<C2Allocator> allocator;
1100 // verify allocator IDs and resolve default allocator
1101 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1102 if (allocator) {
1103 pools->outputAllocatorId = allocator->getId();
1104 } else {
1105 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1106 mName, surfaceAllocator->value);
1107 err = C2_BAD_VALUE;
1108 }
1109 }
1110 }
1111 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1112 && err != C2_OK
1113 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1114 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1115 }
1116 }
1117
1118 if ((poolMask >> pools->outputAllocatorId) & 1) {
1119 err = mComponent->createBlockPool(
1120 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1121 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1122 mName, pools->outputAllocatorId,
1123 (unsigned long long)pools->outputPoolId,
1124 asString(err));
1125 } else {
1126 err = C2_NOT_FOUND;
1127 }
1128 if (err != C2_OK) {
1129 // use basic pool instead
1130 pools->outputPoolId =
1131 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1132 }
1133
1134 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1135 // component.
1136 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1137 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1138
1139 std::vector<std::unique_ptr<C2SettingResult>> failures;
1140 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1141 ALOGD("[%s] Configured output block pool ids %llu => %s",
1142 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1143 outputPoolId_ = pools->outputPoolId;
1144 }
1145
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001146 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001147 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001148 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001149 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001150 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001151 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001152 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001153 output->buffers.reset(new RawGraphicOutputBuffers(numOutputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001154 }
1155 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001156 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001157 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001158 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001159
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001160 output->buffers->clearStash();
1161 if (reorderDepth) {
1162 output->buffers->setReorderDepth(reorderDepth.value);
1163 }
1164 if (reorderKey) {
1165 output->buffers->setReorderKey(reorderKey.value);
1166 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001167
1168 // Try to set output surface to created block pool if given.
1169 if (outputSurface) {
1170 mComponent->setOutputSurface(
1171 outputPoolId_,
1172 outputSurface,
1173 outputGeneration);
1174 }
1175
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001176 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001177 if (buffersBoundToCodec) {
1178 // WORKAROUND: if we're using early CSD workaround we convert to
1179 // array mode, to appease apps assuming the output
1180 // buffers to be of the same size.
1181 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1182 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001183
1184 int32_t channelCount;
1185 int32_t sampleRate;
1186 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1187 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1188 int32_t delay = 0;
1189 int32_t padding = 0;;
1190 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1191 delay = 0;
1192 }
1193 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1194 padding = 0;
1195 }
1196 if (delay || padding) {
1197 // We need write access to the buffers, and we're already in
1198 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001199 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001200 }
1201 }
1202 }
1203 }
1204
1205 // Set up pipeline control. This has to be done after mInputBuffers and
1206 // mOutputBuffers are initialized to make sure that lingering callbacks
1207 // about buffers from the previous generation do not interfere with the
1208 // newly initialized pipeline capacity.
1209
Wonsik Kimab34ed62019-01-31 15:28:46 -08001210 {
1211 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001212 watcher->inputDelay(inputDelayValue)
1213 .pipelineDelay(pipelineDelayValue)
1214 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001215 .smoothnessFactor(kSmoothnessFactor);
1216 watcher->flush();
1217 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001218
1219 mInputMetEos = false;
1220 mSync.start();
1221 return OK;
1222}
1223
1224status_t CCodecBufferChannel::requestInitialInputBuffers() {
1225 if (mInputSurface) {
1226 return OK;
1227 }
1228
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001229 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001230 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1231 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1232 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001233 return UNKNOWN_ERROR;
1234 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001235 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001236 std::vector<sp<MediaCodecBuffer>> toBeQueued;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001237 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001238 size_t index;
1239 sp<MediaCodecBuffer> buffer;
1240 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001241 Mutexed<Input>::Locked input(mInput);
1242 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001243 if (i == 0) {
1244 ALOGW("[%s] start: cannot allocate memory at all", mName);
1245 return NO_MEMORY;
1246 } else {
1247 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
1248 mName, i);
1249 }
1250 break;
1251 }
1252 }
1253 if (buffer) {
1254 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1255 ALOGV("[%s] input buffer %zu available", mName, index);
1256 bool post = true;
1257 if (!configs->empty()) {
1258 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001259 configs->pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001260 if (buffer->capacity() >= config->size()) {
1261 memcpy(buffer->base(), config->data(), config->size());
1262 buffer->setRange(0, config->size());
1263 buffer->meta()->clear();
1264 buffer->meta()->setInt64("timeUs", 0);
1265 buffer->meta()->setInt32("csd", 1);
1266 post = false;
1267 } else {
1268 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
1269 mName, buffer->capacity(), config->size());
1270 }
1271 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001272 && (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001273 // WORKAROUND: Some apps expect CSD available without queueing
1274 // any input. Queue an empty buffer to get the CSD.
1275 buffer->setRange(0, 0);
1276 buffer->meta()->clear();
1277 buffer->meta()->setInt64("timeUs", 0);
1278 post = false;
1279 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001280 if (post) {
1281 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001282 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001283 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001284 }
1285 }
1286 }
1287 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
1288 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001289 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001290 }
1291 }
1292 return OK;
1293}
1294
1295void CCodecBufferChannel::stop() {
1296 mSync.stop();
1297 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1298 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001299 mInputSurface.reset();
1300 }
1301}
1302
1303void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1304 ALOGV("[%s] flush", mName);
1305 {
1306 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1307 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1308 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1309 continue;
1310 }
1311 if (work->input.buffers.empty()
1312 || work->input.buffers.front()->data().linearBlocks().empty()) {
1313 ALOGD("[%s] no linear codec config data found", mName);
1314 continue;
1315 }
1316 C2ReadView view =
1317 work->input.buffers.front()->data().linearBlocks().front().map().get();
1318 if (view.error() != C2_OK) {
1319 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1320 continue;
1321 }
1322 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1323 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1324 }
1325 }
1326 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001327 Mutexed<Input>::Locked input(mInput);
1328 input->buffers->flush();
1329 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001330 }
1331 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001332 Mutexed<Output>::Locked output(mOutput);
1333 output->buffers->flush(flushedWork);
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001334 output->buffers->flushStash();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001335 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001336 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001337}
1338
1339void CCodecBufferChannel::onWorkDone(
1340 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001341 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001342 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001343 feedInputBufferIfAvailable();
1344 }
1345}
1346
1347void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001348 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001349 if (mInputSurface) {
1350 return;
1351 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001352 std::shared_ptr<C2Buffer> buffer =
1353 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001354 bool newInputSlotAvailable;
1355 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001356 Mutexed<Input>::Locked input(mInput);
1357 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1358 if (!newInputSlotAvailable) {
1359 (void)input->extraBuffers.expireComponentBuffer(buffer);
1360 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001361 }
1362 if (newInputSlotAvailable) {
1363 feedInputBufferIfAvailable();
1364 }
1365}
1366
1367bool CCodecBufferChannel::handleWork(
1368 std::unique_ptr<C2Work> work,
1369 const sp<AMessage> &outputFormat,
1370 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001371 // Whether the output buffer should be reported to the client or not.
1372 bool notifyClient = false;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001373
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001374 if (work->result == C2_OK){
1375 notifyClient = true;
1376 } else if (work->result == C2_NOT_FOUND) {
1377 ALOGD("[%s] flushed work; ignored.", mName);
1378 } else {
1379 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
1380 // the config update.
1381 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1382 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1383 return false;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001384 }
1385
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001386 if ((work->input.ordinal.frameIndex -
1387 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001388 // Discard frames from previous generation.
1389 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001390 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001391 }
1392
Wonsik Kim524b0582019-03-12 11:28:57 -07001393 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 || !work->worklets.front()
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001395 || !(work->worklets.front()->output.flags &
1396 C2FrameData::FLAG_INCOMPLETE))) {
1397 mPipelineWatcher.lock()->onWorkDone(
1398 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001399 }
1400
1401 // NOTE: MediaCodec usage supposedly have only one worklet
1402 if (work->worklets.size() != 1u) {
1403 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1404 mName, work->worklets.size());
1405 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1406 return false;
1407 }
1408
1409 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1410
1411 std::shared_ptr<C2Buffer> buffer;
1412 // NOTE: MediaCodec usage supposedly have only one output stream.
1413 if (worklet->output.buffers.size() > 1u) {
1414 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1415 mName, worklet->output.buffers.size());
1416 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1417 return false;
1418 } else if (worklet->output.buffers.size() == 1u) {
1419 buffer = worklet->output.buffers[0];
1420 if (!buffer) {
1421 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1422 }
1423 }
1424
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001425 std::optional<uint32_t> newInputDelay, newPipelineDelay;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001426 while (!worklet->output.configUpdate.empty()) {
1427 std::unique_ptr<C2Param> param;
1428 worklet->output.configUpdate.back().swap(param);
1429 worklet->output.configUpdate.pop_back();
1430 switch (param->coreIndex().coreIndex()) {
1431 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1432 C2PortReorderBufferDepthTuning::output reorderDepth;
1433 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001434 bool secure = mComponent->getName().find(".secure") !=
1435 std::string::npos;
1436 mOutput.lock()->buffers->setReorderDepth(
1437 reorderDepth.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001438 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1439 mName, reorderDepth.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001440 size_t numOutputSlots = mOutput.lock()->numSlots;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001441 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001442 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001443 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001444 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001445 if (!secure) {
1446 output->maxDequeueBuffers += numInputSlots;
1447 }
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001448 if (output->surface) {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001449 output->surface->setMaxDequeuedBufferCount(
1450 output->maxDequeueBuffers);
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001451 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001452 } else {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001453 ALOGD("[%s] onWorkDone: failed to read reorder depth",
1454 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001455 }
1456 break;
1457 }
1458 case C2PortReorderKeySetting::CORE_INDEX: {
1459 C2PortReorderKeySetting::output reorderKey;
1460 if (reorderKey.updateFrom(*param)) {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001461 mOutput.lock()->buffers->setReorderKey(reorderKey.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001462 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1463 mName, reorderKey.value);
1464 } else {
1465 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1466 }
1467 break;
1468 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001469 case C2PortActualDelayTuning::CORE_INDEX: {
1470 if (param->isGlobal()) {
1471 C2ActualPipelineDelayTuning pipelineDelay;
1472 if (pipelineDelay.updateFrom(*param)) {
1473 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1474 mName, pipelineDelay.value);
1475 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001476 (void)mPipelineWatcher.lock()->pipelineDelay(
1477 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001478 }
1479 }
1480 if (param->forInput()) {
1481 C2PortActualDelayTuning::input inputDelay;
1482 if (inputDelay.updateFrom(*param)) {
1483 ALOGV("[%s] onWorkDone: updating input delay %u",
1484 mName, inputDelay.value);
1485 newInputDelay = inputDelay.value;
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001486 (void)mPipelineWatcher.lock()->inputDelay(
1487 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001488 }
1489 }
1490 if (param->forOutput()) {
1491 C2PortActualDelayTuning::output outputDelay;
1492 if (outputDelay.updateFrom(*param)) {
1493 ALOGV("[%s] onWorkDone: updating output delay %u",
1494 mName, outputDelay.value);
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001495 bool secure = mComponent->getName().find(".secure") !=
1496 std::string::npos;
1497 (void)mPipelineWatcher.lock()->outputDelay(
1498 outputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001499
1500 bool outputBuffersChanged = false;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001501 size_t numOutputSlots = 0;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001502 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001503 {
1504 Mutexed<Output>::Locked output(mOutput);
1505 output->outputDelay = outputDelay.value;
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001506 numOutputSlots = outputDelay.value +
1507 kSmoothnessFactor;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001508 if (output->numSlots < numOutputSlots) {
1509 output->numSlots = numOutputSlots;
1510 if (output->buffers->isArrayMode()) {
1511 OutputBuffersArray *array =
1512 (OutputBuffersArray *)output->buffers.get();
1513 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1514 mName, numOutputSlots);
1515 array->grow(numOutputSlots);
1516 outputBuffersChanged = true;
1517 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001518 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001519 numOutputSlots = output->numSlots;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001520 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001521
1522 if (outputBuffersChanged) {
1523 mCCodecCallback->onOutputBuffersChanged();
1524 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001525
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001526 uint32_t depth = mOutput.lock()->buffers->getReorderDepth();
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001527 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001528 output->maxDequeueBuffers = numOutputSlots + depth + kRenderingDepth;
1529 if (!secure) {
1530 output->maxDequeueBuffers += numInputSlots;
1531 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001532 if (output->surface) {
1533 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1534 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001535 }
1536 }
1537 break;
1538 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001539 default:
1540 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1541 mName, param->index());
1542 break;
1543 }
1544 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001545 if (newInputDelay || newPipelineDelay) {
1546 Mutexed<Input>::Locked input(mInput);
1547 size_t newNumSlots =
1548 newInputDelay.value_or(input->inputDelay) +
1549 newPipelineDelay.value_or(input->pipelineDelay) +
1550 kSmoothnessFactor;
1551 if (input->buffers->isArrayMode()) {
1552 if (input->numSlots >= newNumSlots) {
1553 input->numExtraSlots = 0;
1554 } else {
1555 input->numExtraSlots = newNumSlots - input->numSlots;
1556 }
1557 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1558 mName, input->numExtraSlots);
1559 } else {
1560 input->numSlots = newNumSlots;
1561 }
1562 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001563
Pawin Vongmasa36653902018-11-15 00:10:25 -08001564 int32_t flags = 0;
1565 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1566 flags |= MediaCodec::BUFFER_FLAG_EOS;
1567 ALOGV("[%s] onWorkDone: output EOS", mName);
1568 }
1569
Pawin Vongmasa36653902018-11-15 00:10:25 -08001570 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1571 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1572 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1573 // shall correspond to the client input timesamp (in customOrdinal). By using the
1574 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1575 // produces multiple output.
1576 c2_cntr64_t timestamp =
1577 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1578 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001579 if (mInputSurface != nullptr) {
1580 // When using input surface we need to restore the original input timestamp.
1581 timestamp = work->input.ordinal.customOrdinal;
1582 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001583 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1584 mName,
1585 work->input.ordinal.customOrdinal.peekll(),
1586 work->input.ordinal.timestamp.peekll(),
1587 worklet->output.ordinal.timestamp.peekll(),
1588 timestamp.peekll());
1589
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001590 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001591 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001592 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001593 if (outputFormat) {
1594 output->buffers->updateSkipCutBuffer(outputFormat);
1595 output->buffers->setFormat(outputFormat);
1596 }
1597 if (!notifyClient) {
1598 return false;
1599 }
1600 size_t index;
1601 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001602 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001603 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1604 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1605 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1606
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001607 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001608 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001609 } else {
1610 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001611 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001612 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001613 return false;
1614 }
1615 }
1616
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001617 if (notifyClient && !buffer && !flags) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001618 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1619 mName, work->input.ordinal.frameIndex.peekull());
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001620 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001621 }
1622
1623 if (buffer) {
1624 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1625 // TODO: properly translate these to metadata
1626 switch (info->coreIndex().coreIndex()) {
1627 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001628 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001629 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1630 }
1631 break;
1632 default:
1633 break;
1634 }
1635 }
1636 }
1637
1638 {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001639 Mutexed<Output>::Locked output(mOutput);
1640 output->buffers->pushToStash(
1641 buffer,
1642 notifyClient,
1643 timestamp.peek(),
1644 flags,
1645 outputFormat,
1646 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001647 }
1648 sendOutputBuffers();
1649 return true;
1650}
1651
1652void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001653 OutputBuffers::BufferAction action;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001654 size_t index;
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001655 sp<MediaCodecBuffer> outBuffer;
1656 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001657
1658 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001659 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001660 action = output->buffers->popFromStashAndRegister(
1661 &c2Buffer, &index, &outBuffer);
1662 switch (action) {
1663 case OutputBuffers::SKIP:
1664 return;
1665 case OutputBuffers::DISCARD:
1666 break;
1667 case OutputBuffers::NOTIFY_CLIENT:
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001668 output.unlock();
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001669 mCallback->onOutputBufferAvailable(index, outBuffer);
1670 break;
1671 case OutputBuffers::REALLOCATE: {
1672 if (!output->buffers->isArrayMode()) {
1673 output->buffers =
1674 output->buffers->toArrayMode(output->numSlots);
1675 }
1676 static_cast<OutputBuffersArray*>(output->buffers.get())->
1677 realloc(c2Buffer);
1678 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001679 mCCodecCallback->onOutputBuffersChanged();
1680 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001681 return;
Pawin Vongmasab18c1af2020-04-11 05:07:15 -07001682 case OutputBuffers::RETRY:
1683 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
1684 mName);
1685 return;
1686 default:
1687 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
1688 "corrupted BufferAction value (%d) "
1689 "returned from popFromStashAndRegister.",
1690 mName, int(action));
1691 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001692 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001693 }
1694}
1695
1696status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1697 static std::atomic_uint32_t surfaceGeneration{0};
1698 uint32_t generation = (getpid() << 10) |
1699 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1700 & ((1 << 10) - 1));
1701
1702 sp<IGraphicBufferProducer> producer;
1703 if (newSurface) {
1704 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001705 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Lee08515812019-06-05 11:16:32 -07001706 newSurface->setMaxDequeuedBufferCount(mOutputSurface.lock()->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001707 producer = newSurface->getIGraphicBufferProducer();
1708 producer->setGenerationNumber(generation);
1709 } else {
1710 ALOGE("[%s] setting output surface to null", mName);
1711 return INVALID_OPERATION;
1712 }
1713
1714 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1715 C2BlockPool::local_id_t outputPoolId;
1716 {
1717 Mutexed<BlockPools>::Locked pools(mBlockPools);
1718 outputPoolId = pools->outputPoolId;
1719 outputPoolIntf = pools->outputPoolIntf;
1720 }
1721
1722 if (outputPoolIntf) {
1723 if (mComponent->setOutputSurface(
1724 outputPoolId,
1725 producer,
1726 generation) != C2_OK) {
1727 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1728 return INVALID_OPERATION;
1729 }
1730 }
1731
1732 {
1733 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1734 output->surface = newSurface;
1735 output->generation = generation;
1736 }
1737
1738 return OK;
1739}
1740
Wonsik Kimab34ed62019-01-31 15:28:46 -08001741PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001742 // When client pushed EOS, we want all the work to be done quickly.
1743 // Otherwise, component may have stalled work due to input starvation up to
1744 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001745 size_t n = 0;
1746 if (!mInputMetEos) {
1747 size_t outputDelay = mOutput.lock()->outputDelay;
1748 Mutexed<Input>::Locked input(mInput);
1749 n = input->inputDelay + input->pipelineDelay + outputDelay;
1750 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001751 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001752}
1753
Pawin Vongmasa36653902018-11-15 00:10:25 -08001754void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1755 mMetaMode = mode;
1756}
1757
Wonsik Kim596187e2019-10-25 12:44:10 -07001758void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001759 if (mCrypto != nullptr) {
1760 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
1761 mCrypto->unsetHeap(entry.second);
1762 }
1763 mHeapSeqNumMap.clear();
1764 if (mHeapSeqNum >= 0) {
1765 mCrypto->unsetHeap(mHeapSeqNum);
1766 mHeapSeqNum = -1;
1767 }
1768 }
Wonsik Kim596187e2019-10-25 12:44:10 -07001769 mCrypto = crypto;
1770}
1771
1772void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
1773 mDescrambler = descrambler;
1774}
1775
Pawin Vongmasa36653902018-11-15 00:10:25 -08001776status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1777 // C2_OK is always translated to OK.
1778 if (c2s == C2_OK) {
1779 return OK;
1780 }
1781
1782 // Operation-dependent translation
1783 // TODO: Add as necessary
1784 switch (c2op) {
1785 case C2_OPERATION_Component_start:
1786 switch (c2s) {
1787 case C2_NO_MEMORY:
1788 return NO_MEMORY;
1789 default:
1790 return UNKNOWN_ERROR;
1791 }
1792 default:
1793 break;
1794 }
1795
1796 // Backup operation-agnostic translation
1797 switch (c2s) {
1798 case C2_BAD_INDEX:
1799 return BAD_INDEX;
1800 case C2_BAD_VALUE:
1801 return BAD_VALUE;
1802 case C2_BLOCKING:
1803 return WOULD_BLOCK;
1804 case C2_DUPLICATE:
1805 return ALREADY_EXISTS;
1806 case C2_NO_INIT:
1807 return NO_INIT;
1808 case C2_NO_MEMORY:
1809 return NO_MEMORY;
1810 case C2_NOT_FOUND:
1811 return NAME_NOT_FOUND;
1812 case C2_TIMED_OUT:
1813 return TIMED_OUT;
1814 case C2_BAD_STATE:
1815 case C2_CANCELED:
1816 case C2_CANNOT_DO:
1817 case C2_CORRUPTED:
1818 case C2_OMITTED:
1819 case C2_REFUSED:
1820 return UNKNOWN_ERROR;
1821 default:
1822 return -static_cast<status_t>(c2s);
1823 }
1824}
1825
1826} // namespace android