blob: 90265dee3daf82f13123ef79e9f4e05488316752 [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
Sungtak Leeab6f2f32019-02-15 14:43:51 -080064// This is for keeping IGBP's buffer dropping logic in legacy mode other
65// than making it non-blocking. Do not change this value.
66const static size_t kDequeueTimeoutNs = 0;
67
Pawin Vongmasa36653902018-11-15 00:10:25 -080068} // namespace
69
70CCodecBufferChannel::QueueGuard::QueueGuard(
71 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
72 Mutex::Autolock l(mSync.mGuardLock);
73 // At this point it's guaranteed that mSync is not under state transition,
74 // as we are holding its mutex.
75
76 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
77 if (count->value == -1) {
78 mRunning = false;
79 } else {
80 ++count->value;
81 mRunning = true;
82 }
83}
84
85CCodecBufferChannel::QueueGuard::~QueueGuard() {
86 if (mRunning) {
87 // We are not holding mGuardLock at this point so that QueueSync::stop() can
88 // keep holding the lock until mCount reaches zero.
89 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
90 --count->value;
91 count->cond.broadcast();
92 }
93}
94
95void CCodecBufferChannel::QueueSync::start() {
96 Mutex::Autolock l(mGuardLock);
97 // If stopped, it goes to running state; otherwise no-op.
98 Mutexed<Counter>::Locked count(mCount);
99 if (count->value == -1) {
100 count->value = 0;
101 }
102}
103
104void CCodecBufferChannel::QueueSync::stop() {
105 Mutex::Autolock l(mGuardLock);
106 Mutexed<Counter>::Locked count(mCount);
107 if (count->value == -1) {
108 // no-op
109 return;
110 }
111 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
112 // mCount can only decrement. In other words, threads that acquired the lock
113 // are allowed to finish execution but additional threads trying to acquire
114 // the lock at this point will block, and then get QueueGuard at STOPPED
115 // state.
116 while (count->value != 0) {
117 count.waitForCondition(count->cond);
118 }
119 count->value = -1;
120}
121
Pawin Vongmasa36653902018-11-15 00:10:25 -0800122// CCodecBufferChannel::ReorderStash
123
124CCodecBufferChannel::ReorderStash::ReorderStash() {
125 clear();
126}
127
128void CCodecBufferChannel::ReorderStash::clear() {
129 mPending.clear();
130 mStash.clear();
131 mDepth = 0;
132 mKey = C2Config::ORDINAL;
133}
134
Wonsik Kim6897f222019-01-30 13:29:24 -0800135void CCodecBufferChannel::ReorderStash::flush() {
136 mPending.clear();
137 mStash.clear();
138}
139
Pawin Vongmasa36653902018-11-15 00:10:25 -0800140void CCodecBufferChannel::ReorderStash::setDepth(uint32_t depth) {
141 mPending.splice(mPending.end(), mStash);
142 mDepth = depth;
143}
Wonsik Kim66427432019-03-21 15:06:22 -0700144
Pawin Vongmasa36653902018-11-15 00:10:25 -0800145void CCodecBufferChannel::ReorderStash::setKey(C2Config::ordinal_key_t key) {
146 mPending.splice(mPending.end(), mStash);
147 mKey = key;
148}
149
150bool CCodecBufferChannel::ReorderStash::pop(Entry *entry) {
151 if (mPending.empty()) {
152 return false;
153 }
154 entry->buffer = mPending.front().buffer;
155 entry->timestamp = mPending.front().timestamp;
156 entry->flags = mPending.front().flags;
157 entry->ordinal = mPending.front().ordinal;
158 mPending.pop_front();
159 return true;
160}
161
162void CCodecBufferChannel::ReorderStash::emplace(
163 const std::shared_ptr<C2Buffer> &buffer,
164 int64_t timestamp,
165 int32_t flags,
166 const C2WorkOrdinalStruct &ordinal) {
Wonsik Kim66427432019-03-21 15:06:22 -0700167 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
168 if (!buffer && eos) {
169 // TRICKY: we may be violating ordering of the stash here. Because we
170 // don't expect any more emplace() calls after this, the ordering should
171 // not matter.
172 mStash.emplace_back(buffer, timestamp, flags, ordinal);
173 } else {
174 flags = flags & ~MediaCodec::BUFFER_FLAG_EOS;
175 auto it = mStash.begin();
176 for (; it != mStash.end(); ++it) {
177 if (less(ordinal, it->ordinal)) {
178 break;
179 }
180 }
181 mStash.emplace(it, buffer, timestamp, flags, ordinal);
182 if (eos) {
183 mStash.back().flags = mStash.back().flags | MediaCodec::BUFFER_FLAG_EOS;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800184 }
185 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800186 while (!mStash.empty() && mStash.size() > mDepth) {
187 mPending.push_back(mStash.front());
188 mStash.pop_front();
189 }
190}
191
192void CCodecBufferChannel::ReorderStash::defer(
193 const CCodecBufferChannel::ReorderStash::Entry &entry) {
194 mPending.push_front(entry);
195}
196
197bool CCodecBufferChannel::ReorderStash::hasPending() const {
198 return !mPending.empty();
199}
200
201bool CCodecBufferChannel::ReorderStash::less(
202 const C2WorkOrdinalStruct &o1, const C2WorkOrdinalStruct &o2) {
203 switch (mKey) {
204 case C2Config::ORDINAL: return o1.frameIndex < o2.frameIndex;
205 case C2Config::TIMESTAMP: return o1.timestamp < o2.timestamp;
206 case C2Config::CUSTOM: return o1.customOrdinal < o2.customOrdinal;
207 default:
208 ALOGD("Unrecognized key; default to timestamp");
209 return o1.frameIndex < o2.frameIndex;
210 }
211}
212
213// CCodecBufferChannel
214
215CCodecBufferChannel::CCodecBufferChannel(
216 const std::shared_ptr<CCodecCallback> &callback)
217 : mHeapSeqNum(-1),
218 mCCodecCallback(callback),
Wonsik Kim078b58e2019-01-09 15:08:06 -0800219 mNumInputSlots(kSmoothnessFactor),
220 mNumOutputSlots(kSmoothnessFactor),
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800221 mDelay(0),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800222 mFrameIndex(0u),
223 mFirstValidFrameIndex(0u),
224 mMetaMode(MODE_NONE),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800225 mInputMetEos(false) {
Wonsik Kimf5e5c832019-02-21 11:36:05 -0800226 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800227 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
228 buffers->reset(new DummyInputBuffers(""));
229}
230
231CCodecBufferChannel::~CCodecBufferChannel() {
232 if (mCrypto != nullptr && mDealer != nullptr && mHeapSeqNum >= 0) {
233 mCrypto->unsetHeap(mHeapSeqNum);
234 }
235}
236
237void CCodecBufferChannel::setComponent(
238 const std::shared_ptr<Codec2Client::Component> &component) {
239 mComponent = component;
240 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
241 mName = mComponentName.c_str();
242}
243
244status_t CCodecBufferChannel::setInputSurface(
245 const std::shared_ptr<InputSurfaceWrapper> &surface) {
246 ALOGV("[%s] setInputSurface", mName);
247 mInputSurface = surface;
248 return mInputSurface->connect(mComponent);
249}
250
251status_t CCodecBufferChannel::signalEndOfInputStream() {
252 if (mInputSurface == nullptr) {
253 return INVALID_OPERATION;
254 }
255 return mInputSurface->signalEndOfInputStream();
256}
257
258status_t CCodecBufferChannel::queueInputBufferInternal(const sp<MediaCodecBuffer> &buffer) {
259 int64_t timeUs;
260 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
261
262 if (mInputMetEos) {
263 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
264 return OK;
265 }
266
267 int32_t flags = 0;
268 int32_t tmp = 0;
269 bool eos = false;
270 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
271 eos = true;
272 mInputMetEos = true;
273 ALOGV("[%s] input EOS", mName);
274 }
275 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
276 flags |= C2FrameData::FLAG_CODEC_CONFIG;
277 }
278 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
279 std::unique_ptr<C2Work> work(new C2Work);
280 work->input.ordinal.timestamp = timeUs;
281 work->input.ordinal.frameIndex = mFrameIndex++;
282 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
283 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
284 // Keep client timestamp in customOrdinal
285 work->input.ordinal.customOrdinal = timeUs;
286 work->input.buffers.clear();
287
Wonsik Kimab34ed62019-01-31 15:28:46 -0800288 uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
289 std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
290
Pawin Vongmasa36653902018-11-15 00:10:25 -0800291 if (buffer->size() > 0u) {
292 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
293 std::shared_ptr<C2Buffer> c2buffer;
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800294 if (!(*buffers)->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800295 return -ENOENT;
296 }
297 work->input.buffers.push_back(c2buffer);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800298 queuedBuffers.push_back(c2buffer);
299 } else if (eos) {
300 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800301 }
302 work->input.flags = (C2FrameData::flags_t)flags;
303 // TODO: fill info's
304
305 work->input.configUpdate = std::move(mParamsToBeSet);
306 work->worklets.clear();
307 work->worklets.emplace_back(new C2Worklet);
308
309 std::list<std::unique_ptr<C2Work>> items;
310 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800311 mPipelineWatcher.lock()->onWorkQueued(
312 queuedFrameIndex,
313 std::move(queuedBuffers),
314 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800315 c2_status_t err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800316 if (err != C2_OK) {
317 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
318 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800319
320 if (err == C2_OK && eos && buffer->size() > 0u) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800321 work.reset(new C2Work);
322 work->input.ordinal.timestamp = timeUs;
323 work->input.ordinal.frameIndex = mFrameIndex++;
324 // WORKAROUND: keep client timestamp in customOrdinal
325 work->input.ordinal.customOrdinal = timeUs;
326 work->input.buffers.clear();
327 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800328 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800329
Wonsik Kimab34ed62019-01-31 15:28:46 -0800330 queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
331 queuedBuffers.clear();
332
Pawin Vongmasa36653902018-11-15 00:10:25 -0800333 items.clear();
334 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800335
336 mPipelineWatcher.lock()->onWorkQueued(
337 queuedFrameIndex,
338 std::move(queuedBuffers),
339 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800340 err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800341 if (err != C2_OK) {
342 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
343 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800344 }
345 if (err == C2_OK) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800346 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
347 bool released = (*buffers)->releaseBuffer(buffer, nullptr, true);
348 ALOGV("[%s] queueInputBuffer: buffer %sreleased", mName, released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800349 }
350
351 feedInputBufferIfAvailableInternal();
352 return err;
353}
354
355status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
356 QueueGuard guard(mSync);
357 if (!guard.isRunning()) {
358 ALOGD("[%s] setParameters is only supported in the running state.", mName);
359 return -ENOSYS;
360 }
361 mParamsToBeSet.insert(mParamsToBeSet.end(),
362 std::make_move_iterator(params.begin()),
363 std::make_move_iterator(params.end()));
364 params.clear();
365 return OK;
366}
367
368status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
369 QueueGuard guard(mSync);
370 if (!guard.isRunning()) {
371 ALOGD("[%s] No more buffers should be queued at current state.", mName);
372 return -ENOSYS;
373 }
374 return queueInputBufferInternal(buffer);
375}
376
377status_t CCodecBufferChannel::queueSecureInputBuffer(
378 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
379 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
380 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
381 AString *errorDetailMsg) {
382 QueueGuard guard(mSync);
383 if (!guard.isRunning()) {
384 ALOGD("[%s] No more buffers should be queued at current state.", mName);
385 return -ENOSYS;
386 }
387
388 if (!hasCryptoOrDescrambler()) {
389 return -ENOSYS;
390 }
391 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
392
393 ssize_t result = -1;
394 ssize_t codecDataOffset = 0;
395 if (mCrypto != nullptr) {
396 ICrypto::DestinationBuffer destination;
397 if (secure) {
398 destination.mType = ICrypto::kDestinationTypeNativeHandle;
399 destination.mHandle = encryptedBuffer->handle();
400 } else {
401 destination.mType = ICrypto::kDestinationTypeSharedMemory;
402 destination.mSharedMemory = mDecryptDestination;
403 }
404 ICrypto::SourceBuffer source;
405 encryptedBuffer->fillSourceBuffer(&source);
406 result = mCrypto->decrypt(
407 key, iv, mode, pattern, source, buffer->offset(),
408 subSamples, numSubSamples, destination, errorDetailMsg);
409 if (result < 0) {
410 return result;
411 }
412 if (destination.mType == ICrypto::kDestinationTypeSharedMemory) {
413 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
414 }
415 } else {
416 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
417 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
418 hidl_vec<SubSample> hidlSubSamples;
419 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
420
421 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
422 encryptedBuffer->fillSourceBuffer(&srcBuffer);
423
424 DestinationBuffer dstBuffer;
425 if (secure) {
426 dstBuffer.type = BufferType::NATIVE_HANDLE;
427 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
428 } else {
429 dstBuffer.type = BufferType::SHARED_MEMORY;
430 dstBuffer.nonsecureMemory = srcBuffer;
431 }
432
433 CasStatus status = CasStatus::OK;
434 hidl_string detailedError;
435 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
436
437 if (key != nullptr) {
438 sctrl = (ScramblingControl)key[0];
439 // Adjust for the PES offset
440 codecDataOffset = key[2] | (key[3] << 8);
441 }
442
443 auto returnVoid = mDescrambler->descramble(
444 sctrl,
445 hidlSubSamples,
446 srcBuffer,
447 0,
448 dstBuffer,
449 0,
450 [&status, &result, &detailedError] (
451 CasStatus _status, uint32_t _bytesWritten,
452 const hidl_string& _detailedError) {
453 status = _status;
454 result = (ssize_t)_bytesWritten;
455 detailedError = _detailedError;
456 });
457
458 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
459 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
460 mName, returnVoid.description().c_str(), status, result);
461 return UNKNOWN_ERROR;
462 }
463
464 if (result < codecDataOffset) {
465 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
466 return BAD_VALUE;
467 }
468
469 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
470
471 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
472 encryptedBuffer->copyDecryptedContentFromMemory(result);
473 }
474 }
475
476 buffer->setRange(codecDataOffset, result - codecDataOffset);
477 return queueInputBufferInternal(buffer);
478}
479
480void CCodecBufferChannel::feedInputBufferIfAvailable() {
481 QueueGuard guard(mSync);
482 if (!guard.isRunning()) {
483 ALOGV("[%s] We're not running --- no input buffer reported", mName);
484 return;
485 }
486 feedInputBufferIfAvailableInternal();
487}
488
489void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800490 if (mInputMetEos ||
491 mReorderStash.lock()->hasPending() ||
492 mPipelineWatcher.lock()->pipelineFull()) {
493 return;
494 } else {
495 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
496 if ((*buffers)->numClientBuffers() >= mNumOutputSlots) {
497 return;
498 }
499 }
500 for (size_t i = 0; i < mNumInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800501 sp<MediaCodecBuffer> inBuffer;
502 size_t index;
503 {
504 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800505 if ((*buffers)->numClientBuffers() >= mNumInputSlots) {
506 return;
507 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800508 if (!(*buffers)->requestNewBuffer(&index, &inBuffer)) {
509 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800510 break;
511 }
512 }
513 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
514 mCallback->onInputBufferAvailable(index, inBuffer);
515 }
516}
517
518status_t CCodecBufferChannel::renderOutputBuffer(
519 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800520 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800521 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800522 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800523 {
524 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
525 if (*buffers) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800526 released = (*buffers)->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800527 }
528 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800529 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
530 // set to true.
531 sendOutputBuffers();
532 // input buffer feeding may have been gated by pending output buffers
533 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800534 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800535 if (released) {
536 ALOGD("[%s] The app is calling releaseOutputBuffer() with "
537 "timestamp or render=true with non-video buffers. Apps should "
538 "call releaseOutputBuffer() with render=false for those.",
539 mName);
540 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800541 return INVALID_OPERATION;
542 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800543
544#if 0
545 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
546 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
547 for (const std::shared_ptr<const C2Info> &info : infoParams) {
548 AString res;
549 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
550 if (ix) res.append(", ");
551 res.append(*((int32_t*)info.get() + (ix / 4)));
552 }
553 ALOGV(" [%s]", res.c_str());
554 }
555#endif
556 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
557 std::static_pointer_cast<const C2StreamRotationInfo::output>(
558 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
559 bool flip = rotation && (rotation->flip & 1);
560 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
561 uint32_t transform = 0;
562 switch (quarters) {
563 case 0: // no rotation
564 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
565 break;
566 case 1: // 90 degrees counter-clockwise
567 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
568 : HAL_TRANSFORM_ROT_270;
569 break;
570 case 2: // 180 degrees
571 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
572 break;
573 case 3: // 90 degrees clockwise
574 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
575 : HAL_TRANSFORM_ROT_90;
576 break;
577 }
578
579 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
580 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
581 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
582 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
583 if (surfaceScaling) {
584 videoScalingMode = surfaceScaling->value;
585 }
586
587 // Use dataspace from format as it has the default aspects already applied
588 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
589 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
590
591 // HDR static info
592 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
593 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
594 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
595
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800596 // HDR10 plus info
597 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
598 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
599 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
600
Pawin Vongmasa36653902018-11-15 00:10:25 -0800601 {
602 Mutexed<OutputSurface>::Locked output(mOutputSurface);
603 if (output->surface == nullptr) {
604 ALOGI("[%s] cannot render buffer without surface", mName);
605 return OK;
606 }
607 }
608
609 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
610 if (blocks.size() != 1u) {
611 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
612 return UNKNOWN_ERROR;
613 }
614 const C2ConstGraphicBlock &block = blocks.front();
615
616 // TODO: revisit this after C2Fence implementation.
617 android::IGraphicBufferProducer::QueueBufferInput qbi(
618 timestampNs,
619 false, // droppable
620 dataSpace,
621 Rect(blocks.front().crop().left,
622 blocks.front().crop().top,
623 blocks.front().crop().right(),
624 blocks.front().crop().bottom()),
625 videoScalingMode,
626 transform,
627 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800628 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800629 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800630 if (hdrStaticInfo) {
631 struct android_smpte2086_metadata smpte2086_meta = {
632 .displayPrimaryRed = {
633 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
634 },
635 .displayPrimaryGreen = {
636 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
637 },
638 .displayPrimaryBlue = {
639 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
640 },
641 .whitePoint = {
642 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
643 },
644 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
645 .minLuminance = hdrStaticInfo->mastering.minLuminance,
646 };
647
648 struct android_cta861_3_metadata cta861_meta = {
649 .maxContentLightLevel = hdrStaticInfo->maxCll,
650 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
651 };
652
653 hdr.validTypes = HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3;
654 hdr.smpte2086 = smpte2086_meta;
655 hdr.cta8613 = cta861_meta;
656 }
657 if (hdr10PlusInfo) {
658 hdr.validTypes |= HdrMetadata::HDR10PLUS;
659 hdr.hdr10plus.assign(
660 hdr10PlusInfo->m.value,
661 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
662 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800663 qbi.setHdrMetadata(hdr);
664 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800665 // we don't have dirty regions
666 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800667 android::IGraphicBufferProducer::QueueBufferOutput qbo;
668 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
669 if (result != OK) {
670 ALOGI("[%s] queueBuffer failed: %d", mName, result);
671 return result;
672 }
673 ALOGV("[%s] queue buffer successful", mName);
674
675 int64_t mediaTimeUs = 0;
676 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
677 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
678
679 return OK;
680}
681
682status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
683 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
684 bool released = false;
685 {
686 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800687 if (*buffers && (*buffers)->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800688 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800689 }
690 }
691 {
692 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
693 if (*buffers && (*buffers)->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800694 released = true;
695 }
696 }
697 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800698 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800699 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800700 } else {
701 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
702 }
703 return OK;
704}
705
706void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
707 array->clear();
708 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
709
710 if (!(*buffers)->isArrayMode()) {
Wonsik Kim078b58e2019-01-09 15:08:06 -0800711 *buffers = (*buffers)->toArrayMode(mNumInputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800712 }
713
714 (*buffers)->getArray(array);
715}
716
717void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
718 array->clear();
719 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
720
721 if (!(*buffers)->isArrayMode()) {
Wonsik Kim078b58e2019-01-09 15:08:06 -0800722 *buffers = (*buffers)->toArrayMode(mNumOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800723 }
724
725 (*buffers)->getArray(array);
726}
727
728status_t CCodecBufferChannel::start(
729 const sp<AMessage> &inputFormat, const sp<AMessage> &outputFormat) {
730 C2StreamBufferTypeSetting::input iStreamFormat(0u);
731 C2StreamBufferTypeSetting::output oStreamFormat(0u);
732 C2PortReorderBufferDepthTuning::output reorderDepth;
733 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800734 C2PortActualDelayTuning::input inputDelay(0);
735 C2PortActualDelayTuning::output outputDelay(0);
736 C2ActualPipelineDelayTuning pipelineDelay(0);
737
Pawin Vongmasa36653902018-11-15 00:10:25 -0800738 c2_status_t err = mComponent->query(
739 {
740 &iStreamFormat,
741 &oStreamFormat,
742 &reorderDepth,
743 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800744 &inputDelay,
745 &pipelineDelay,
746 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800747 },
748 {},
749 C2_DONT_BLOCK,
750 nullptr);
751 if (err == C2_BAD_INDEX) {
752 if (!iStreamFormat || !oStreamFormat) {
753 return UNKNOWN_ERROR;
754 }
755 } else if (err != C2_OK) {
756 return UNKNOWN_ERROR;
757 }
758
759 {
760 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
761 reorder->clear();
762 if (reorderDepth) {
763 reorder->setDepth(reorderDepth.value);
764 }
765 if (reorderKey) {
766 reorder->setKey(reorderKey.value);
767 }
768 }
Wonsik Kim078b58e2019-01-09 15:08:06 -0800769
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800770 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
771 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
772 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
773
774 mNumInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
775 mNumOutputSlots = outputDelayValue + kSmoothnessFactor;
776 mDelay = inputDelayValue + pipelineDelayValue + outputDelayValue;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800777
Pawin Vongmasa36653902018-11-15 00:10:25 -0800778 // TODO: get this from input format
779 bool secure = mComponent->getName().find(".secure") != std::string::npos;
780
781 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
782 int poolMask = property_get_int32(
783 "debug.stagefright.c2-poolmask",
784 1 << C2PlatformAllocatorStore::ION |
785 1 << C2PlatformAllocatorStore::BUFFERQUEUE);
786
787 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800788 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800789 std::shared_ptr<C2BlockPool> pool;
790 {
791 Mutexed<BlockPools>::Locked pools(mBlockPools);
792
793 // set default allocator ID.
794 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
795 : C2PlatformAllocatorStore::ION;
796
797 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
798 // from component, create the input block pool with given ID. Otherwise, use default IDs.
799 std::vector<std::unique_ptr<C2Param>> params;
800 err = mComponent->query({ },
801 { C2PortAllocatorsTuning::input::PARAM_TYPE },
802 C2_DONT_BLOCK,
803 &params);
804 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
805 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
806 mName, params.size(), asString(err), err);
807 } else if (err == C2_OK && params.size() == 1) {
808 C2PortAllocatorsTuning::input *inputAllocators =
809 C2PortAllocatorsTuning::input::From(params[0].get());
810 if (inputAllocators && inputAllocators->flexCount() > 0) {
811 std::shared_ptr<C2Allocator> allocator;
812 // verify allocator IDs and resolve default allocator
813 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
814 if (allocator) {
815 pools->inputAllocatorId = allocator->getId();
816 } else {
817 ALOGD("[%s] component requested invalid input allocator ID %u",
818 mName, inputAllocators->m.values[0]);
819 }
820 }
821 }
822
823 // TODO: use C2Component wrapper to associate this pool with ourselves
824 if ((poolMask >> pools->inputAllocatorId) & 1) {
825 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
826 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
827 mName, pools->inputAllocatorId,
828 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
829 asString(err), err);
830 } else {
831 err = C2_NOT_FOUND;
832 }
833 if (err != C2_OK) {
834 C2BlockPool::local_id_t inputPoolId =
835 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
836 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
837 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
838 mName, (unsigned long long)inputPoolId,
839 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
840 asString(err), err);
841 if (err != C2_OK) {
842 return NO_MEMORY;
843 }
844 }
845 pools->inputPool = pool;
846 }
847
Wonsik Kim51051262018-11-28 13:59:05 -0800848 bool forceArrayMode = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800849 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
850 if (graphic) {
851 if (mInputSurface) {
852 buffers->reset(new DummyInputBuffers(mName));
853 } else if (mMetaMode == MODE_ANW) {
854 buffers->reset(new GraphicMetadataInputBuffers(mName));
855 } else {
Wonsik Kim078b58e2019-01-09 15:08:06 -0800856 buffers->reset(new GraphicInputBuffers(mNumInputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800857 }
858 } else {
859 if (hasCryptoOrDescrambler()) {
860 int32_t capacity = kLinearBufferSize;
861 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
862 if ((size_t)capacity > kMaxLinearBufferSize) {
863 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
864 capacity = kMaxLinearBufferSize;
865 }
866 if (mDealer == nullptr) {
867 mDealer = new MemoryDealer(
868 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim078b58e2019-01-09 15:08:06 -0800869 * (mNumInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800870 "EncryptedLinearInputBuffers");
871 mDecryptDestination = mDealer->allocate((size_t)capacity);
872 }
873 if (mCrypto != nullptr && mHeapSeqNum < 0) {
874 mHeapSeqNum = mCrypto->setHeap(mDealer->getMemoryHeap());
875 } else {
876 mHeapSeqNum = -1;
877 }
878 buffers->reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -0800879 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
880 mNumInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -0800881 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800882 } else {
883 buffers->reset(new LinearInputBuffers(mName));
884 }
885 }
886 (*buffers)->setFormat(inputFormat);
887
888 if (err == C2_OK) {
889 (*buffers)->setPool(pool);
890 } else {
891 // TODO: error
892 }
Wonsik Kim51051262018-11-28 13:59:05 -0800893
894 if (forceArrayMode) {
Wonsik Kim078b58e2019-01-09 15:08:06 -0800895 *buffers = (*buffers)->toArrayMode(mNumInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -0800896 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800897 }
898
899 if (outputFormat != nullptr) {
900 sp<IGraphicBufferProducer> outputSurface;
901 uint32_t outputGeneration;
902 {
903 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Wonsik Kimf5e5c832019-02-21 11:36:05 -0800904 output->maxDequeueBuffers = mNumOutputSlots + reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800905 outputSurface = output->surface ?
906 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -0800907 if (outputSurface) {
908 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
909 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800910 outputGeneration = output->generation;
911 }
912
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800913 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800914 C2BlockPool::local_id_t outputPoolId_;
915
916 {
917 Mutexed<BlockPools>::Locked pools(mBlockPools);
918
919 // set default allocator ID.
920 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
921 : C2PlatformAllocatorStore::ION;
922
923 // query C2PortAllocatorsTuning::output from component, or use default allocator if
924 // unsuccessful.
925 std::vector<std::unique_ptr<C2Param>> params;
926 err = mComponent->query({ },
927 { C2PortAllocatorsTuning::output::PARAM_TYPE },
928 C2_DONT_BLOCK,
929 &params);
930 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
931 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
932 mName, params.size(), asString(err), err);
933 } else if (err == C2_OK && params.size() == 1) {
934 C2PortAllocatorsTuning::output *outputAllocators =
935 C2PortAllocatorsTuning::output::From(params[0].get());
936 if (outputAllocators && outputAllocators->flexCount() > 0) {
937 std::shared_ptr<C2Allocator> allocator;
938 // verify allocator IDs and resolve default allocator
939 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
940 if (allocator) {
941 pools->outputAllocatorId = allocator->getId();
942 } else {
943 ALOGD("[%s] component requested invalid output allocator ID %u",
944 mName, outputAllocators->m.values[0]);
945 }
946 }
947 }
948
949 // use bufferqueue if outputting to a surface.
950 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
951 // if unsuccessful.
952 if (outputSurface) {
953 params.clear();
954 err = mComponent->query({ },
955 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
956 C2_DONT_BLOCK,
957 &params);
958 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
959 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
960 mName, params.size(), asString(err), err);
961 } else if (err == C2_OK && params.size() == 1) {
962 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
963 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
964 if (surfaceAllocator) {
965 std::shared_ptr<C2Allocator> allocator;
966 // verify allocator IDs and resolve default allocator
967 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
968 if (allocator) {
969 pools->outputAllocatorId = allocator->getId();
970 } else {
971 ALOGD("[%s] component requested invalid surface output allocator ID %u",
972 mName, surfaceAllocator->value);
973 err = C2_BAD_VALUE;
974 }
975 }
976 }
977 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
978 && err != C2_OK
979 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
980 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
981 }
982 }
983
984 if ((poolMask >> pools->outputAllocatorId) & 1) {
985 err = mComponent->createBlockPool(
986 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
987 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
988 mName, pools->outputAllocatorId,
989 (unsigned long long)pools->outputPoolId,
990 asString(err));
991 } else {
992 err = C2_NOT_FOUND;
993 }
994 if (err != C2_OK) {
995 // use basic pool instead
996 pools->outputPoolId =
997 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
998 }
999
1000 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1001 // component.
1002 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1003 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1004
1005 std::vector<std::unique_ptr<C2SettingResult>> failures;
1006 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1007 ALOGD("[%s] Configured output block pool ids %llu => %s",
1008 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1009 outputPoolId_ = pools->outputPoolId;
1010 }
1011
1012 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1013
1014 if (graphic) {
1015 if (outputSurface) {
1016 buffers->reset(new GraphicOutputBuffers(mName));
1017 } else {
Wonsik Kim078b58e2019-01-09 15:08:06 -08001018 buffers->reset(new RawGraphicOutputBuffers(mNumOutputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001019 }
1020 } else {
1021 buffers->reset(new LinearOutputBuffers(mName));
1022 }
1023 (*buffers)->setFormat(outputFormat->dup());
1024
1025
1026 // Try to set output surface to created block pool if given.
1027 if (outputSurface) {
1028 mComponent->setOutputSurface(
1029 outputPoolId_,
1030 outputSurface,
1031 outputGeneration);
1032 }
1033
1034 if (oStreamFormat.value == C2BufferData::LINEAR
1035 && mComponentName.find("c2.qti.") == std::string::npos) {
1036 // WORKAROUND: if we're using early CSD workaround we convert to
1037 // array mode, to appease apps assuming the output
1038 // buffers to be of the same size.
Wonsik Kim078b58e2019-01-09 15:08:06 -08001039 (*buffers) = (*buffers)->toArrayMode(mNumOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001040
1041 int32_t channelCount;
1042 int32_t sampleRate;
1043 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1044 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1045 int32_t delay = 0;
1046 int32_t padding = 0;;
1047 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1048 delay = 0;
1049 }
1050 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1051 padding = 0;
1052 }
1053 if (delay || padding) {
1054 // We need write access to the buffers, and we're already in
1055 // array mode.
1056 (*buffers)->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
1057 }
1058 }
1059 }
1060 }
1061
1062 // Set up pipeline control. This has to be done after mInputBuffers and
1063 // mOutputBuffers are initialized to make sure that lingering callbacks
1064 // about buffers from the previous generation do not interfere with the
1065 // newly initialized pipeline capacity.
1066
Wonsik Kimab34ed62019-01-31 15:28:46 -08001067 {
1068 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001069 watcher->inputDelay(inputDelayValue)
1070 .pipelineDelay(pipelineDelayValue)
1071 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001072 .smoothnessFactor(kSmoothnessFactor);
1073 watcher->flush();
1074 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001075
1076 mInputMetEos = false;
1077 mSync.start();
1078 return OK;
1079}
1080
1081status_t CCodecBufferChannel::requestInitialInputBuffers() {
1082 if (mInputSurface) {
1083 return OK;
1084 }
1085
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001086 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001087 c2_status_t err = mComponent->query({ &oStreamFormat }, {}, C2_DONT_BLOCK, nullptr);
1088 if (err != C2_OK) {
1089 return UNKNOWN_ERROR;
1090 }
1091 std::vector<sp<MediaCodecBuffer>> toBeQueued;
1092 // TODO: use proper buffer depth instead of this random value
Wonsik Kim078b58e2019-01-09 15:08:06 -08001093 for (size_t i = 0; i < mNumInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001094 size_t index;
1095 sp<MediaCodecBuffer> buffer;
1096 {
1097 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1098 if (!(*buffers)->requestNewBuffer(&index, &buffer)) {
1099 if (i == 0) {
1100 ALOGW("[%s] start: cannot allocate memory at all", mName);
1101 return NO_MEMORY;
1102 } else {
1103 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
1104 mName, i);
1105 }
1106 break;
1107 }
1108 }
1109 if (buffer) {
1110 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1111 ALOGV("[%s] input buffer %zu available", mName, index);
1112 bool post = true;
1113 if (!configs->empty()) {
1114 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001115 configs->pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001116 if (buffer->capacity() >= config->size()) {
1117 memcpy(buffer->base(), config->data(), config->size());
1118 buffer->setRange(0, config->size());
1119 buffer->meta()->clear();
1120 buffer->meta()->setInt64("timeUs", 0);
1121 buffer->meta()->setInt32("csd", 1);
1122 post = false;
1123 } else {
1124 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
1125 mName, buffer->capacity(), config->size());
1126 }
1127 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
1128 && mComponentName.find("c2.qti.") == std::string::npos) {
1129 // WORKAROUND: Some apps expect CSD available without queueing
1130 // any input. Queue an empty buffer to get the CSD.
1131 buffer->setRange(0, 0);
1132 buffer->meta()->clear();
1133 buffer->meta()->setInt64("timeUs", 0);
1134 post = false;
1135 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001136 if (post) {
1137 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001138 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001139 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001140 }
1141 }
1142 }
1143 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
1144 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001145 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001146 }
1147 }
1148 return OK;
1149}
1150
1151void CCodecBufferChannel::stop() {
1152 mSync.stop();
1153 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1154 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001155 mInputSurface.reset();
1156 }
1157}
1158
1159void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1160 ALOGV("[%s] flush", mName);
1161 {
1162 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1163 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1164 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1165 continue;
1166 }
1167 if (work->input.buffers.empty()
1168 || work->input.buffers.front()->data().linearBlocks().empty()) {
1169 ALOGD("[%s] no linear codec config data found", mName);
1170 continue;
1171 }
1172 C2ReadView view =
1173 work->input.buffers.front()->data().linearBlocks().front().map().get();
1174 if (view.error() != C2_OK) {
1175 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1176 continue;
1177 }
1178 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1179 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1180 }
1181 }
1182 {
1183 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1184 (*buffers)->flush();
1185 }
1186 {
1187 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1188 (*buffers)->flush(flushedWork);
1189 }
Wonsik Kim6897f222019-01-30 13:29:24 -08001190 mReorderStash.lock()->flush();
Wonsik Kimab34ed62019-01-31 15:28:46 -08001191 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001192}
1193
1194void CCodecBufferChannel::onWorkDone(
1195 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001196 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001197 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001198 feedInputBufferIfAvailable();
1199 }
1200}
1201
1202void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001203 uint64_t frameIndex, size_t arrayIndex) {
1204 std::shared_ptr<C2Buffer> buffer =
1205 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001206 bool newInputSlotAvailable;
1207 {
1208 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1209 newInputSlotAvailable = (*buffers)->expireComponentBuffer(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001210 }
1211 if (newInputSlotAvailable) {
1212 feedInputBufferIfAvailable();
1213 }
1214}
1215
1216bool CCodecBufferChannel::handleWork(
1217 std::unique_ptr<C2Work> work,
1218 const sp<AMessage> &outputFormat,
1219 const C2StreamInitDataInfo::output *initData) {
1220 if ((work->input.ordinal.frameIndex - mFirstValidFrameIndex.load()).peek() < 0) {
1221 // Discard frames from previous generation.
1222 ALOGD("[%s] Discard frames from previous generation.", mName);
1223 return false;
1224 }
1225
Wonsik Kim524b0582019-03-12 11:28:57 -07001226 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001227 || !work->worklets.front()
Wonsik Kim524b0582019-03-12 11:28:57 -07001228 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE))) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001229 mPipelineWatcher.lock()->onWorkDone(work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001230 }
1231
1232 if (work->result == C2_NOT_FOUND) {
1233 ALOGD("[%s] flushed work; ignored.", mName);
1234 return true;
1235 }
1236
1237 if (work->result != C2_OK) {
1238 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1239 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1240 return false;
1241 }
1242
1243 // NOTE: MediaCodec usage supposedly have only one worklet
1244 if (work->worklets.size() != 1u) {
1245 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1246 mName, work->worklets.size());
1247 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1248 return false;
1249 }
1250
1251 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1252
1253 std::shared_ptr<C2Buffer> buffer;
1254 // NOTE: MediaCodec usage supposedly have only one output stream.
1255 if (worklet->output.buffers.size() > 1u) {
1256 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1257 mName, worklet->output.buffers.size());
1258 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1259 return false;
1260 } else if (worklet->output.buffers.size() == 1u) {
1261 buffer = worklet->output.buffers[0];
1262 if (!buffer) {
1263 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1264 }
1265 }
1266
1267 while (!worklet->output.configUpdate.empty()) {
1268 std::unique_ptr<C2Param> param;
1269 worklet->output.configUpdate.back().swap(param);
1270 worklet->output.configUpdate.pop_back();
1271 switch (param->coreIndex().coreIndex()) {
1272 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1273 C2PortReorderBufferDepthTuning::output reorderDepth;
1274 if (reorderDepth.updateFrom(*param)) {
1275 mReorderStash.lock()->setDepth(reorderDepth.value);
1276 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1277 mName, reorderDepth.value);
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001278 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1279 output->maxDequeueBuffers = mNumOutputSlots + reorderDepth.value + kRenderingDepth;
1280 if (output->surface) {
1281 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1282 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001283 } else {
1284 ALOGD("[%s] onWorkDone: failed to read reorder depth", mName);
1285 }
1286 break;
1287 }
1288 case C2PortReorderKeySetting::CORE_INDEX: {
1289 C2PortReorderKeySetting::output reorderKey;
1290 if (reorderKey.updateFrom(*param)) {
1291 mReorderStash.lock()->setKey(reorderKey.value);
1292 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1293 mName, reorderKey.value);
1294 } else {
1295 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1296 }
1297 break;
1298 }
1299 default:
1300 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1301 mName, param->index());
1302 break;
1303 }
1304 }
1305
1306 if (outputFormat != nullptr) {
1307 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1308 ALOGD("[%s] onWorkDone: output format changed to %s",
1309 mName, outputFormat->debugString().c_str());
1310 (*buffers)->setFormat(outputFormat);
1311
1312 AString mediaType;
1313 if (outputFormat->findString(KEY_MIME, &mediaType)
1314 && mediaType == MIMETYPE_AUDIO_RAW) {
1315 int32_t channelCount;
1316 int32_t sampleRate;
1317 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1318 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1319 (*buffers)->updateSkipCutBuffer(sampleRate, channelCount);
1320 }
1321 }
1322 }
1323
1324 int32_t flags = 0;
1325 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1326 flags |= MediaCodec::BUFFER_FLAG_EOS;
1327 ALOGV("[%s] onWorkDone: output EOS", mName);
1328 }
1329
1330 sp<MediaCodecBuffer> outBuffer;
1331 size_t index;
1332
1333 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1334 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1335 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1336 // shall correspond to the client input timesamp (in customOrdinal). By using the
1337 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1338 // produces multiple output.
1339 c2_cntr64_t timestamp =
1340 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1341 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001342 if (mInputSurface != nullptr) {
1343 // When using input surface we need to restore the original input timestamp.
1344 timestamp = work->input.ordinal.customOrdinal;
1345 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001346 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1347 mName,
1348 work->input.ordinal.customOrdinal.peekll(),
1349 work->input.ordinal.timestamp.peekll(),
1350 worklet->output.ordinal.timestamp.peekll(),
1351 timestamp.peekll());
1352
1353 if (initData != nullptr) {
1354 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1355 if ((*buffers)->registerCsd(initData, &index, &outBuffer) == OK) {
1356 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1357 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1358 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1359
1360 buffers.unlock();
1361 mCallback->onOutputBufferAvailable(index, outBuffer);
1362 buffers.lock();
1363 } else {
1364 ALOGD("[%s] onWorkDone: unable to register csd", mName);
1365 buffers.unlock();
1366 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1367 buffers.lock();
1368 return false;
1369 }
1370 }
1371
1372 if (!buffer && !flags) {
1373 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1374 mName, work->input.ordinal.frameIndex.peekull());
1375 return true;
1376 }
1377
1378 if (buffer) {
1379 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1380 // TODO: properly translate these to metadata
1381 switch (info->coreIndex().coreIndex()) {
1382 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001383 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001384 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1385 }
1386 break;
1387 default:
1388 break;
1389 }
1390 }
1391 }
1392
1393 {
1394 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1395 reorder->emplace(buffer, timestamp.peek(), flags, worklet->output.ordinal);
1396 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
1397 // Flush reorder stash
1398 reorder->setDepth(0);
1399 }
1400 }
1401 sendOutputBuffers();
1402 return true;
1403}
1404
1405void CCodecBufferChannel::sendOutputBuffers() {
1406 ReorderStash::Entry entry;
1407 sp<MediaCodecBuffer> outBuffer;
1408 size_t index;
1409
1410 while (true) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001411 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1412 if (!reorder->hasPending()) {
1413 break;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001414 }
Wonsik Kim38ad3412019-02-01 15:13:23 -08001415 if (!reorder->pop(&entry)) {
1416 break;
1417 }
1418
Pawin Vongmasa36653902018-11-15 00:10:25 -08001419 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1420 status_t err = (*buffers)->registerBuffer(entry.buffer, &index, &outBuffer);
1421 if (err != OK) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001422 bool outputBuffersChanged = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001423 if (err != WOULD_BLOCK) {
Wonsik Kim186fdbf2019-01-29 13:30:01 -08001424 if (!(*buffers)->isArrayMode()) {
1425 *buffers = (*buffers)->toArrayMode(mNumOutputSlots);
1426 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001427 OutputBuffersArray *array = (OutputBuffersArray *)buffers->get();
1428 array->realloc(entry.buffer);
Wonsik Kim38ad3412019-02-01 15:13:23 -08001429 outputBuffersChanged = true;
1430 }
1431 ALOGV("[%s] sendOutputBuffers: unable to register output buffer", mName);
1432 reorder->defer(entry);
1433
1434 buffers.unlock();
1435 reorder.unlock();
1436
1437 if (outputBuffersChanged) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001438 mCCodecCallback->onOutputBuffersChanged();
1439 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001440 return;
1441 }
1442 buffers.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08001443 reorder.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001444
1445 outBuffer->meta()->setInt64("timeUs", entry.timestamp);
1446 outBuffer->meta()->setInt32("flags", entry.flags);
Wonsik Kim66427432019-03-21 15:06:22 -07001447 ALOGV("[%s] sendOutputBuffers: out buffer index = %zu [%p] => %p + %zu (%lld)",
1448 mName, index, outBuffer.get(), outBuffer->data(), outBuffer->size(),
1449 (long long)entry.timestamp);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001450 mCallback->onOutputBufferAvailable(index, outBuffer);
1451 }
1452}
1453
1454status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1455 static std::atomic_uint32_t surfaceGeneration{0};
1456 uint32_t generation = (getpid() << 10) |
1457 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1458 & ((1 << 10) - 1));
1459
1460 sp<IGraphicBufferProducer> producer;
1461 if (newSurface) {
1462 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001463 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001464 producer = newSurface->getIGraphicBufferProducer();
1465 producer->setGenerationNumber(generation);
1466 } else {
1467 ALOGE("[%s] setting output surface to null", mName);
1468 return INVALID_OPERATION;
1469 }
1470
1471 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1472 C2BlockPool::local_id_t outputPoolId;
1473 {
1474 Mutexed<BlockPools>::Locked pools(mBlockPools);
1475 outputPoolId = pools->outputPoolId;
1476 outputPoolIntf = pools->outputPoolIntf;
1477 }
1478
1479 if (outputPoolIntf) {
1480 if (mComponent->setOutputSurface(
1481 outputPoolId,
1482 producer,
1483 generation) != C2_OK) {
1484 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1485 return INVALID_OPERATION;
1486 }
1487 }
1488
1489 {
1490 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001491 newSurface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001492 output->surface = newSurface;
1493 output->generation = generation;
1494 }
1495
1496 return OK;
1497}
1498
Wonsik Kimab34ed62019-01-31 15:28:46 -08001499PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001500 // When client pushed EOS, we want all the work to be done quickly.
1501 // Otherwise, component may have stalled work due to input starvation up to
1502 // the sum of the delay in the pipeline.
1503 size_t n = mInputMetEos ? 0 : mDelay;
1504 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001505}
1506
Pawin Vongmasa36653902018-11-15 00:10:25 -08001507void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1508 mMetaMode = mode;
1509}
1510
1511status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1512 // C2_OK is always translated to OK.
1513 if (c2s == C2_OK) {
1514 return OK;
1515 }
1516
1517 // Operation-dependent translation
1518 // TODO: Add as necessary
1519 switch (c2op) {
1520 case C2_OPERATION_Component_start:
1521 switch (c2s) {
1522 case C2_NO_MEMORY:
1523 return NO_MEMORY;
1524 default:
1525 return UNKNOWN_ERROR;
1526 }
1527 default:
1528 break;
1529 }
1530
1531 // Backup operation-agnostic translation
1532 switch (c2s) {
1533 case C2_BAD_INDEX:
1534 return BAD_INDEX;
1535 case C2_BAD_VALUE:
1536 return BAD_VALUE;
1537 case C2_BLOCKING:
1538 return WOULD_BLOCK;
1539 case C2_DUPLICATE:
1540 return ALREADY_EXISTS;
1541 case C2_NO_INIT:
1542 return NO_INIT;
1543 case C2_NO_MEMORY:
1544 return NO_MEMORY;
1545 case C2_NOT_FOUND:
1546 return NAME_NOT_FOUND;
1547 case C2_TIMED_OUT:
1548 return TIMED_OUT;
1549 case C2_BAD_STATE:
1550 case C2_CANCELED:
1551 case C2_CANNOT_DO:
1552 case C2_CORRUPTED:
1553 case C2_OMITTED:
1554 case C2_REFUSED:
1555 return UNKNOWN_ERROR;
1556 default:
1557 return -static_cast<status_t>(c2s);
1558 }
1559}
1560
1561} // namespace android