blob: 7669421ec4490f4845d6da83059c15e21c5f368b [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) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700536 std::call_once(mRenderWarningFlag, [this] {
537 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
538 "timestamp or render=true with non-video buffers. Apps should "
539 "call releaseOutputBuffer() with render=false for those.",
540 mName);
541 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800542 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800543 return INVALID_OPERATION;
544 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800545
546#if 0
547 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
548 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
549 for (const std::shared_ptr<const C2Info> &info : infoParams) {
550 AString res;
551 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
552 if (ix) res.append(", ");
553 res.append(*((int32_t*)info.get() + (ix / 4)));
554 }
555 ALOGV(" [%s]", res.c_str());
556 }
557#endif
558 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
559 std::static_pointer_cast<const C2StreamRotationInfo::output>(
560 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
561 bool flip = rotation && (rotation->flip & 1);
562 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
563 uint32_t transform = 0;
564 switch (quarters) {
565 case 0: // no rotation
566 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
567 break;
568 case 1: // 90 degrees counter-clockwise
569 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
570 : HAL_TRANSFORM_ROT_270;
571 break;
572 case 2: // 180 degrees
573 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
574 break;
575 case 3: // 90 degrees clockwise
576 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
577 : HAL_TRANSFORM_ROT_90;
578 break;
579 }
580
581 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
582 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
583 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
584 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
585 if (surfaceScaling) {
586 videoScalingMode = surfaceScaling->value;
587 }
588
589 // Use dataspace from format as it has the default aspects already applied
590 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
591 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
592
593 // HDR static info
594 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
595 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
596 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
597
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800598 // HDR10 plus info
599 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
600 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
601 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
602
Pawin Vongmasa36653902018-11-15 00:10:25 -0800603 {
604 Mutexed<OutputSurface>::Locked output(mOutputSurface);
605 if (output->surface == nullptr) {
606 ALOGI("[%s] cannot render buffer without surface", mName);
607 return OK;
608 }
609 }
610
611 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
612 if (blocks.size() != 1u) {
613 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
614 return UNKNOWN_ERROR;
615 }
616 const C2ConstGraphicBlock &block = blocks.front();
617
618 // TODO: revisit this after C2Fence implementation.
619 android::IGraphicBufferProducer::QueueBufferInput qbi(
620 timestampNs,
621 false, // droppable
622 dataSpace,
623 Rect(blocks.front().crop().left,
624 blocks.front().crop().top,
625 blocks.front().crop().right(),
626 blocks.front().crop().bottom()),
627 videoScalingMode,
628 transform,
629 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800630 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800631 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800632 if (hdrStaticInfo) {
633 struct android_smpte2086_metadata smpte2086_meta = {
634 .displayPrimaryRed = {
635 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
636 },
637 .displayPrimaryGreen = {
638 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
639 },
640 .displayPrimaryBlue = {
641 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
642 },
643 .whitePoint = {
644 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
645 },
646 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
647 .minLuminance = hdrStaticInfo->mastering.minLuminance,
648 };
649
650 struct android_cta861_3_metadata cta861_meta = {
651 .maxContentLightLevel = hdrStaticInfo->maxCll,
652 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
653 };
654
655 hdr.validTypes = HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3;
656 hdr.smpte2086 = smpte2086_meta;
657 hdr.cta8613 = cta861_meta;
658 }
659 if (hdr10PlusInfo) {
660 hdr.validTypes |= HdrMetadata::HDR10PLUS;
661 hdr.hdr10plus.assign(
662 hdr10PlusInfo->m.value,
663 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
664 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800665 qbi.setHdrMetadata(hdr);
666 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800667 // we don't have dirty regions
668 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800669 android::IGraphicBufferProducer::QueueBufferOutput qbo;
670 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
671 if (result != OK) {
672 ALOGI("[%s] queueBuffer failed: %d", mName, result);
673 return result;
674 }
675 ALOGV("[%s] queue buffer successful", mName);
676
677 int64_t mediaTimeUs = 0;
678 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
679 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
680
681 return OK;
682}
683
684status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
685 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
686 bool released = false;
687 {
688 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800689 if (*buffers && (*buffers)->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800690 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800691 }
692 }
693 {
694 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
695 if (*buffers && (*buffers)->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800696 released = true;
697 }
698 }
699 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800700 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800701 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800702 } else {
703 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
704 }
705 return OK;
706}
707
708void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
709 array->clear();
710 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
711
712 if (!(*buffers)->isArrayMode()) {
Wonsik Kim078b58e2019-01-09 15:08:06 -0800713 *buffers = (*buffers)->toArrayMode(mNumInputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800714 }
715
716 (*buffers)->getArray(array);
717}
718
719void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
720 array->clear();
721 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
722
723 if (!(*buffers)->isArrayMode()) {
Wonsik Kim078b58e2019-01-09 15:08:06 -0800724 *buffers = (*buffers)->toArrayMode(mNumOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800725 }
726
727 (*buffers)->getArray(array);
728}
729
730status_t CCodecBufferChannel::start(
731 const sp<AMessage> &inputFormat, const sp<AMessage> &outputFormat) {
732 C2StreamBufferTypeSetting::input iStreamFormat(0u);
733 C2StreamBufferTypeSetting::output oStreamFormat(0u);
734 C2PortReorderBufferDepthTuning::output reorderDepth;
735 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800736 C2PortActualDelayTuning::input inputDelay(0);
737 C2PortActualDelayTuning::output outputDelay(0);
738 C2ActualPipelineDelayTuning pipelineDelay(0);
739
Pawin Vongmasa36653902018-11-15 00:10:25 -0800740 c2_status_t err = mComponent->query(
741 {
742 &iStreamFormat,
743 &oStreamFormat,
744 &reorderDepth,
745 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800746 &inputDelay,
747 &pipelineDelay,
748 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800749 },
750 {},
751 C2_DONT_BLOCK,
752 nullptr);
753 if (err == C2_BAD_INDEX) {
754 if (!iStreamFormat || !oStreamFormat) {
755 return UNKNOWN_ERROR;
756 }
757 } else if (err != C2_OK) {
758 return UNKNOWN_ERROR;
759 }
760
761 {
762 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
763 reorder->clear();
764 if (reorderDepth) {
765 reorder->setDepth(reorderDepth.value);
766 }
767 if (reorderKey) {
768 reorder->setKey(reorderKey.value);
769 }
770 }
Wonsik Kim078b58e2019-01-09 15:08:06 -0800771
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800772 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
773 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
774 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
775
776 mNumInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
777 mNumOutputSlots = outputDelayValue + kSmoothnessFactor;
778 mDelay = inputDelayValue + pipelineDelayValue + outputDelayValue;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800779
Pawin Vongmasa36653902018-11-15 00:10:25 -0800780 // TODO: get this from input format
781 bool secure = mComponent->getName().find(".secure") != std::string::npos;
782
783 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
784 int poolMask = property_get_int32(
785 "debug.stagefright.c2-poolmask",
786 1 << C2PlatformAllocatorStore::ION |
787 1 << C2PlatformAllocatorStore::BUFFERQUEUE);
788
789 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800790 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800791 std::shared_ptr<C2BlockPool> pool;
792 {
793 Mutexed<BlockPools>::Locked pools(mBlockPools);
794
795 // set default allocator ID.
796 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
797 : C2PlatformAllocatorStore::ION;
798
799 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
800 // from component, create the input block pool with given ID. Otherwise, use default IDs.
801 std::vector<std::unique_ptr<C2Param>> params;
802 err = mComponent->query({ },
803 { C2PortAllocatorsTuning::input::PARAM_TYPE },
804 C2_DONT_BLOCK,
805 &params);
806 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
807 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
808 mName, params.size(), asString(err), err);
809 } else if (err == C2_OK && params.size() == 1) {
810 C2PortAllocatorsTuning::input *inputAllocators =
811 C2PortAllocatorsTuning::input::From(params[0].get());
812 if (inputAllocators && inputAllocators->flexCount() > 0) {
813 std::shared_ptr<C2Allocator> allocator;
814 // verify allocator IDs and resolve default allocator
815 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
816 if (allocator) {
817 pools->inputAllocatorId = allocator->getId();
818 } else {
819 ALOGD("[%s] component requested invalid input allocator ID %u",
820 mName, inputAllocators->m.values[0]);
821 }
822 }
823 }
824
825 // TODO: use C2Component wrapper to associate this pool with ourselves
826 if ((poolMask >> pools->inputAllocatorId) & 1) {
827 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
828 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
829 mName, pools->inputAllocatorId,
830 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
831 asString(err), err);
832 } else {
833 err = C2_NOT_FOUND;
834 }
835 if (err != C2_OK) {
836 C2BlockPool::local_id_t inputPoolId =
837 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
838 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
839 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
840 mName, (unsigned long long)inputPoolId,
841 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
842 asString(err), err);
843 if (err != C2_OK) {
844 return NO_MEMORY;
845 }
846 }
847 pools->inputPool = pool;
848 }
849
Wonsik Kim51051262018-11-28 13:59:05 -0800850 bool forceArrayMode = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800851 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
852 if (graphic) {
853 if (mInputSurface) {
854 buffers->reset(new DummyInputBuffers(mName));
855 } else if (mMetaMode == MODE_ANW) {
856 buffers->reset(new GraphicMetadataInputBuffers(mName));
857 } else {
Wonsik Kim078b58e2019-01-09 15:08:06 -0800858 buffers->reset(new GraphicInputBuffers(mNumInputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800859 }
860 } else {
861 if (hasCryptoOrDescrambler()) {
862 int32_t capacity = kLinearBufferSize;
863 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
864 if ((size_t)capacity > kMaxLinearBufferSize) {
865 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
866 capacity = kMaxLinearBufferSize;
867 }
868 if (mDealer == nullptr) {
869 mDealer = new MemoryDealer(
870 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim078b58e2019-01-09 15:08:06 -0800871 * (mNumInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800872 "EncryptedLinearInputBuffers");
873 mDecryptDestination = mDealer->allocate((size_t)capacity);
874 }
875 if (mCrypto != nullptr && mHeapSeqNum < 0) {
876 mHeapSeqNum = mCrypto->setHeap(mDealer->getMemoryHeap());
877 } else {
878 mHeapSeqNum = -1;
879 }
880 buffers->reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -0800881 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
882 mNumInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -0800883 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800884 } else {
885 buffers->reset(new LinearInputBuffers(mName));
886 }
887 }
888 (*buffers)->setFormat(inputFormat);
889
890 if (err == C2_OK) {
891 (*buffers)->setPool(pool);
892 } else {
893 // TODO: error
894 }
Wonsik Kim51051262018-11-28 13:59:05 -0800895
896 if (forceArrayMode) {
Wonsik Kim078b58e2019-01-09 15:08:06 -0800897 *buffers = (*buffers)->toArrayMode(mNumInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -0800898 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800899 }
900
901 if (outputFormat != nullptr) {
902 sp<IGraphicBufferProducer> outputSurface;
903 uint32_t outputGeneration;
904 {
905 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Wonsik Kimf5e5c832019-02-21 11:36:05 -0800906 output->maxDequeueBuffers = mNumOutputSlots + reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800907 outputSurface = output->surface ?
908 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -0800909 if (outputSurface) {
910 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
911 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800912 outputGeneration = output->generation;
913 }
914
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800915 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800916 C2BlockPool::local_id_t outputPoolId_;
917
918 {
919 Mutexed<BlockPools>::Locked pools(mBlockPools);
920
921 // set default allocator ID.
922 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
923 : C2PlatformAllocatorStore::ION;
924
925 // query C2PortAllocatorsTuning::output from component, or use default allocator if
926 // unsuccessful.
927 std::vector<std::unique_ptr<C2Param>> params;
928 err = mComponent->query({ },
929 { C2PortAllocatorsTuning::output::PARAM_TYPE },
930 C2_DONT_BLOCK,
931 &params);
932 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
933 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
934 mName, params.size(), asString(err), err);
935 } else if (err == C2_OK && params.size() == 1) {
936 C2PortAllocatorsTuning::output *outputAllocators =
937 C2PortAllocatorsTuning::output::From(params[0].get());
938 if (outputAllocators && outputAllocators->flexCount() > 0) {
939 std::shared_ptr<C2Allocator> allocator;
940 // verify allocator IDs and resolve default allocator
941 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
942 if (allocator) {
943 pools->outputAllocatorId = allocator->getId();
944 } else {
945 ALOGD("[%s] component requested invalid output allocator ID %u",
946 mName, outputAllocators->m.values[0]);
947 }
948 }
949 }
950
951 // use bufferqueue if outputting to a surface.
952 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
953 // if unsuccessful.
954 if (outputSurface) {
955 params.clear();
956 err = mComponent->query({ },
957 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
958 C2_DONT_BLOCK,
959 &params);
960 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
961 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
962 mName, params.size(), asString(err), err);
963 } else if (err == C2_OK && params.size() == 1) {
964 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
965 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
966 if (surfaceAllocator) {
967 std::shared_ptr<C2Allocator> allocator;
968 // verify allocator IDs and resolve default allocator
969 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
970 if (allocator) {
971 pools->outputAllocatorId = allocator->getId();
972 } else {
973 ALOGD("[%s] component requested invalid surface output allocator ID %u",
974 mName, surfaceAllocator->value);
975 err = C2_BAD_VALUE;
976 }
977 }
978 }
979 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
980 && err != C2_OK
981 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
982 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
983 }
984 }
985
986 if ((poolMask >> pools->outputAllocatorId) & 1) {
987 err = mComponent->createBlockPool(
988 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
989 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
990 mName, pools->outputAllocatorId,
991 (unsigned long long)pools->outputPoolId,
992 asString(err));
993 } else {
994 err = C2_NOT_FOUND;
995 }
996 if (err != C2_OK) {
997 // use basic pool instead
998 pools->outputPoolId =
999 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1000 }
1001
1002 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1003 // component.
1004 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1005 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1006
1007 std::vector<std::unique_ptr<C2SettingResult>> failures;
1008 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1009 ALOGD("[%s] Configured output block pool ids %llu => %s",
1010 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1011 outputPoolId_ = pools->outputPoolId;
1012 }
1013
1014 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1015
1016 if (graphic) {
1017 if (outputSurface) {
1018 buffers->reset(new GraphicOutputBuffers(mName));
1019 } else {
Wonsik Kim078b58e2019-01-09 15:08:06 -08001020 buffers->reset(new RawGraphicOutputBuffers(mNumOutputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001021 }
1022 } else {
1023 buffers->reset(new LinearOutputBuffers(mName));
1024 }
1025 (*buffers)->setFormat(outputFormat->dup());
1026
1027
1028 // Try to set output surface to created block pool if given.
1029 if (outputSurface) {
1030 mComponent->setOutputSurface(
1031 outputPoolId_,
1032 outputSurface,
1033 outputGeneration);
1034 }
1035
1036 if (oStreamFormat.value == C2BufferData::LINEAR
1037 && mComponentName.find("c2.qti.") == std::string::npos) {
1038 // WORKAROUND: if we're using early CSD workaround we convert to
1039 // array mode, to appease apps assuming the output
1040 // buffers to be of the same size.
Wonsik Kim078b58e2019-01-09 15:08:06 -08001041 (*buffers) = (*buffers)->toArrayMode(mNumOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001042
1043 int32_t channelCount;
1044 int32_t sampleRate;
1045 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1046 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1047 int32_t delay = 0;
1048 int32_t padding = 0;;
1049 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1050 delay = 0;
1051 }
1052 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1053 padding = 0;
1054 }
1055 if (delay || padding) {
1056 // We need write access to the buffers, and we're already in
1057 // array mode.
1058 (*buffers)->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
1059 }
1060 }
1061 }
1062 }
1063
1064 // Set up pipeline control. This has to be done after mInputBuffers and
1065 // mOutputBuffers are initialized to make sure that lingering callbacks
1066 // about buffers from the previous generation do not interfere with the
1067 // newly initialized pipeline capacity.
1068
Wonsik Kimab34ed62019-01-31 15:28:46 -08001069 {
1070 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001071 watcher->inputDelay(inputDelayValue)
1072 .pipelineDelay(pipelineDelayValue)
1073 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001074 .smoothnessFactor(kSmoothnessFactor);
1075 watcher->flush();
1076 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001077
1078 mInputMetEos = false;
1079 mSync.start();
1080 return OK;
1081}
1082
1083status_t CCodecBufferChannel::requestInitialInputBuffers() {
1084 if (mInputSurface) {
1085 return OK;
1086 }
1087
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001088 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001089 c2_status_t err = mComponent->query({ &oStreamFormat }, {}, C2_DONT_BLOCK, nullptr);
1090 if (err != C2_OK) {
1091 return UNKNOWN_ERROR;
1092 }
1093 std::vector<sp<MediaCodecBuffer>> toBeQueued;
1094 // TODO: use proper buffer depth instead of this random value
Wonsik Kim078b58e2019-01-09 15:08:06 -08001095 for (size_t i = 0; i < mNumInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001096 size_t index;
1097 sp<MediaCodecBuffer> buffer;
1098 {
1099 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1100 if (!(*buffers)->requestNewBuffer(&index, &buffer)) {
1101 if (i == 0) {
1102 ALOGW("[%s] start: cannot allocate memory at all", mName);
1103 return NO_MEMORY;
1104 } else {
1105 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
1106 mName, i);
1107 }
1108 break;
1109 }
1110 }
1111 if (buffer) {
1112 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1113 ALOGV("[%s] input buffer %zu available", mName, index);
1114 bool post = true;
1115 if (!configs->empty()) {
1116 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001117 configs->pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001118 if (buffer->capacity() >= config->size()) {
1119 memcpy(buffer->base(), config->data(), config->size());
1120 buffer->setRange(0, config->size());
1121 buffer->meta()->clear();
1122 buffer->meta()->setInt64("timeUs", 0);
1123 buffer->meta()->setInt32("csd", 1);
1124 post = false;
1125 } else {
1126 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
1127 mName, buffer->capacity(), config->size());
1128 }
1129 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
1130 && mComponentName.find("c2.qti.") == std::string::npos) {
1131 // WORKAROUND: Some apps expect CSD available without queueing
1132 // any input. Queue an empty buffer to get the CSD.
1133 buffer->setRange(0, 0);
1134 buffer->meta()->clear();
1135 buffer->meta()->setInt64("timeUs", 0);
1136 post = false;
1137 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001138 if (post) {
1139 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001140 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001141 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001142 }
1143 }
1144 }
1145 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
1146 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001147 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001148 }
1149 }
1150 return OK;
1151}
1152
1153void CCodecBufferChannel::stop() {
1154 mSync.stop();
1155 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1156 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001157 mInputSurface.reset();
1158 }
1159}
1160
1161void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1162 ALOGV("[%s] flush", mName);
1163 {
1164 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1165 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1166 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1167 continue;
1168 }
1169 if (work->input.buffers.empty()
1170 || work->input.buffers.front()->data().linearBlocks().empty()) {
1171 ALOGD("[%s] no linear codec config data found", mName);
1172 continue;
1173 }
1174 C2ReadView view =
1175 work->input.buffers.front()->data().linearBlocks().front().map().get();
1176 if (view.error() != C2_OK) {
1177 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1178 continue;
1179 }
1180 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1181 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1182 }
1183 }
1184 {
1185 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1186 (*buffers)->flush();
1187 }
1188 {
1189 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1190 (*buffers)->flush(flushedWork);
1191 }
Wonsik Kim6897f222019-01-30 13:29:24 -08001192 mReorderStash.lock()->flush();
Wonsik Kimab34ed62019-01-31 15:28:46 -08001193 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001194}
1195
1196void CCodecBufferChannel::onWorkDone(
1197 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001198 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001199 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001200 feedInputBufferIfAvailable();
1201 }
1202}
1203
1204void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001205 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001206 if (mInputSurface) {
1207 return;
1208 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001209 std::shared_ptr<C2Buffer> buffer =
1210 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001211 bool newInputSlotAvailable;
1212 {
1213 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1214 newInputSlotAvailable = (*buffers)->expireComponentBuffer(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001215 }
1216 if (newInputSlotAvailable) {
1217 feedInputBufferIfAvailable();
1218 }
1219}
1220
1221bool CCodecBufferChannel::handleWork(
1222 std::unique_ptr<C2Work> work,
1223 const sp<AMessage> &outputFormat,
1224 const C2StreamInitDataInfo::output *initData) {
1225 if ((work->input.ordinal.frameIndex - mFirstValidFrameIndex.load()).peek() < 0) {
1226 // Discard frames from previous generation.
1227 ALOGD("[%s] Discard frames from previous generation.", mName);
1228 return false;
1229 }
1230
Wonsik Kim524b0582019-03-12 11:28:57 -07001231 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001232 || !work->worklets.front()
Wonsik Kim524b0582019-03-12 11:28:57 -07001233 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE))) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001234 mPipelineWatcher.lock()->onWorkDone(work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001235 }
1236
1237 if (work->result == C2_NOT_FOUND) {
1238 ALOGD("[%s] flushed work; ignored.", mName);
1239 return true;
1240 }
1241
1242 if (work->result != C2_OK) {
1243 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1244 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1245 return false;
1246 }
1247
1248 // NOTE: MediaCodec usage supposedly have only one worklet
1249 if (work->worklets.size() != 1u) {
1250 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1251 mName, work->worklets.size());
1252 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1253 return false;
1254 }
1255
1256 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1257
1258 std::shared_ptr<C2Buffer> buffer;
1259 // NOTE: MediaCodec usage supposedly have only one output stream.
1260 if (worklet->output.buffers.size() > 1u) {
1261 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1262 mName, worklet->output.buffers.size());
1263 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1264 return false;
1265 } else if (worklet->output.buffers.size() == 1u) {
1266 buffer = worklet->output.buffers[0];
1267 if (!buffer) {
1268 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1269 }
1270 }
1271
1272 while (!worklet->output.configUpdate.empty()) {
1273 std::unique_ptr<C2Param> param;
1274 worklet->output.configUpdate.back().swap(param);
1275 worklet->output.configUpdate.pop_back();
1276 switch (param->coreIndex().coreIndex()) {
1277 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1278 C2PortReorderBufferDepthTuning::output reorderDepth;
1279 if (reorderDepth.updateFrom(*param)) {
1280 mReorderStash.lock()->setDepth(reorderDepth.value);
1281 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1282 mName, reorderDepth.value);
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001283 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1284 output->maxDequeueBuffers = mNumOutputSlots + reorderDepth.value + kRenderingDepth;
1285 if (output->surface) {
1286 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1287 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001288 } else {
1289 ALOGD("[%s] onWorkDone: failed to read reorder depth", mName);
1290 }
1291 break;
1292 }
1293 case C2PortReorderKeySetting::CORE_INDEX: {
1294 C2PortReorderKeySetting::output reorderKey;
1295 if (reorderKey.updateFrom(*param)) {
1296 mReorderStash.lock()->setKey(reorderKey.value);
1297 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1298 mName, reorderKey.value);
1299 } else {
1300 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1301 }
1302 break;
1303 }
1304 default:
1305 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1306 mName, param->index());
1307 break;
1308 }
1309 }
1310
1311 if (outputFormat != nullptr) {
1312 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1313 ALOGD("[%s] onWorkDone: output format changed to %s",
1314 mName, outputFormat->debugString().c_str());
1315 (*buffers)->setFormat(outputFormat);
1316
1317 AString mediaType;
1318 if (outputFormat->findString(KEY_MIME, &mediaType)
1319 && mediaType == MIMETYPE_AUDIO_RAW) {
1320 int32_t channelCount;
1321 int32_t sampleRate;
1322 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1323 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1324 (*buffers)->updateSkipCutBuffer(sampleRate, channelCount);
1325 }
1326 }
1327 }
1328
1329 int32_t flags = 0;
1330 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1331 flags |= MediaCodec::BUFFER_FLAG_EOS;
1332 ALOGV("[%s] onWorkDone: output EOS", mName);
1333 }
1334
1335 sp<MediaCodecBuffer> outBuffer;
1336 size_t index;
1337
1338 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1339 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1340 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1341 // shall correspond to the client input timesamp (in customOrdinal). By using the
1342 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1343 // produces multiple output.
1344 c2_cntr64_t timestamp =
1345 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1346 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001347 if (mInputSurface != nullptr) {
1348 // When using input surface we need to restore the original input timestamp.
1349 timestamp = work->input.ordinal.customOrdinal;
1350 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001351 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1352 mName,
1353 work->input.ordinal.customOrdinal.peekll(),
1354 work->input.ordinal.timestamp.peekll(),
1355 worklet->output.ordinal.timestamp.peekll(),
1356 timestamp.peekll());
1357
1358 if (initData != nullptr) {
1359 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1360 if ((*buffers)->registerCsd(initData, &index, &outBuffer) == OK) {
1361 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1362 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1363 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1364
1365 buffers.unlock();
1366 mCallback->onOutputBufferAvailable(index, outBuffer);
1367 buffers.lock();
1368 } else {
1369 ALOGD("[%s] onWorkDone: unable to register csd", mName);
1370 buffers.unlock();
1371 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1372 buffers.lock();
1373 return false;
1374 }
1375 }
1376
1377 if (!buffer && !flags) {
1378 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1379 mName, work->input.ordinal.frameIndex.peekull());
1380 return true;
1381 }
1382
1383 if (buffer) {
1384 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1385 // TODO: properly translate these to metadata
1386 switch (info->coreIndex().coreIndex()) {
1387 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001388 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001389 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1390 }
1391 break;
1392 default:
1393 break;
1394 }
1395 }
1396 }
1397
1398 {
1399 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1400 reorder->emplace(buffer, timestamp.peek(), flags, worklet->output.ordinal);
1401 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
1402 // Flush reorder stash
1403 reorder->setDepth(0);
1404 }
1405 }
1406 sendOutputBuffers();
1407 return true;
1408}
1409
1410void CCodecBufferChannel::sendOutputBuffers() {
1411 ReorderStash::Entry entry;
1412 sp<MediaCodecBuffer> outBuffer;
1413 size_t index;
1414
1415 while (true) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001416 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1417 if (!reorder->hasPending()) {
1418 break;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001419 }
Wonsik Kim38ad3412019-02-01 15:13:23 -08001420 if (!reorder->pop(&entry)) {
1421 break;
1422 }
1423
Pawin Vongmasa36653902018-11-15 00:10:25 -08001424 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1425 status_t err = (*buffers)->registerBuffer(entry.buffer, &index, &outBuffer);
1426 if (err != OK) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001427 bool outputBuffersChanged = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001428 if (err != WOULD_BLOCK) {
Wonsik Kim186fdbf2019-01-29 13:30:01 -08001429 if (!(*buffers)->isArrayMode()) {
1430 *buffers = (*buffers)->toArrayMode(mNumOutputSlots);
1431 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001432 OutputBuffersArray *array = (OutputBuffersArray *)buffers->get();
1433 array->realloc(entry.buffer);
Wonsik Kim38ad3412019-02-01 15:13:23 -08001434 outputBuffersChanged = true;
1435 }
1436 ALOGV("[%s] sendOutputBuffers: unable to register output buffer", mName);
1437 reorder->defer(entry);
1438
1439 buffers.unlock();
1440 reorder.unlock();
1441
1442 if (outputBuffersChanged) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001443 mCCodecCallback->onOutputBuffersChanged();
1444 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001445 return;
1446 }
1447 buffers.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08001448 reorder.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001449
1450 outBuffer->meta()->setInt64("timeUs", entry.timestamp);
1451 outBuffer->meta()->setInt32("flags", entry.flags);
Wonsik Kim66427432019-03-21 15:06:22 -07001452 ALOGV("[%s] sendOutputBuffers: out buffer index = %zu [%p] => %p + %zu (%lld)",
1453 mName, index, outBuffer.get(), outBuffer->data(), outBuffer->size(),
1454 (long long)entry.timestamp);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001455 mCallback->onOutputBufferAvailable(index, outBuffer);
1456 }
1457}
1458
1459status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1460 static std::atomic_uint32_t surfaceGeneration{0};
1461 uint32_t generation = (getpid() << 10) |
1462 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1463 & ((1 << 10) - 1));
1464
1465 sp<IGraphicBufferProducer> producer;
1466 if (newSurface) {
1467 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001468 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001469 producer = newSurface->getIGraphicBufferProducer();
1470 producer->setGenerationNumber(generation);
1471 } else {
1472 ALOGE("[%s] setting output surface to null", mName);
1473 return INVALID_OPERATION;
1474 }
1475
1476 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1477 C2BlockPool::local_id_t outputPoolId;
1478 {
1479 Mutexed<BlockPools>::Locked pools(mBlockPools);
1480 outputPoolId = pools->outputPoolId;
1481 outputPoolIntf = pools->outputPoolIntf;
1482 }
1483
1484 if (outputPoolIntf) {
1485 if (mComponent->setOutputSurface(
1486 outputPoolId,
1487 producer,
1488 generation) != C2_OK) {
1489 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1490 return INVALID_OPERATION;
1491 }
1492 }
1493
1494 {
1495 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001496 newSurface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001497 output->surface = newSurface;
1498 output->generation = generation;
1499 }
1500
1501 return OK;
1502}
1503
Wonsik Kimab34ed62019-01-31 15:28:46 -08001504PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001505 // When client pushed EOS, we want all the work to be done quickly.
1506 // Otherwise, component may have stalled work due to input starvation up to
1507 // the sum of the delay in the pipeline.
1508 size_t n = mInputMetEos ? 0 : mDelay;
1509 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001510}
1511
Pawin Vongmasa36653902018-11-15 00:10:25 -08001512void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1513 mMetaMode = mode;
1514}
1515
1516status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1517 // C2_OK is always translated to OK.
1518 if (c2s == C2_OK) {
1519 return OK;
1520 }
1521
1522 // Operation-dependent translation
1523 // TODO: Add as necessary
1524 switch (c2op) {
1525 case C2_OPERATION_Component_start:
1526 switch (c2s) {
1527 case C2_NO_MEMORY:
1528 return NO_MEMORY;
1529 default:
1530 return UNKNOWN_ERROR;
1531 }
1532 default:
1533 break;
1534 }
1535
1536 // Backup operation-agnostic translation
1537 switch (c2s) {
1538 case C2_BAD_INDEX:
1539 return BAD_INDEX;
1540 case C2_BAD_VALUE:
1541 return BAD_VALUE;
1542 case C2_BLOCKING:
1543 return WOULD_BLOCK;
1544 case C2_DUPLICATE:
1545 return ALREADY_EXISTS;
1546 case C2_NO_INIT:
1547 return NO_INIT;
1548 case C2_NO_MEMORY:
1549 return NO_MEMORY;
1550 case C2_NOT_FOUND:
1551 return NAME_NOT_FOUND;
1552 case C2_TIMED_OUT:
1553 return TIMED_OUT;
1554 case C2_BAD_STATE:
1555 case C2_CANCELED:
1556 case C2_CANNOT_DO:
1557 case C2_CORRUPTED:
1558 case C2_OMITTED:
1559 case C2_REFUSED:
1560 return UNKNOWN_ERROR;
1561 default:
1562 return -static_cast<status_t>(c2s);
1563 }
1564}
1565
1566} // namespace android