blob: 00e0c165d4890920433d533f128fbfbb6e46b1b4 [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>
30#include <android-base/stringprintf.h>
31#include <binder/MemoryDealer.h>
32#include <gui/Surface.h>
33#include <media/openmax/OMX_Core.h>
34#include <media/stagefright/foundation/ABuffer.h>
35#include <media/stagefright/foundation/ALookup.h>
36#include <media/stagefright/foundation/AMessage.h>
37#include <media/stagefright/foundation/AUtils.h>
38#include <media/stagefright/foundation/hexdump.h>
39#include <media/stagefright/MediaCodec.h>
40#include <media/stagefright/MediaCodecConstants.h>
41#include <media/MediaCodecBuffer.h>
42#include <system/window.h>
43
44#include "CCodecBufferChannel.h"
45#include "Codec2Buffer.h"
46#include "SkipCutBuffer.h"
47
48namespace android {
49
50using android::base::StringPrintf;
51using hardware::hidl_handle;
52using hardware::hidl_string;
53using hardware::hidl_vec;
54using namespace hardware::cas::V1_0;
55using namespace hardware::cas::native::V1_0;
56
57using CasStatus = hardware::cas::V1_0::Status;
58
Pawin Vongmasa36653902018-11-15 00:10:25 -080059namespace {
60
Wonsik Kim469c8342019-04-11 16:46:09 -070061constexpr size_t kSmoothnessFactor = 4;
62constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080063
64} // namespace
65
66CCodecBufferChannel::QueueGuard::QueueGuard(
67 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
68 Mutex::Autolock l(mSync.mGuardLock);
69 // At this point it's guaranteed that mSync is not under state transition,
70 // as we are holding its mutex.
71
72 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
73 if (count->value == -1) {
74 mRunning = false;
75 } else {
76 ++count->value;
77 mRunning = true;
78 }
79}
80
81CCodecBufferChannel::QueueGuard::~QueueGuard() {
82 if (mRunning) {
83 // We are not holding mGuardLock at this point so that QueueSync::stop() can
84 // keep holding the lock until mCount reaches zero.
85 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
86 --count->value;
87 count->cond.broadcast();
88 }
89}
90
91void CCodecBufferChannel::QueueSync::start() {
92 Mutex::Autolock l(mGuardLock);
93 // If stopped, it goes to running state; otherwise no-op.
94 Mutexed<Counter>::Locked count(mCount);
95 if (count->value == -1) {
96 count->value = 0;
97 }
98}
99
100void CCodecBufferChannel::QueueSync::stop() {
101 Mutex::Autolock l(mGuardLock);
102 Mutexed<Counter>::Locked count(mCount);
103 if (count->value == -1) {
104 // no-op
105 return;
106 }
107 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
108 // mCount can only decrement. In other words, threads that acquired the lock
109 // are allowed to finish execution but additional threads trying to acquire
110 // the lock at this point will block, and then get QueueGuard at STOPPED
111 // state.
112 while (count->value != 0) {
113 count.waitForCondition(count->cond);
114 }
115 count->value = -1;
116}
117
Pawin Vongmasa36653902018-11-15 00:10:25 -0800118// CCodecBufferChannel::ReorderStash
119
120CCodecBufferChannel::ReorderStash::ReorderStash() {
121 clear();
122}
123
124void CCodecBufferChannel::ReorderStash::clear() {
125 mPending.clear();
126 mStash.clear();
127 mDepth = 0;
128 mKey = C2Config::ORDINAL;
129}
130
Wonsik Kim6897f222019-01-30 13:29:24 -0800131void CCodecBufferChannel::ReorderStash::flush() {
132 mPending.clear();
133 mStash.clear();
134}
135
Pawin Vongmasa36653902018-11-15 00:10:25 -0800136void CCodecBufferChannel::ReorderStash::setDepth(uint32_t depth) {
137 mPending.splice(mPending.end(), mStash);
138 mDepth = depth;
139}
Wonsik Kim66427432019-03-21 15:06:22 -0700140
Pawin Vongmasa36653902018-11-15 00:10:25 -0800141void CCodecBufferChannel::ReorderStash::setKey(C2Config::ordinal_key_t key) {
142 mPending.splice(mPending.end(), mStash);
143 mKey = key;
144}
145
146bool CCodecBufferChannel::ReorderStash::pop(Entry *entry) {
147 if (mPending.empty()) {
148 return false;
149 }
150 entry->buffer = mPending.front().buffer;
151 entry->timestamp = mPending.front().timestamp;
152 entry->flags = mPending.front().flags;
153 entry->ordinal = mPending.front().ordinal;
154 mPending.pop_front();
155 return true;
156}
157
158void CCodecBufferChannel::ReorderStash::emplace(
159 const std::shared_ptr<C2Buffer> &buffer,
160 int64_t timestamp,
161 int32_t flags,
162 const C2WorkOrdinalStruct &ordinal) {
Wonsik Kim66427432019-03-21 15:06:22 -0700163 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
164 if (!buffer && eos) {
165 // TRICKY: we may be violating ordering of the stash here. Because we
166 // don't expect any more emplace() calls after this, the ordering should
167 // not matter.
168 mStash.emplace_back(buffer, timestamp, flags, ordinal);
169 } else {
170 flags = flags & ~MediaCodec::BUFFER_FLAG_EOS;
171 auto it = mStash.begin();
172 for (; it != mStash.end(); ++it) {
173 if (less(ordinal, it->ordinal)) {
174 break;
175 }
176 }
177 mStash.emplace(it, buffer, timestamp, flags, ordinal);
178 if (eos) {
179 mStash.back().flags = mStash.back().flags | MediaCodec::BUFFER_FLAG_EOS;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800180 }
181 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800182 while (!mStash.empty() && mStash.size() > mDepth) {
183 mPending.push_back(mStash.front());
184 mStash.pop_front();
185 }
186}
187
188void CCodecBufferChannel::ReorderStash::defer(
189 const CCodecBufferChannel::ReorderStash::Entry &entry) {
190 mPending.push_front(entry);
191}
192
193bool CCodecBufferChannel::ReorderStash::hasPending() const {
194 return !mPending.empty();
195}
196
197bool CCodecBufferChannel::ReorderStash::less(
198 const C2WorkOrdinalStruct &o1, const C2WorkOrdinalStruct &o2) {
199 switch (mKey) {
200 case C2Config::ORDINAL: return o1.frameIndex < o2.frameIndex;
201 case C2Config::TIMESTAMP: return o1.timestamp < o2.timestamp;
202 case C2Config::CUSTOM: return o1.customOrdinal < o2.customOrdinal;
203 default:
204 ALOGD("Unrecognized key; default to timestamp");
205 return o1.frameIndex < o2.frameIndex;
206 }
207}
208
209// CCodecBufferChannel
210
211CCodecBufferChannel::CCodecBufferChannel(
212 const std::shared_ptr<CCodecCallback> &callback)
213 : mHeapSeqNum(-1),
214 mCCodecCallback(callback),
Wonsik Kim078b58e2019-01-09 15:08:06 -0800215 mNumInputSlots(kSmoothnessFactor),
216 mNumOutputSlots(kSmoothnessFactor),
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800217 mDelay(0),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800218 mFrameIndex(0u),
219 mFirstValidFrameIndex(0u),
220 mMetaMode(MODE_NONE),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800221 mInputMetEos(false) {
Wonsik Kimf5e5c832019-02-21 11:36:05 -0800222 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800223 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
224 buffers->reset(new DummyInputBuffers(""));
225}
226
227CCodecBufferChannel::~CCodecBufferChannel() {
228 if (mCrypto != nullptr && mDealer != nullptr && mHeapSeqNum >= 0) {
229 mCrypto->unsetHeap(mHeapSeqNum);
230 }
231}
232
233void CCodecBufferChannel::setComponent(
234 const std::shared_ptr<Codec2Client::Component> &component) {
235 mComponent = component;
236 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
237 mName = mComponentName.c_str();
238}
239
240status_t CCodecBufferChannel::setInputSurface(
241 const std::shared_ptr<InputSurfaceWrapper> &surface) {
242 ALOGV("[%s] setInputSurface", mName);
243 mInputSurface = surface;
244 return mInputSurface->connect(mComponent);
245}
246
247status_t CCodecBufferChannel::signalEndOfInputStream() {
248 if (mInputSurface == nullptr) {
249 return INVALID_OPERATION;
250 }
251 return mInputSurface->signalEndOfInputStream();
252}
253
254status_t CCodecBufferChannel::queueInputBufferInternal(const sp<MediaCodecBuffer> &buffer) {
255 int64_t timeUs;
256 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
257
258 if (mInputMetEos) {
259 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
260 return OK;
261 }
262
263 int32_t flags = 0;
264 int32_t tmp = 0;
265 bool eos = false;
266 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
267 eos = true;
268 mInputMetEos = true;
269 ALOGV("[%s] input EOS", mName);
270 }
271 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
272 flags |= C2FrameData::FLAG_CODEC_CONFIG;
273 }
274 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
275 std::unique_ptr<C2Work> work(new C2Work);
276 work->input.ordinal.timestamp = timeUs;
277 work->input.ordinal.frameIndex = mFrameIndex++;
278 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
279 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
280 // Keep client timestamp in customOrdinal
281 work->input.ordinal.customOrdinal = timeUs;
282 work->input.buffers.clear();
283
Wonsik Kimab34ed62019-01-31 15:28:46 -0800284 uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
285 std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
286
Pawin Vongmasa36653902018-11-15 00:10:25 -0800287 if (buffer->size() > 0u) {
288 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
289 std::shared_ptr<C2Buffer> c2buffer;
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800290 if (!(*buffers)->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800291 return -ENOENT;
292 }
293 work->input.buffers.push_back(c2buffer);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800294 queuedBuffers.push_back(c2buffer);
295 } else if (eos) {
296 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800297 }
298 work->input.flags = (C2FrameData::flags_t)flags;
299 // TODO: fill info's
300
301 work->input.configUpdate = std::move(mParamsToBeSet);
302 work->worklets.clear();
303 work->worklets.emplace_back(new C2Worklet);
304
305 std::list<std::unique_ptr<C2Work>> items;
306 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800307 mPipelineWatcher.lock()->onWorkQueued(
308 queuedFrameIndex,
309 std::move(queuedBuffers),
310 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800311 c2_status_t err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800312 if (err != C2_OK) {
313 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
314 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800315
316 if (err == C2_OK && eos && buffer->size() > 0u) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800317 work.reset(new C2Work);
318 work->input.ordinal.timestamp = timeUs;
319 work->input.ordinal.frameIndex = mFrameIndex++;
320 // WORKAROUND: keep client timestamp in customOrdinal
321 work->input.ordinal.customOrdinal = timeUs;
322 work->input.buffers.clear();
323 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800324 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800325
Wonsik Kimab34ed62019-01-31 15:28:46 -0800326 queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
327 queuedBuffers.clear();
328
Pawin Vongmasa36653902018-11-15 00:10:25 -0800329 items.clear();
330 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800331
332 mPipelineWatcher.lock()->onWorkQueued(
333 queuedFrameIndex,
334 std::move(queuedBuffers),
335 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800336 err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800337 if (err != C2_OK) {
338 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
339 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800340 }
341 if (err == C2_OK) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800342 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
343 bool released = (*buffers)->releaseBuffer(buffer, nullptr, true);
344 ALOGV("[%s] queueInputBuffer: buffer %sreleased", mName, released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800345 }
346
347 feedInputBufferIfAvailableInternal();
348 return err;
349}
350
351status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
352 QueueGuard guard(mSync);
353 if (!guard.isRunning()) {
354 ALOGD("[%s] setParameters is only supported in the running state.", mName);
355 return -ENOSYS;
356 }
357 mParamsToBeSet.insert(mParamsToBeSet.end(),
358 std::make_move_iterator(params.begin()),
359 std::make_move_iterator(params.end()));
360 params.clear();
361 return OK;
362}
363
364status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
365 QueueGuard guard(mSync);
366 if (!guard.isRunning()) {
367 ALOGD("[%s] No more buffers should be queued at current state.", mName);
368 return -ENOSYS;
369 }
370 return queueInputBufferInternal(buffer);
371}
372
373status_t CCodecBufferChannel::queueSecureInputBuffer(
374 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
375 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
376 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
377 AString *errorDetailMsg) {
378 QueueGuard guard(mSync);
379 if (!guard.isRunning()) {
380 ALOGD("[%s] No more buffers should be queued at current state.", mName);
381 return -ENOSYS;
382 }
383
384 if (!hasCryptoOrDescrambler()) {
385 return -ENOSYS;
386 }
387 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
388
389 ssize_t result = -1;
390 ssize_t codecDataOffset = 0;
391 if (mCrypto != nullptr) {
392 ICrypto::DestinationBuffer destination;
393 if (secure) {
394 destination.mType = ICrypto::kDestinationTypeNativeHandle;
395 destination.mHandle = encryptedBuffer->handle();
396 } else {
397 destination.mType = ICrypto::kDestinationTypeSharedMemory;
398 destination.mSharedMemory = mDecryptDestination;
399 }
400 ICrypto::SourceBuffer source;
401 encryptedBuffer->fillSourceBuffer(&source);
402 result = mCrypto->decrypt(
403 key, iv, mode, pattern, source, buffer->offset(),
404 subSamples, numSubSamples, destination, errorDetailMsg);
405 if (result < 0) {
406 return result;
407 }
408 if (destination.mType == ICrypto::kDestinationTypeSharedMemory) {
409 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
410 }
411 } else {
412 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
413 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
414 hidl_vec<SubSample> hidlSubSamples;
415 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
416
417 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
418 encryptedBuffer->fillSourceBuffer(&srcBuffer);
419
420 DestinationBuffer dstBuffer;
421 if (secure) {
422 dstBuffer.type = BufferType::NATIVE_HANDLE;
423 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
424 } else {
425 dstBuffer.type = BufferType::SHARED_MEMORY;
426 dstBuffer.nonsecureMemory = srcBuffer;
427 }
428
429 CasStatus status = CasStatus::OK;
430 hidl_string detailedError;
431 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
432
433 if (key != nullptr) {
434 sctrl = (ScramblingControl)key[0];
435 // Adjust for the PES offset
436 codecDataOffset = key[2] | (key[3] << 8);
437 }
438
439 auto returnVoid = mDescrambler->descramble(
440 sctrl,
441 hidlSubSamples,
442 srcBuffer,
443 0,
444 dstBuffer,
445 0,
446 [&status, &result, &detailedError] (
447 CasStatus _status, uint32_t _bytesWritten,
448 const hidl_string& _detailedError) {
449 status = _status;
450 result = (ssize_t)_bytesWritten;
451 detailedError = _detailedError;
452 });
453
454 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
455 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
456 mName, returnVoid.description().c_str(), status, result);
457 return UNKNOWN_ERROR;
458 }
459
460 if (result < codecDataOffset) {
461 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
462 return BAD_VALUE;
463 }
464
465 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
466
467 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
468 encryptedBuffer->copyDecryptedContentFromMemory(result);
469 }
470 }
471
472 buffer->setRange(codecDataOffset, result - codecDataOffset);
473 return queueInputBufferInternal(buffer);
474}
475
476void CCodecBufferChannel::feedInputBufferIfAvailable() {
477 QueueGuard guard(mSync);
478 if (!guard.isRunning()) {
479 ALOGV("[%s] We're not running --- no input buffer reported", mName);
480 return;
481 }
482 feedInputBufferIfAvailableInternal();
483}
484
485void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800486 if (mInputMetEos ||
487 mReorderStash.lock()->hasPending() ||
488 mPipelineWatcher.lock()->pipelineFull()) {
489 return;
490 } else {
491 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
492 if ((*buffers)->numClientBuffers() >= mNumOutputSlots) {
493 return;
494 }
495 }
496 for (size_t i = 0; i < mNumInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800497 sp<MediaCodecBuffer> inBuffer;
498 size_t index;
499 {
500 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800501 if ((*buffers)->numClientBuffers() >= mNumInputSlots) {
502 return;
503 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800504 if (!(*buffers)->requestNewBuffer(&index, &inBuffer)) {
505 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800506 break;
507 }
508 }
509 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
510 mCallback->onInputBufferAvailable(index, inBuffer);
511 }
512}
513
514status_t CCodecBufferChannel::renderOutputBuffer(
515 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800516 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800517 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800518 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800519 {
520 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
521 if (*buffers) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800522 released = (*buffers)->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800523 }
524 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800525 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
526 // set to true.
527 sendOutputBuffers();
528 // input buffer feeding may have been gated by pending output buffers
529 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800530 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800531 if (released) {
532 ALOGD("[%s] The app is calling releaseOutputBuffer() with "
533 "timestamp or render=true with non-video buffers. Apps should "
534 "call releaseOutputBuffer() with render=false for those.",
535 mName);
536 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800537 return INVALID_OPERATION;
538 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800539
540#if 0
541 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
542 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
543 for (const std::shared_ptr<const C2Info> &info : infoParams) {
544 AString res;
545 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
546 if (ix) res.append(", ");
547 res.append(*((int32_t*)info.get() + (ix / 4)));
548 }
549 ALOGV(" [%s]", res.c_str());
550 }
551#endif
552 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
553 std::static_pointer_cast<const C2StreamRotationInfo::output>(
554 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
555 bool flip = rotation && (rotation->flip & 1);
556 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
557 uint32_t transform = 0;
558 switch (quarters) {
559 case 0: // no rotation
560 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
561 break;
562 case 1: // 90 degrees counter-clockwise
563 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
564 : HAL_TRANSFORM_ROT_270;
565 break;
566 case 2: // 180 degrees
567 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
568 break;
569 case 3: // 90 degrees clockwise
570 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
571 : HAL_TRANSFORM_ROT_90;
572 break;
573 }
574
575 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
576 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
577 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
578 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
579 if (surfaceScaling) {
580 videoScalingMode = surfaceScaling->value;
581 }
582
583 // Use dataspace from format as it has the default aspects already applied
584 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
585 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
586
587 // HDR static info
588 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
589 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
590 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
591
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800592 // HDR10 plus info
593 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
594 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
595 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
596
Pawin Vongmasa36653902018-11-15 00:10:25 -0800597 {
598 Mutexed<OutputSurface>::Locked output(mOutputSurface);
599 if (output->surface == nullptr) {
600 ALOGI("[%s] cannot render buffer without surface", mName);
601 return OK;
602 }
603 }
604
605 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
606 if (blocks.size() != 1u) {
607 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
608 return UNKNOWN_ERROR;
609 }
610 const C2ConstGraphicBlock &block = blocks.front();
611
612 // TODO: revisit this after C2Fence implementation.
613 android::IGraphicBufferProducer::QueueBufferInput qbi(
614 timestampNs,
615 false, // droppable
616 dataSpace,
617 Rect(blocks.front().crop().left,
618 blocks.front().crop().top,
619 blocks.front().crop().right(),
620 blocks.front().crop().bottom()),
621 videoScalingMode,
622 transform,
623 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800624 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800625 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800626 if (hdrStaticInfo) {
627 struct android_smpte2086_metadata smpte2086_meta = {
628 .displayPrimaryRed = {
629 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
630 },
631 .displayPrimaryGreen = {
632 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
633 },
634 .displayPrimaryBlue = {
635 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
636 },
637 .whitePoint = {
638 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
639 },
640 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
641 .minLuminance = hdrStaticInfo->mastering.minLuminance,
642 };
643
644 struct android_cta861_3_metadata cta861_meta = {
645 .maxContentLightLevel = hdrStaticInfo->maxCll,
646 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
647 };
648
649 hdr.validTypes = HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3;
650 hdr.smpte2086 = smpte2086_meta;
651 hdr.cta8613 = cta861_meta;
652 }
653 if (hdr10PlusInfo) {
654 hdr.validTypes |= HdrMetadata::HDR10PLUS;
655 hdr.hdr10plus.assign(
656 hdr10PlusInfo->m.value,
657 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
658 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800659 qbi.setHdrMetadata(hdr);
660 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800661 // we don't have dirty regions
662 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800663 android::IGraphicBufferProducer::QueueBufferOutput qbo;
664 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
665 if (result != OK) {
666 ALOGI("[%s] queueBuffer failed: %d", mName, result);
667 return result;
668 }
669 ALOGV("[%s] queue buffer successful", mName);
670
671 int64_t mediaTimeUs = 0;
672 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
673 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
674
675 return OK;
676}
677
678status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
679 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
680 bool released = false;
681 {
682 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800683 if (*buffers && (*buffers)->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800684 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800685 }
686 }
687 {
688 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
689 if (*buffers && (*buffers)->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800690 released = true;
691 }
692 }
693 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800694 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800695 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800696 } else {
697 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
698 }
699 return OK;
700}
701
702void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
703 array->clear();
704 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
705
706 if (!(*buffers)->isArrayMode()) {
Wonsik Kim078b58e2019-01-09 15:08:06 -0800707 *buffers = (*buffers)->toArrayMode(mNumInputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800708 }
709
710 (*buffers)->getArray(array);
711}
712
713void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
714 array->clear();
715 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
716
717 if (!(*buffers)->isArrayMode()) {
Wonsik Kim078b58e2019-01-09 15:08:06 -0800718 *buffers = (*buffers)->toArrayMode(mNumOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800719 }
720
721 (*buffers)->getArray(array);
722}
723
724status_t CCodecBufferChannel::start(
725 const sp<AMessage> &inputFormat, const sp<AMessage> &outputFormat) {
726 C2StreamBufferTypeSetting::input iStreamFormat(0u);
727 C2StreamBufferTypeSetting::output oStreamFormat(0u);
728 C2PortReorderBufferDepthTuning::output reorderDepth;
729 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800730 C2PortActualDelayTuning::input inputDelay(0);
731 C2PortActualDelayTuning::output outputDelay(0);
732 C2ActualPipelineDelayTuning pipelineDelay(0);
733
Pawin Vongmasa36653902018-11-15 00:10:25 -0800734 c2_status_t err = mComponent->query(
735 {
736 &iStreamFormat,
737 &oStreamFormat,
738 &reorderDepth,
739 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800740 &inputDelay,
741 &pipelineDelay,
742 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800743 },
744 {},
745 C2_DONT_BLOCK,
746 nullptr);
747 if (err == C2_BAD_INDEX) {
748 if (!iStreamFormat || !oStreamFormat) {
749 return UNKNOWN_ERROR;
750 }
751 } else if (err != C2_OK) {
752 return UNKNOWN_ERROR;
753 }
754
755 {
756 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
757 reorder->clear();
758 if (reorderDepth) {
759 reorder->setDepth(reorderDepth.value);
760 }
761 if (reorderKey) {
762 reorder->setKey(reorderKey.value);
763 }
764 }
Wonsik Kim078b58e2019-01-09 15:08:06 -0800765
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800766 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
767 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
768 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
769
770 mNumInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
771 mNumOutputSlots = outputDelayValue + kSmoothnessFactor;
772 mDelay = inputDelayValue + pipelineDelayValue + outputDelayValue;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800773
Pawin Vongmasa36653902018-11-15 00:10:25 -0800774 // TODO: get this from input format
775 bool secure = mComponent->getName().find(".secure") != std::string::npos;
776
777 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
778 int poolMask = property_get_int32(
779 "debug.stagefright.c2-poolmask",
780 1 << C2PlatformAllocatorStore::ION |
781 1 << C2PlatformAllocatorStore::BUFFERQUEUE);
782
783 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800784 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800785 std::shared_ptr<C2BlockPool> pool;
786 {
787 Mutexed<BlockPools>::Locked pools(mBlockPools);
788
789 // set default allocator ID.
790 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
791 : C2PlatformAllocatorStore::ION;
792
793 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
794 // from component, create the input block pool with given ID. Otherwise, use default IDs.
795 std::vector<std::unique_ptr<C2Param>> params;
796 err = mComponent->query({ },
797 { C2PortAllocatorsTuning::input::PARAM_TYPE },
798 C2_DONT_BLOCK,
799 &params);
800 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
801 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
802 mName, params.size(), asString(err), err);
803 } else if (err == C2_OK && params.size() == 1) {
804 C2PortAllocatorsTuning::input *inputAllocators =
805 C2PortAllocatorsTuning::input::From(params[0].get());
806 if (inputAllocators && inputAllocators->flexCount() > 0) {
807 std::shared_ptr<C2Allocator> allocator;
808 // verify allocator IDs and resolve default allocator
809 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
810 if (allocator) {
811 pools->inputAllocatorId = allocator->getId();
812 } else {
813 ALOGD("[%s] component requested invalid input allocator ID %u",
814 mName, inputAllocators->m.values[0]);
815 }
816 }
817 }
818
819 // TODO: use C2Component wrapper to associate this pool with ourselves
820 if ((poolMask >> pools->inputAllocatorId) & 1) {
821 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
822 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
823 mName, pools->inputAllocatorId,
824 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
825 asString(err), err);
826 } else {
827 err = C2_NOT_FOUND;
828 }
829 if (err != C2_OK) {
830 C2BlockPool::local_id_t inputPoolId =
831 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
832 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
833 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
834 mName, (unsigned long long)inputPoolId,
835 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
836 asString(err), err);
837 if (err != C2_OK) {
838 return NO_MEMORY;
839 }
840 }
841 pools->inputPool = pool;
842 }
843
Wonsik Kim51051262018-11-28 13:59:05 -0800844 bool forceArrayMode = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800845 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
846 if (graphic) {
847 if (mInputSurface) {
848 buffers->reset(new DummyInputBuffers(mName));
849 } else if (mMetaMode == MODE_ANW) {
850 buffers->reset(new GraphicMetadataInputBuffers(mName));
851 } else {
Wonsik Kim078b58e2019-01-09 15:08:06 -0800852 buffers->reset(new GraphicInputBuffers(mNumInputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800853 }
854 } else {
855 if (hasCryptoOrDescrambler()) {
856 int32_t capacity = kLinearBufferSize;
857 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
858 if ((size_t)capacity > kMaxLinearBufferSize) {
859 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
860 capacity = kMaxLinearBufferSize;
861 }
862 if (mDealer == nullptr) {
863 mDealer = new MemoryDealer(
864 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim078b58e2019-01-09 15:08:06 -0800865 * (mNumInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800866 "EncryptedLinearInputBuffers");
867 mDecryptDestination = mDealer->allocate((size_t)capacity);
868 }
869 if (mCrypto != nullptr && mHeapSeqNum < 0) {
870 mHeapSeqNum = mCrypto->setHeap(mDealer->getMemoryHeap());
871 } else {
872 mHeapSeqNum = -1;
873 }
874 buffers->reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -0800875 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
876 mNumInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -0800877 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800878 } else {
879 buffers->reset(new LinearInputBuffers(mName));
880 }
881 }
882 (*buffers)->setFormat(inputFormat);
883
884 if (err == C2_OK) {
885 (*buffers)->setPool(pool);
886 } else {
887 // TODO: error
888 }
Wonsik Kim51051262018-11-28 13:59:05 -0800889
890 if (forceArrayMode) {
Wonsik Kim078b58e2019-01-09 15:08:06 -0800891 *buffers = (*buffers)->toArrayMode(mNumInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -0800892 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800893 }
894
895 if (outputFormat != nullptr) {
896 sp<IGraphicBufferProducer> outputSurface;
897 uint32_t outputGeneration;
898 {
899 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Wonsik Kimf5e5c832019-02-21 11:36:05 -0800900 output->maxDequeueBuffers = mNumOutputSlots + reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800901 outputSurface = output->surface ?
902 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -0800903 if (outputSurface) {
904 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
905 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800906 outputGeneration = output->generation;
907 }
908
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800909 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800910 C2BlockPool::local_id_t outputPoolId_;
911
912 {
913 Mutexed<BlockPools>::Locked pools(mBlockPools);
914
915 // set default allocator ID.
916 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
917 : C2PlatformAllocatorStore::ION;
918
919 // query C2PortAllocatorsTuning::output from component, or use default allocator if
920 // unsuccessful.
921 std::vector<std::unique_ptr<C2Param>> params;
922 err = mComponent->query({ },
923 { C2PortAllocatorsTuning::output::PARAM_TYPE },
924 C2_DONT_BLOCK,
925 &params);
926 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
927 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
928 mName, params.size(), asString(err), err);
929 } else if (err == C2_OK && params.size() == 1) {
930 C2PortAllocatorsTuning::output *outputAllocators =
931 C2PortAllocatorsTuning::output::From(params[0].get());
932 if (outputAllocators && outputAllocators->flexCount() > 0) {
933 std::shared_ptr<C2Allocator> allocator;
934 // verify allocator IDs and resolve default allocator
935 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
936 if (allocator) {
937 pools->outputAllocatorId = allocator->getId();
938 } else {
939 ALOGD("[%s] component requested invalid output allocator ID %u",
940 mName, outputAllocators->m.values[0]);
941 }
942 }
943 }
944
945 // use bufferqueue if outputting to a surface.
946 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
947 // if unsuccessful.
948 if (outputSurface) {
949 params.clear();
950 err = mComponent->query({ },
951 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
952 C2_DONT_BLOCK,
953 &params);
954 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
955 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
956 mName, params.size(), asString(err), err);
957 } else if (err == C2_OK && params.size() == 1) {
958 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
959 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
960 if (surfaceAllocator) {
961 std::shared_ptr<C2Allocator> allocator;
962 // verify allocator IDs and resolve default allocator
963 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
964 if (allocator) {
965 pools->outputAllocatorId = allocator->getId();
966 } else {
967 ALOGD("[%s] component requested invalid surface output allocator ID %u",
968 mName, surfaceAllocator->value);
969 err = C2_BAD_VALUE;
970 }
971 }
972 }
973 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
974 && err != C2_OK
975 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
976 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
977 }
978 }
979
980 if ((poolMask >> pools->outputAllocatorId) & 1) {
981 err = mComponent->createBlockPool(
982 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
983 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
984 mName, pools->outputAllocatorId,
985 (unsigned long long)pools->outputPoolId,
986 asString(err));
987 } else {
988 err = C2_NOT_FOUND;
989 }
990 if (err != C2_OK) {
991 // use basic pool instead
992 pools->outputPoolId =
993 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
994 }
995
996 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
997 // component.
998 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
999 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1000
1001 std::vector<std::unique_ptr<C2SettingResult>> failures;
1002 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1003 ALOGD("[%s] Configured output block pool ids %llu => %s",
1004 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1005 outputPoolId_ = pools->outputPoolId;
1006 }
1007
1008 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1009
1010 if (graphic) {
1011 if (outputSurface) {
1012 buffers->reset(new GraphicOutputBuffers(mName));
1013 } else {
Wonsik Kim078b58e2019-01-09 15:08:06 -08001014 buffers->reset(new RawGraphicOutputBuffers(mNumOutputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001015 }
1016 } else {
1017 buffers->reset(new LinearOutputBuffers(mName));
1018 }
1019 (*buffers)->setFormat(outputFormat->dup());
1020
1021
1022 // Try to set output surface to created block pool if given.
1023 if (outputSurface) {
1024 mComponent->setOutputSurface(
1025 outputPoolId_,
1026 outputSurface,
1027 outputGeneration);
1028 }
1029
1030 if (oStreamFormat.value == C2BufferData::LINEAR
1031 && mComponentName.find("c2.qti.") == std::string::npos) {
1032 // WORKAROUND: if we're using early CSD workaround we convert to
1033 // array mode, to appease apps assuming the output
1034 // buffers to be of the same size.
Wonsik Kim078b58e2019-01-09 15:08:06 -08001035 (*buffers) = (*buffers)->toArrayMode(mNumOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001036
1037 int32_t channelCount;
1038 int32_t sampleRate;
1039 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1040 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1041 int32_t delay = 0;
1042 int32_t padding = 0;;
1043 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1044 delay = 0;
1045 }
1046 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1047 padding = 0;
1048 }
1049 if (delay || padding) {
1050 // We need write access to the buffers, and we're already in
1051 // array mode.
1052 (*buffers)->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
1053 }
1054 }
1055 }
1056 }
1057
1058 // Set up pipeline control. This has to be done after mInputBuffers and
1059 // mOutputBuffers are initialized to make sure that lingering callbacks
1060 // about buffers from the previous generation do not interfere with the
1061 // newly initialized pipeline capacity.
1062
Wonsik Kimab34ed62019-01-31 15:28:46 -08001063 {
1064 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001065 watcher->inputDelay(inputDelayValue)
1066 .pipelineDelay(pipelineDelayValue)
1067 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001068 .smoothnessFactor(kSmoothnessFactor);
1069 watcher->flush();
1070 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001071
1072 mInputMetEos = false;
1073 mSync.start();
1074 return OK;
1075}
1076
1077status_t CCodecBufferChannel::requestInitialInputBuffers() {
1078 if (mInputSurface) {
1079 return OK;
1080 }
1081
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001082 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001083 c2_status_t err = mComponent->query({ &oStreamFormat }, {}, C2_DONT_BLOCK, nullptr);
1084 if (err != C2_OK) {
1085 return UNKNOWN_ERROR;
1086 }
1087 std::vector<sp<MediaCodecBuffer>> toBeQueued;
1088 // TODO: use proper buffer depth instead of this random value
Wonsik Kim078b58e2019-01-09 15:08:06 -08001089 for (size_t i = 0; i < mNumInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001090 size_t index;
1091 sp<MediaCodecBuffer> buffer;
1092 {
1093 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1094 if (!(*buffers)->requestNewBuffer(&index, &buffer)) {
1095 if (i == 0) {
1096 ALOGW("[%s] start: cannot allocate memory at all", mName);
1097 return NO_MEMORY;
1098 } else {
1099 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
1100 mName, i);
1101 }
1102 break;
1103 }
1104 }
1105 if (buffer) {
1106 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1107 ALOGV("[%s] input buffer %zu available", mName, index);
1108 bool post = true;
1109 if (!configs->empty()) {
1110 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001111 configs->pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001112 if (buffer->capacity() >= config->size()) {
1113 memcpy(buffer->base(), config->data(), config->size());
1114 buffer->setRange(0, config->size());
1115 buffer->meta()->clear();
1116 buffer->meta()->setInt64("timeUs", 0);
1117 buffer->meta()->setInt32("csd", 1);
1118 post = false;
1119 } else {
1120 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
1121 mName, buffer->capacity(), config->size());
1122 }
1123 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
1124 && mComponentName.find("c2.qti.") == std::string::npos) {
1125 // WORKAROUND: Some apps expect CSD available without queueing
1126 // any input. Queue an empty buffer to get the CSD.
1127 buffer->setRange(0, 0);
1128 buffer->meta()->clear();
1129 buffer->meta()->setInt64("timeUs", 0);
1130 post = false;
1131 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001132 if (post) {
1133 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001134 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001135 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001136 }
1137 }
1138 }
1139 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
1140 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001141 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001142 }
1143 }
1144 return OK;
1145}
1146
1147void CCodecBufferChannel::stop() {
1148 mSync.stop();
1149 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1150 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001151 mInputSurface.reset();
1152 }
1153}
1154
1155void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1156 ALOGV("[%s] flush", mName);
1157 {
1158 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1159 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1160 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1161 continue;
1162 }
1163 if (work->input.buffers.empty()
1164 || work->input.buffers.front()->data().linearBlocks().empty()) {
1165 ALOGD("[%s] no linear codec config data found", mName);
1166 continue;
1167 }
1168 C2ReadView view =
1169 work->input.buffers.front()->data().linearBlocks().front().map().get();
1170 if (view.error() != C2_OK) {
1171 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1172 continue;
1173 }
1174 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1175 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1176 }
1177 }
1178 {
1179 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1180 (*buffers)->flush();
1181 }
1182 {
1183 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1184 (*buffers)->flush(flushedWork);
1185 }
Wonsik Kim6897f222019-01-30 13:29:24 -08001186 mReorderStash.lock()->flush();
Wonsik Kimab34ed62019-01-31 15:28:46 -08001187 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001188}
1189
1190void CCodecBufferChannel::onWorkDone(
1191 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001192 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001193 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001194 feedInputBufferIfAvailable();
1195 }
1196}
1197
1198void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001199 uint64_t frameIndex, size_t arrayIndex) {
1200 std::shared_ptr<C2Buffer> buffer =
1201 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001202 bool newInputSlotAvailable;
1203 {
1204 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1205 newInputSlotAvailable = (*buffers)->expireComponentBuffer(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001206 }
1207 if (newInputSlotAvailable) {
1208 feedInputBufferIfAvailable();
1209 }
1210}
1211
1212bool CCodecBufferChannel::handleWork(
1213 std::unique_ptr<C2Work> work,
1214 const sp<AMessage> &outputFormat,
1215 const C2StreamInitDataInfo::output *initData) {
1216 if ((work->input.ordinal.frameIndex - mFirstValidFrameIndex.load()).peek() < 0) {
1217 // Discard frames from previous generation.
1218 ALOGD("[%s] Discard frames from previous generation.", mName);
1219 return false;
1220 }
1221
Wonsik Kim524b0582019-03-12 11:28:57 -07001222 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001223 || !work->worklets.front()
Wonsik Kim524b0582019-03-12 11:28:57 -07001224 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE))) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001225 mPipelineWatcher.lock()->onWorkDone(work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001226 }
1227
1228 if (work->result == C2_NOT_FOUND) {
1229 ALOGD("[%s] flushed work; ignored.", mName);
1230 return true;
1231 }
1232
1233 if (work->result != C2_OK) {
1234 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1235 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1236 return false;
1237 }
1238
1239 // NOTE: MediaCodec usage supposedly have only one worklet
1240 if (work->worklets.size() != 1u) {
1241 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1242 mName, work->worklets.size());
1243 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1244 return false;
1245 }
1246
1247 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1248
1249 std::shared_ptr<C2Buffer> buffer;
1250 // NOTE: MediaCodec usage supposedly have only one output stream.
1251 if (worklet->output.buffers.size() > 1u) {
1252 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1253 mName, worklet->output.buffers.size());
1254 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1255 return false;
1256 } else if (worklet->output.buffers.size() == 1u) {
1257 buffer = worklet->output.buffers[0];
1258 if (!buffer) {
1259 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1260 }
1261 }
1262
1263 while (!worklet->output.configUpdate.empty()) {
1264 std::unique_ptr<C2Param> param;
1265 worklet->output.configUpdate.back().swap(param);
1266 worklet->output.configUpdate.pop_back();
1267 switch (param->coreIndex().coreIndex()) {
1268 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1269 C2PortReorderBufferDepthTuning::output reorderDepth;
1270 if (reorderDepth.updateFrom(*param)) {
1271 mReorderStash.lock()->setDepth(reorderDepth.value);
1272 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1273 mName, reorderDepth.value);
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001274 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1275 output->maxDequeueBuffers = mNumOutputSlots + reorderDepth.value + kRenderingDepth;
1276 if (output->surface) {
1277 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1278 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001279 } else {
1280 ALOGD("[%s] onWorkDone: failed to read reorder depth", mName);
1281 }
1282 break;
1283 }
1284 case C2PortReorderKeySetting::CORE_INDEX: {
1285 C2PortReorderKeySetting::output reorderKey;
1286 if (reorderKey.updateFrom(*param)) {
1287 mReorderStash.lock()->setKey(reorderKey.value);
1288 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1289 mName, reorderKey.value);
1290 } else {
1291 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1292 }
1293 break;
1294 }
1295 default:
1296 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1297 mName, param->index());
1298 break;
1299 }
1300 }
1301
1302 if (outputFormat != nullptr) {
1303 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1304 ALOGD("[%s] onWorkDone: output format changed to %s",
1305 mName, outputFormat->debugString().c_str());
1306 (*buffers)->setFormat(outputFormat);
1307
1308 AString mediaType;
1309 if (outputFormat->findString(KEY_MIME, &mediaType)
1310 && mediaType == MIMETYPE_AUDIO_RAW) {
1311 int32_t channelCount;
1312 int32_t sampleRate;
1313 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1314 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1315 (*buffers)->updateSkipCutBuffer(sampleRate, channelCount);
1316 }
1317 }
1318 }
1319
1320 int32_t flags = 0;
1321 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1322 flags |= MediaCodec::BUFFER_FLAG_EOS;
1323 ALOGV("[%s] onWorkDone: output EOS", mName);
1324 }
1325
1326 sp<MediaCodecBuffer> outBuffer;
1327 size_t index;
1328
1329 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1330 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1331 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1332 // shall correspond to the client input timesamp (in customOrdinal). By using the
1333 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1334 // produces multiple output.
1335 c2_cntr64_t timestamp =
1336 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1337 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001338 if (mInputSurface != nullptr) {
1339 // When using input surface we need to restore the original input timestamp.
1340 timestamp = work->input.ordinal.customOrdinal;
1341 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001342 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1343 mName,
1344 work->input.ordinal.customOrdinal.peekll(),
1345 work->input.ordinal.timestamp.peekll(),
1346 worklet->output.ordinal.timestamp.peekll(),
1347 timestamp.peekll());
1348
1349 if (initData != nullptr) {
1350 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1351 if ((*buffers)->registerCsd(initData, &index, &outBuffer) == OK) {
1352 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1353 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1354 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1355
1356 buffers.unlock();
1357 mCallback->onOutputBufferAvailable(index, outBuffer);
1358 buffers.lock();
1359 } else {
1360 ALOGD("[%s] onWorkDone: unable to register csd", mName);
1361 buffers.unlock();
1362 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1363 buffers.lock();
1364 return false;
1365 }
1366 }
1367
1368 if (!buffer && !flags) {
1369 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1370 mName, work->input.ordinal.frameIndex.peekull());
1371 return true;
1372 }
1373
1374 if (buffer) {
1375 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1376 // TODO: properly translate these to metadata
1377 switch (info->coreIndex().coreIndex()) {
1378 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001379 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001380 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1381 }
1382 break;
1383 default:
1384 break;
1385 }
1386 }
1387 }
1388
1389 {
1390 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1391 reorder->emplace(buffer, timestamp.peek(), flags, worklet->output.ordinal);
1392 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
1393 // Flush reorder stash
1394 reorder->setDepth(0);
1395 }
1396 }
1397 sendOutputBuffers();
1398 return true;
1399}
1400
1401void CCodecBufferChannel::sendOutputBuffers() {
1402 ReorderStash::Entry entry;
1403 sp<MediaCodecBuffer> outBuffer;
1404 size_t index;
1405
1406 while (true) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001407 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1408 if (!reorder->hasPending()) {
1409 break;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001410 }
Wonsik Kim38ad3412019-02-01 15:13:23 -08001411 if (!reorder->pop(&entry)) {
1412 break;
1413 }
1414
Pawin Vongmasa36653902018-11-15 00:10:25 -08001415 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1416 status_t err = (*buffers)->registerBuffer(entry.buffer, &index, &outBuffer);
1417 if (err != OK) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001418 bool outputBuffersChanged = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001419 if (err != WOULD_BLOCK) {
Wonsik Kim186fdbf2019-01-29 13:30:01 -08001420 if (!(*buffers)->isArrayMode()) {
1421 *buffers = (*buffers)->toArrayMode(mNumOutputSlots);
1422 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001423 OutputBuffersArray *array = (OutputBuffersArray *)buffers->get();
1424 array->realloc(entry.buffer);
Wonsik Kim38ad3412019-02-01 15:13:23 -08001425 outputBuffersChanged = true;
1426 }
1427 ALOGV("[%s] sendOutputBuffers: unable to register output buffer", mName);
1428 reorder->defer(entry);
1429
1430 buffers.unlock();
1431 reorder.unlock();
1432
1433 if (outputBuffersChanged) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001434 mCCodecCallback->onOutputBuffersChanged();
1435 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001436 return;
1437 }
1438 buffers.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08001439 reorder.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001440
1441 outBuffer->meta()->setInt64("timeUs", entry.timestamp);
1442 outBuffer->meta()->setInt32("flags", entry.flags);
Wonsik Kim66427432019-03-21 15:06:22 -07001443 ALOGV("[%s] sendOutputBuffers: out buffer index = %zu [%p] => %p + %zu (%lld)",
1444 mName, index, outBuffer.get(), outBuffer->data(), outBuffer->size(),
1445 (long long)entry.timestamp);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001446 mCallback->onOutputBufferAvailable(index, outBuffer);
1447 }
1448}
1449
1450status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1451 static std::atomic_uint32_t surfaceGeneration{0};
1452 uint32_t generation = (getpid() << 10) |
1453 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1454 & ((1 << 10) - 1));
1455
1456 sp<IGraphicBufferProducer> producer;
1457 if (newSurface) {
1458 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001459 producer = newSurface->getIGraphicBufferProducer();
1460 producer->setGenerationNumber(generation);
1461 } else {
1462 ALOGE("[%s] setting output surface to null", mName);
1463 return INVALID_OPERATION;
1464 }
1465
1466 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1467 C2BlockPool::local_id_t outputPoolId;
1468 {
1469 Mutexed<BlockPools>::Locked pools(mBlockPools);
1470 outputPoolId = pools->outputPoolId;
1471 outputPoolIntf = pools->outputPoolIntf;
1472 }
1473
1474 if (outputPoolIntf) {
1475 if (mComponent->setOutputSurface(
1476 outputPoolId,
1477 producer,
1478 generation) != C2_OK) {
1479 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1480 return INVALID_OPERATION;
1481 }
1482 }
1483
1484 {
1485 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001486 newSurface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001487 output->surface = newSurface;
1488 output->generation = generation;
1489 }
1490
1491 return OK;
1492}
1493
Wonsik Kimab34ed62019-01-31 15:28:46 -08001494PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001495 // When client pushed EOS, we want all the work to be done quickly.
1496 // Otherwise, component may have stalled work due to input starvation up to
1497 // the sum of the delay in the pipeline.
1498 size_t n = mInputMetEos ? 0 : mDelay;
1499 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001500}
1501
Pawin Vongmasa36653902018-11-15 00:10:25 -08001502void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1503 mMetaMode = mode;
1504}
1505
1506status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1507 // C2_OK is always translated to OK.
1508 if (c2s == C2_OK) {
1509 return OK;
1510 }
1511
1512 // Operation-dependent translation
1513 // TODO: Add as necessary
1514 switch (c2op) {
1515 case C2_OPERATION_Component_start:
1516 switch (c2s) {
1517 case C2_NO_MEMORY:
1518 return NO_MEMORY;
1519 default:
1520 return UNKNOWN_ERROR;
1521 }
1522 default:
1523 break;
1524 }
1525
1526 // Backup operation-agnostic translation
1527 switch (c2s) {
1528 case C2_BAD_INDEX:
1529 return BAD_INDEX;
1530 case C2_BAD_VALUE:
1531 return BAD_VALUE;
1532 case C2_BLOCKING:
1533 return WOULD_BLOCK;
1534 case C2_DUPLICATE:
1535 return ALREADY_EXISTS;
1536 case C2_NO_INIT:
1537 return NO_INIT;
1538 case C2_NO_MEMORY:
1539 return NO_MEMORY;
1540 case C2_NOT_FOUND:
1541 return NAME_NOT_FOUND;
1542 case C2_TIMED_OUT:
1543 return TIMED_OUT;
1544 case C2_BAD_STATE:
1545 case C2_CANCELED:
1546 case C2_CANNOT_DO:
1547 case C2_CORRUPTED:
1548 case C2_OMITTED:
1549 case C2_REFUSED:
1550 return UNKNOWN_ERROR;
1551 default:
1552 return -static_cast<status_t>(c2s);
1553 }
1554}
1555
1556} // namespace android