blob: 18832253691d459a1b55be93fa4b542308c30893 [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>
Ray Essick18ea0452019-08-27 16:07:27 -070032#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080033#include <gui/Surface.h>
34#include <media/openmax/OMX_Core.h>
35#include <media/stagefright/foundation/ABuffer.h>
36#include <media/stagefright/foundation/ALookup.h>
37#include <media/stagefright/foundation/AMessage.h>
38#include <media/stagefright/foundation/AUtils.h>
39#include <media/stagefright/foundation/hexdump.h>
40#include <media/stagefright/MediaCodec.h>
41#include <media/stagefright/MediaCodecConstants.h>
42#include <media/MediaCodecBuffer.h>
43#include <system/window.h>
44
45#include "CCodecBufferChannel.h"
46#include "Codec2Buffer.h"
47#include "SkipCutBuffer.h"
48
49namespace android {
50
51using android::base::StringPrintf;
52using hardware::hidl_handle;
53using hardware::hidl_string;
54using hardware::hidl_vec;
55using namespace hardware::cas::V1_0;
56using namespace hardware::cas::native::V1_0;
57
58using CasStatus = hardware::cas::V1_0::Status;
59
Pawin Vongmasa36653902018-11-15 00:10:25 -080060namespace {
61
Wonsik Kim469c8342019-04-11 16:46:09 -070062constexpr size_t kSmoothnessFactor = 4;
63constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080064
Sungtak Leeab6f2f32019-02-15 14:43:51 -080065// This is for keeping IGBP's buffer dropping logic in legacy mode other
66// than making it non-blocking. Do not change this value.
67const static size_t kDequeueTimeoutNs = 0;
68
Pawin Vongmasa36653902018-11-15 00:10:25 -080069} // namespace
70
71CCodecBufferChannel::QueueGuard::QueueGuard(
72 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
73 Mutex::Autolock l(mSync.mGuardLock);
74 // At this point it's guaranteed that mSync is not under state transition,
75 // as we are holding its mutex.
76
77 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
78 if (count->value == -1) {
79 mRunning = false;
80 } else {
81 ++count->value;
82 mRunning = true;
83 }
84}
85
86CCodecBufferChannel::QueueGuard::~QueueGuard() {
87 if (mRunning) {
88 // We are not holding mGuardLock at this point so that QueueSync::stop() can
89 // keep holding the lock until mCount reaches zero.
90 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
91 --count->value;
92 count->cond.broadcast();
93 }
94}
95
96void CCodecBufferChannel::QueueSync::start() {
97 Mutex::Autolock l(mGuardLock);
98 // If stopped, it goes to running state; otherwise no-op.
99 Mutexed<Counter>::Locked count(mCount);
100 if (count->value == -1) {
101 count->value = 0;
102 }
103}
104
105void CCodecBufferChannel::QueueSync::stop() {
106 Mutex::Autolock l(mGuardLock);
107 Mutexed<Counter>::Locked count(mCount);
108 if (count->value == -1) {
109 // no-op
110 return;
111 }
112 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
113 // mCount can only decrement. In other words, threads that acquired the lock
114 // are allowed to finish execution but additional threads trying to acquire
115 // the lock at this point will block, and then get QueueGuard at STOPPED
116 // state.
117 while (count->value != 0) {
118 count.waitForCondition(count->cond);
119 }
120 count->value = -1;
121}
122
Pawin Vongmasa36653902018-11-15 00:10:25 -0800123// CCodecBufferChannel::ReorderStash
124
125CCodecBufferChannel::ReorderStash::ReorderStash() {
126 clear();
127}
128
129void CCodecBufferChannel::ReorderStash::clear() {
130 mPending.clear();
131 mStash.clear();
132 mDepth = 0;
133 mKey = C2Config::ORDINAL;
134}
135
Wonsik Kim6897f222019-01-30 13:29:24 -0800136void CCodecBufferChannel::ReorderStash::flush() {
137 mPending.clear();
138 mStash.clear();
139}
140
Pawin Vongmasa36653902018-11-15 00:10:25 -0800141void CCodecBufferChannel::ReorderStash::setDepth(uint32_t depth) {
142 mPending.splice(mPending.end(), mStash);
143 mDepth = depth;
144}
Wonsik Kim66427432019-03-21 15:06:22 -0700145
Pawin Vongmasa36653902018-11-15 00:10:25 -0800146void CCodecBufferChannel::ReorderStash::setKey(C2Config::ordinal_key_t key) {
147 mPending.splice(mPending.end(), mStash);
148 mKey = key;
149}
150
151bool CCodecBufferChannel::ReorderStash::pop(Entry *entry) {
152 if (mPending.empty()) {
153 return false;
154 }
155 entry->buffer = mPending.front().buffer;
156 entry->timestamp = mPending.front().timestamp;
157 entry->flags = mPending.front().flags;
158 entry->ordinal = mPending.front().ordinal;
159 mPending.pop_front();
160 return true;
161}
162
163void CCodecBufferChannel::ReorderStash::emplace(
164 const std::shared_ptr<C2Buffer> &buffer,
165 int64_t timestamp,
166 int32_t flags,
167 const C2WorkOrdinalStruct &ordinal) {
Wonsik Kim66427432019-03-21 15:06:22 -0700168 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
169 if (!buffer && eos) {
170 // TRICKY: we may be violating ordering of the stash here. Because we
171 // don't expect any more emplace() calls after this, the ordering should
172 // not matter.
173 mStash.emplace_back(buffer, timestamp, flags, ordinal);
174 } else {
175 flags = flags & ~MediaCodec::BUFFER_FLAG_EOS;
176 auto it = mStash.begin();
177 for (; it != mStash.end(); ++it) {
178 if (less(ordinal, it->ordinal)) {
179 break;
180 }
181 }
182 mStash.emplace(it, buffer, timestamp, flags, ordinal);
183 if (eos) {
184 mStash.back().flags = mStash.back().flags | MediaCodec::BUFFER_FLAG_EOS;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800185 }
186 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800187 while (!mStash.empty() && mStash.size() > mDepth) {
188 mPending.push_back(mStash.front());
189 mStash.pop_front();
190 }
191}
192
193void CCodecBufferChannel::ReorderStash::defer(
194 const CCodecBufferChannel::ReorderStash::Entry &entry) {
195 mPending.push_front(entry);
196}
197
198bool CCodecBufferChannel::ReorderStash::hasPending() const {
199 return !mPending.empty();
200}
201
202bool CCodecBufferChannel::ReorderStash::less(
203 const C2WorkOrdinalStruct &o1, const C2WorkOrdinalStruct &o2) {
204 switch (mKey) {
205 case C2Config::ORDINAL: return o1.frameIndex < o2.frameIndex;
206 case C2Config::TIMESTAMP: return o1.timestamp < o2.timestamp;
207 case C2Config::CUSTOM: return o1.customOrdinal < o2.customOrdinal;
208 default:
209 ALOGD("Unrecognized key; default to timestamp");
210 return o1.frameIndex < o2.frameIndex;
211 }
212}
213
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700214// Input
215
216CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
217
Pawin Vongmasa36653902018-11-15 00:10:25 -0800218// CCodecBufferChannel
219
220CCodecBufferChannel::CCodecBufferChannel(
221 const std::shared_ptr<CCodecCallback> &callback)
222 : mHeapSeqNum(-1),
223 mCCodecCallback(callback),
224 mFrameIndex(0u),
225 mFirstValidFrameIndex(0u),
226 mMetaMode(MODE_NONE),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800227 mInputMetEos(false) {
Sungtak Lee7a7b7422019-07-16 17:40:40 -0700228 mOutputSurface.lock()->maxDequeueBuffers = 2 * kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700229 {
230 Mutexed<Input>::Locked input(mInput);
231 input->buffers.reset(new DummyInputBuffers(""));
232 input->extraBuffers.flush();
233 input->inputDelay = 0u;
234 input->pipelineDelay = 0u;
235 input->numSlots = kSmoothnessFactor;
236 input->numExtraSlots = 0u;
237 }
238 {
239 Mutexed<Output>::Locked output(mOutput);
240 output->outputDelay = 0u;
241 output->numSlots = kSmoothnessFactor;
242 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800243}
244
245CCodecBufferChannel::~CCodecBufferChannel() {
246 if (mCrypto != nullptr && mDealer != nullptr && mHeapSeqNum >= 0) {
247 mCrypto->unsetHeap(mHeapSeqNum);
248 }
249}
250
251void CCodecBufferChannel::setComponent(
252 const std::shared_ptr<Codec2Client::Component> &component) {
253 mComponent = component;
254 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
255 mName = mComponentName.c_str();
256}
257
258status_t CCodecBufferChannel::setInputSurface(
259 const std::shared_ptr<InputSurfaceWrapper> &surface) {
260 ALOGV("[%s] setInputSurface", mName);
261 mInputSurface = surface;
262 return mInputSurface->connect(mComponent);
263}
264
265status_t CCodecBufferChannel::signalEndOfInputStream() {
266 if (mInputSurface == nullptr) {
267 return INVALID_OPERATION;
268 }
269 return mInputSurface->signalEndOfInputStream();
270}
271
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700272status_t CCodecBufferChannel::queueInputBufferInternal(sp<MediaCodecBuffer> buffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800273 int64_t timeUs;
274 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
275
276 if (mInputMetEos) {
277 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
278 return OK;
279 }
280
281 int32_t flags = 0;
282 int32_t tmp = 0;
283 bool eos = false;
284 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
285 eos = true;
286 mInputMetEos = true;
287 ALOGV("[%s] input EOS", mName);
288 }
289 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
290 flags |= C2FrameData::FLAG_CODEC_CONFIG;
291 }
292 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
293 std::unique_ptr<C2Work> work(new C2Work);
294 work->input.ordinal.timestamp = timeUs;
295 work->input.ordinal.frameIndex = mFrameIndex++;
296 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
297 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
298 // Keep client timestamp in customOrdinal
299 work->input.ordinal.customOrdinal = timeUs;
300 work->input.buffers.clear();
301
Wonsik Kimab34ed62019-01-31 15:28:46 -0800302 uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
303 std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700304 sp<Codec2Buffer> copy;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800305
Pawin Vongmasa36653902018-11-15 00:10:25 -0800306 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700307 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800308 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700309 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800310 return -ENOENT;
311 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700312 // TODO: we want to delay copying buffers.
313 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
314 copy = input->buffers->cloneAndReleaseBuffer(buffer);
315 if (copy != nullptr) {
316 (void)input->extraBuffers.assignSlot(copy);
317 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
318 return UNKNOWN_ERROR;
319 }
320 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
321 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
322 mName, released ? "" : "not ");
323 buffer.clear();
324 } else {
325 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
326 "buffer starvation on component.", mName);
327 }
328 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800329 work->input.buffers.push_back(c2buffer);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800330 queuedBuffers.push_back(c2buffer);
331 } else if (eos) {
332 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800333 }
334 work->input.flags = (C2FrameData::flags_t)flags;
335 // TODO: fill info's
336
337 work->input.configUpdate = std::move(mParamsToBeSet);
338 work->worklets.clear();
339 work->worklets.emplace_back(new C2Worklet);
340
341 std::list<std::unique_ptr<C2Work>> items;
342 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800343 mPipelineWatcher.lock()->onWorkQueued(
344 queuedFrameIndex,
345 std::move(queuedBuffers),
346 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800347 c2_status_t err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800348 if (err != C2_OK) {
349 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
350 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800351
352 if (err == C2_OK && eos && buffer->size() > 0u) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800353 work.reset(new C2Work);
354 work->input.ordinal.timestamp = timeUs;
355 work->input.ordinal.frameIndex = mFrameIndex++;
356 // WORKAROUND: keep client timestamp in customOrdinal
357 work->input.ordinal.customOrdinal = timeUs;
358 work->input.buffers.clear();
359 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800360 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800361
Wonsik Kimab34ed62019-01-31 15:28:46 -0800362 queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
363 queuedBuffers.clear();
364
Pawin Vongmasa36653902018-11-15 00:10:25 -0800365 items.clear();
366 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800367
368 mPipelineWatcher.lock()->onWorkQueued(
369 queuedFrameIndex,
370 std::move(queuedBuffers),
371 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800372 err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800373 if (err != C2_OK) {
374 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
375 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800376 }
377 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700378 Mutexed<Input>::Locked input(mInput);
379 bool released = false;
380 if (buffer) {
381 released = input->buffers->releaseBuffer(buffer, nullptr, true);
382 } else if (copy) {
383 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
384 }
385 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
386 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800387 }
388
389 feedInputBufferIfAvailableInternal();
390 return err;
391}
392
393status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
394 QueueGuard guard(mSync);
395 if (!guard.isRunning()) {
396 ALOGD("[%s] setParameters is only supported in the running state.", mName);
397 return -ENOSYS;
398 }
399 mParamsToBeSet.insert(mParamsToBeSet.end(),
400 std::make_move_iterator(params.begin()),
401 std::make_move_iterator(params.end()));
402 params.clear();
403 return OK;
404}
405
406status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
407 QueueGuard guard(mSync);
408 if (!guard.isRunning()) {
409 ALOGD("[%s] No more buffers should be queued at current state.", mName);
410 return -ENOSYS;
411 }
412 return queueInputBufferInternal(buffer);
413}
414
415status_t CCodecBufferChannel::queueSecureInputBuffer(
416 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
417 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
418 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
419 AString *errorDetailMsg) {
420 QueueGuard guard(mSync);
421 if (!guard.isRunning()) {
422 ALOGD("[%s] No more buffers should be queued at current state.", mName);
423 return -ENOSYS;
424 }
425
426 if (!hasCryptoOrDescrambler()) {
427 return -ENOSYS;
428 }
429 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
430
431 ssize_t result = -1;
432 ssize_t codecDataOffset = 0;
433 if (mCrypto != nullptr) {
434 ICrypto::DestinationBuffer destination;
435 if (secure) {
436 destination.mType = ICrypto::kDestinationTypeNativeHandle;
437 destination.mHandle = encryptedBuffer->handle();
438 } else {
439 destination.mType = ICrypto::kDestinationTypeSharedMemory;
440 destination.mSharedMemory = mDecryptDestination;
441 }
442 ICrypto::SourceBuffer source;
443 encryptedBuffer->fillSourceBuffer(&source);
444 result = mCrypto->decrypt(
445 key, iv, mode, pattern, source, buffer->offset(),
446 subSamples, numSubSamples, destination, errorDetailMsg);
447 if (result < 0) {
448 return result;
449 }
450 if (destination.mType == ICrypto::kDestinationTypeSharedMemory) {
451 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
452 }
453 } else {
454 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
455 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
456 hidl_vec<SubSample> hidlSubSamples;
457 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
458
459 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
460 encryptedBuffer->fillSourceBuffer(&srcBuffer);
461
462 DestinationBuffer dstBuffer;
463 if (secure) {
464 dstBuffer.type = BufferType::NATIVE_HANDLE;
465 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
466 } else {
467 dstBuffer.type = BufferType::SHARED_MEMORY;
468 dstBuffer.nonsecureMemory = srcBuffer;
469 }
470
471 CasStatus status = CasStatus::OK;
472 hidl_string detailedError;
473 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
474
475 if (key != nullptr) {
476 sctrl = (ScramblingControl)key[0];
477 // Adjust for the PES offset
478 codecDataOffset = key[2] | (key[3] << 8);
479 }
480
481 auto returnVoid = mDescrambler->descramble(
482 sctrl,
483 hidlSubSamples,
484 srcBuffer,
485 0,
486 dstBuffer,
487 0,
488 [&status, &result, &detailedError] (
489 CasStatus _status, uint32_t _bytesWritten,
490 const hidl_string& _detailedError) {
491 status = _status;
492 result = (ssize_t)_bytesWritten;
493 detailedError = _detailedError;
494 });
495
496 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
497 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
498 mName, returnVoid.description().c_str(), status, result);
499 return UNKNOWN_ERROR;
500 }
501
502 if (result < codecDataOffset) {
503 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
504 return BAD_VALUE;
505 }
506
507 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
508
509 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
510 encryptedBuffer->copyDecryptedContentFromMemory(result);
511 }
512 }
513
514 buffer->setRange(codecDataOffset, result - codecDataOffset);
515 return queueInputBufferInternal(buffer);
516}
517
518void CCodecBufferChannel::feedInputBufferIfAvailable() {
519 QueueGuard guard(mSync);
520 if (!guard.isRunning()) {
521 ALOGV("[%s] We're not running --- no input buffer reported", mName);
522 return;
523 }
524 feedInputBufferIfAvailableInternal();
525}
526
527void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800528 if (mInputMetEos ||
529 mReorderStash.lock()->hasPending() ||
530 mPipelineWatcher.lock()->pipelineFull()) {
531 return;
532 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700533 Mutexed<Output>::Locked output(mOutput);
534 if (output->buffers->numClientBuffers() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800535 return;
536 }
537 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700538 size_t numInputSlots = mInput.lock()->numSlots;
539 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800540 sp<MediaCodecBuffer> inBuffer;
541 size_t index;
542 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700543 Mutexed<Input>::Locked input(mInput);
544 if (input->buffers->numClientBuffers() >= input->numSlots) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800545 return;
546 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700547 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800548 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800549 break;
550 }
551 }
552 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
553 mCallback->onInputBufferAvailable(index, inBuffer);
554 }
555}
556
557status_t CCodecBufferChannel::renderOutputBuffer(
558 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800559 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800560 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800561 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800562 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700563 Mutexed<Output>::Locked output(mOutput);
564 if (output->buffers) {
565 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800566 }
567 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800568 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
569 // set to true.
570 sendOutputBuffers();
571 // input buffer feeding may have been gated by pending output buffers
572 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800573 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800574 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700575 std::call_once(mRenderWarningFlag, [this] {
576 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
577 "timestamp or render=true with non-video buffers. Apps should "
578 "call releaseOutputBuffer() with render=false for those.",
579 mName);
580 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800581 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800582 return INVALID_OPERATION;
583 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800584
585#if 0
586 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
587 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
588 for (const std::shared_ptr<const C2Info> &info : infoParams) {
589 AString res;
590 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
591 if (ix) res.append(", ");
592 res.append(*((int32_t*)info.get() + (ix / 4)));
593 }
594 ALOGV(" [%s]", res.c_str());
595 }
596#endif
597 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
598 std::static_pointer_cast<const C2StreamRotationInfo::output>(
599 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
600 bool flip = rotation && (rotation->flip & 1);
601 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
602 uint32_t transform = 0;
603 switch (quarters) {
604 case 0: // no rotation
605 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
606 break;
607 case 1: // 90 degrees counter-clockwise
608 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
609 : HAL_TRANSFORM_ROT_270;
610 break;
611 case 2: // 180 degrees
612 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
613 break;
614 case 3: // 90 degrees clockwise
615 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
616 : HAL_TRANSFORM_ROT_90;
617 break;
618 }
619
620 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
621 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
622 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
623 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
624 if (surfaceScaling) {
625 videoScalingMode = surfaceScaling->value;
626 }
627
628 // Use dataspace from format as it has the default aspects already applied
629 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
630 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
631
632 // HDR static info
633 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
634 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
635 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
636
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800637 // HDR10 plus info
638 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
639 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
640 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
641
Pawin Vongmasa36653902018-11-15 00:10:25 -0800642 {
643 Mutexed<OutputSurface>::Locked output(mOutputSurface);
644 if (output->surface == nullptr) {
645 ALOGI("[%s] cannot render buffer without surface", mName);
646 return OK;
647 }
648 }
649
650 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
651 if (blocks.size() != 1u) {
652 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
653 return UNKNOWN_ERROR;
654 }
655 const C2ConstGraphicBlock &block = blocks.front();
656
657 // TODO: revisit this after C2Fence implementation.
658 android::IGraphicBufferProducer::QueueBufferInput qbi(
659 timestampNs,
660 false, // droppable
661 dataSpace,
662 Rect(blocks.front().crop().left,
663 blocks.front().crop().top,
664 blocks.front().crop().right(),
665 blocks.front().crop().bottom()),
666 videoScalingMode,
667 transform,
668 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800669 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800670 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800671 if (hdrStaticInfo) {
672 struct android_smpte2086_metadata smpte2086_meta = {
673 .displayPrimaryRed = {
674 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
675 },
676 .displayPrimaryGreen = {
677 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
678 },
679 .displayPrimaryBlue = {
680 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
681 },
682 .whitePoint = {
683 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
684 },
685 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
686 .minLuminance = hdrStaticInfo->mastering.minLuminance,
687 };
688
689 struct android_cta861_3_metadata cta861_meta = {
690 .maxContentLightLevel = hdrStaticInfo->maxCll,
691 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
692 };
693
694 hdr.validTypes = HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3;
695 hdr.smpte2086 = smpte2086_meta;
696 hdr.cta8613 = cta861_meta;
697 }
698 if (hdr10PlusInfo) {
699 hdr.validTypes |= HdrMetadata::HDR10PLUS;
700 hdr.hdr10plus.assign(
701 hdr10PlusInfo->m.value,
702 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
703 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800704 qbi.setHdrMetadata(hdr);
705 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800706 // we don't have dirty regions
707 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800708 android::IGraphicBufferProducer::QueueBufferOutput qbo;
709 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
710 if (result != OK) {
711 ALOGI("[%s] queueBuffer failed: %d", mName, result);
712 return result;
713 }
714 ALOGV("[%s] queue buffer successful", mName);
715
716 int64_t mediaTimeUs = 0;
717 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
718 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
719
720 return OK;
721}
722
723status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
724 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
725 bool released = false;
726 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700727 Mutexed<Input>::Locked input(mInput);
728 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800729 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800730 }
731 }
732 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700733 Mutexed<Output>::Locked output(mOutput);
734 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800735 released = true;
736 }
737 }
738 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800739 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800740 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800741 } else {
742 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
743 }
744 return OK;
745}
746
747void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
748 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700749 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800750
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700751 if (!input->buffers->isArrayMode()) {
752 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800753 }
754
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700755 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800756}
757
758void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
759 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700760 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800761
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700762 if (!output->buffers->isArrayMode()) {
763 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800764 }
765
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700766 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800767}
768
769status_t CCodecBufferChannel::start(
770 const sp<AMessage> &inputFormat, const sp<AMessage> &outputFormat) {
771 C2StreamBufferTypeSetting::input iStreamFormat(0u);
772 C2StreamBufferTypeSetting::output oStreamFormat(0u);
773 C2PortReorderBufferDepthTuning::output reorderDepth;
774 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800775 C2PortActualDelayTuning::input inputDelay(0);
776 C2PortActualDelayTuning::output outputDelay(0);
777 C2ActualPipelineDelayTuning pipelineDelay(0);
778
Pawin Vongmasa36653902018-11-15 00:10:25 -0800779 c2_status_t err = mComponent->query(
780 {
781 &iStreamFormat,
782 &oStreamFormat,
783 &reorderDepth,
784 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800785 &inputDelay,
786 &pipelineDelay,
787 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800788 },
789 {},
790 C2_DONT_BLOCK,
791 nullptr);
792 if (err == C2_BAD_INDEX) {
793 if (!iStreamFormat || !oStreamFormat) {
794 return UNKNOWN_ERROR;
795 }
796 } else if (err != C2_OK) {
797 return UNKNOWN_ERROR;
798 }
799
800 {
801 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
802 reorder->clear();
803 if (reorderDepth) {
804 reorder->setDepth(reorderDepth.value);
805 }
806 if (reorderKey) {
807 reorder->setKey(reorderKey.value);
808 }
809 }
Wonsik Kim078b58e2019-01-09 15:08:06 -0800810
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800811 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
812 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
813 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
814
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700815 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
816 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800817
Pawin Vongmasa36653902018-11-15 00:10:25 -0800818 // TODO: get this from input format
819 bool secure = mComponent->getName().find(".secure") != std::string::npos;
820
821 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
822 int poolMask = property_get_int32(
823 "debug.stagefright.c2-poolmask",
824 1 << C2PlatformAllocatorStore::ION |
825 1 << C2PlatformAllocatorStore::BUFFERQUEUE);
826
827 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800828 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800829 std::shared_ptr<C2BlockPool> pool;
830 {
831 Mutexed<BlockPools>::Locked pools(mBlockPools);
832
833 // set default allocator ID.
834 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
835 : C2PlatformAllocatorStore::ION;
836
837 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
838 // from component, create the input block pool with given ID. Otherwise, use default IDs.
839 std::vector<std::unique_ptr<C2Param>> params;
840 err = mComponent->query({ },
841 { C2PortAllocatorsTuning::input::PARAM_TYPE },
842 C2_DONT_BLOCK,
843 &params);
844 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
845 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
846 mName, params.size(), asString(err), err);
847 } else if (err == C2_OK && params.size() == 1) {
848 C2PortAllocatorsTuning::input *inputAllocators =
849 C2PortAllocatorsTuning::input::From(params[0].get());
850 if (inputAllocators && inputAllocators->flexCount() > 0) {
851 std::shared_ptr<C2Allocator> allocator;
852 // verify allocator IDs and resolve default allocator
853 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
854 if (allocator) {
855 pools->inputAllocatorId = allocator->getId();
856 } else {
857 ALOGD("[%s] component requested invalid input allocator ID %u",
858 mName, inputAllocators->m.values[0]);
859 }
860 }
861 }
862
863 // TODO: use C2Component wrapper to associate this pool with ourselves
864 if ((poolMask >> pools->inputAllocatorId) & 1) {
865 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
866 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
867 mName, pools->inputAllocatorId,
868 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
869 asString(err), err);
870 } else {
871 err = C2_NOT_FOUND;
872 }
873 if (err != C2_OK) {
874 C2BlockPool::local_id_t inputPoolId =
875 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
876 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
877 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
878 mName, (unsigned long long)inputPoolId,
879 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
880 asString(err), err);
881 if (err != C2_OK) {
882 return NO_MEMORY;
883 }
884 }
885 pools->inputPool = pool;
886 }
887
Wonsik Kim51051262018-11-28 13:59:05 -0800888 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700889 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -0700890 input->inputDelay = inputDelayValue;
891 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700892 input->numSlots = numInputSlots;
893 input->extraBuffers.flush();
894 input->numExtraSlots = 0u;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800895 if (graphic) {
896 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700897 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800898 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700899 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -0700900 // This is to ensure buffers do not get released prematurely.
901 // TODO: handle this without going into array mode
902 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800903 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700904 input->buffers.reset(new GraphicInputBuffers(numInputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800905 }
906 } else {
907 if (hasCryptoOrDescrambler()) {
908 int32_t capacity = kLinearBufferSize;
909 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
910 if ((size_t)capacity > kMaxLinearBufferSize) {
911 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
912 capacity = kMaxLinearBufferSize;
913 }
914 if (mDealer == nullptr) {
915 mDealer = new MemoryDealer(
916 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700917 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800918 "EncryptedLinearInputBuffers");
919 mDecryptDestination = mDealer->allocate((size_t)capacity);
920 }
921 if (mCrypto != nullptr && mHeapSeqNum < 0) {
922 mHeapSeqNum = mCrypto->setHeap(mDealer->getMemoryHeap());
923 } else {
924 mHeapSeqNum = -1;
925 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700926 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -0800927 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700928 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -0800929 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800930 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700931 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800932 }
933 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700934 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800935
936 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700937 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800938 } else {
939 // TODO: error
940 }
Wonsik Kim51051262018-11-28 13:59:05 -0800941
942 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700943 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -0800944 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800945 }
946
947 if (outputFormat != nullptr) {
948 sp<IGraphicBufferProducer> outputSurface;
949 uint32_t outputGeneration;
950 {
951 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Lee7a7b7422019-07-16 17:40:40 -0700952 output->maxDequeueBuffers = numOutputSlots + numInputSlots +
953 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800954 outputSurface = output->surface ?
955 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -0800956 if (outputSurface) {
957 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
958 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800959 outputGeneration = output->generation;
960 }
961
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800962 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800963 C2BlockPool::local_id_t outputPoolId_;
964
965 {
966 Mutexed<BlockPools>::Locked pools(mBlockPools);
967
968 // set default allocator ID.
969 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
970 : C2PlatformAllocatorStore::ION;
971
972 // query C2PortAllocatorsTuning::output from component, or use default allocator if
973 // unsuccessful.
974 std::vector<std::unique_ptr<C2Param>> params;
975 err = mComponent->query({ },
976 { C2PortAllocatorsTuning::output::PARAM_TYPE },
977 C2_DONT_BLOCK,
978 &params);
979 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
980 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
981 mName, params.size(), asString(err), err);
982 } else if (err == C2_OK && params.size() == 1) {
983 C2PortAllocatorsTuning::output *outputAllocators =
984 C2PortAllocatorsTuning::output::From(params[0].get());
985 if (outputAllocators && outputAllocators->flexCount() > 0) {
986 std::shared_ptr<C2Allocator> allocator;
987 // verify allocator IDs and resolve default allocator
988 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
989 if (allocator) {
990 pools->outputAllocatorId = allocator->getId();
991 } else {
992 ALOGD("[%s] component requested invalid output allocator ID %u",
993 mName, outputAllocators->m.values[0]);
994 }
995 }
996 }
997
998 // use bufferqueue if outputting to a surface.
999 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1000 // if unsuccessful.
1001 if (outputSurface) {
1002 params.clear();
1003 err = mComponent->query({ },
1004 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1005 C2_DONT_BLOCK,
1006 &params);
1007 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1008 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1009 mName, params.size(), asString(err), err);
1010 } else if (err == C2_OK && params.size() == 1) {
1011 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1012 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1013 if (surfaceAllocator) {
1014 std::shared_ptr<C2Allocator> allocator;
1015 // verify allocator IDs and resolve default allocator
1016 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1017 if (allocator) {
1018 pools->outputAllocatorId = allocator->getId();
1019 } else {
1020 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1021 mName, surfaceAllocator->value);
1022 err = C2_BAD_VALUE;
1023 }
1024 }
1025 }
1026 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1027 && err != C2_OK
1028 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1029 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1030 }
1031 }
1032
1033 if ((poolMask >> pools->outputAllocatorId) & 1) {
1034 err = mComponent->createBlockPool(
1035 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1036 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1037 mName, pools->outputAllocatorId,
1038 (unsigned long long)pools->outputPoolId,
1039 asString(err));
1040 } else {
1041 err = C2_NOT_FOUND;
1042 }
1043 if (err != C2_OK) {
1044 // use basic pool instead
1045 pools->outputPoolId =
1046 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1047 }
1048
1049 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1050 // component.
1051 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1052 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1053
1054 std::vector<std::unique_ptr<C2SettingResult>> failures;
1055 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1056 ALOGD("[%s] Configured output block pool ids %llu => %s",
1057 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1058 outputPoolId_ = pools->outputPoolId;
1059 }
1060
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001061 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001062 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001063 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001064 if (graphic) {
1065 if (outputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001066 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001067 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001068 output->buffers.reset(new RawGraphicOutputBuffers(numOutputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001069 }
1070 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001071 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001072 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001073 output->buffers->setFormat(outputFormat->dup());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001074
1075
1076 // Try to set output surface to created block pool if given.
1077 if (outputSurface) {
1078 mComponent->setOutputSurface(
1079 outputPoolId_,
1080 outputSurface,
1081 outputGeneration);
1082 }
1083
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001084 if (oStreamFormat.value == C2BufferData::LINEAR) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001085 // WORKAROUND: if we're using early CSD workaround we convert to
1086 // array mode, to appease apps assuming the output
1087 // buffers to be of the same size.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001088 output->buffers = output->buffers->toArrayMode(numOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001089
1090 int32_t channelCount;
1091 int32_t sampleRate;
1092 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1093 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1094 int32_t delay = 0;
1095 int32_t padding = 0;;
1096 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1097 delay = 0;
1098 }
1099 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1100 padding = 0;
1101 }
1102 if (delay || padding) {
1103 // We need write access to the buffers, and we're already in
1104 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001105 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001106 }
1107 }
1108 }
1109 }
1110
1111 // Set up pipeline control. This has to be done after mInputBuffers and
1112 // mOutputBuffers are initialized to make sure that lingering callbacks
1113 // about buffers from the previous generation do not interfere with the
1114 // newly initialized pipeline capacity.
1115
Wonsik Kimab34ed62019-01-31 15:28:46 -08001116 {
1117 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001118 watcher->inputDelay(inputDelayValue)
1119 .pipelineDelay(pipelineDelayValue)
1120 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001121 .smoothnessFactor(kSmoothnessFactor);
1122 watcher->flush();
1123 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001124
1125 mInputMetEos = false;
1126 mSync.start();
1127 return OK;
1128}
1129
1130status_t CCodecBufferChannel::requestInitialInputBuffers() {
1131 if (mInputSurface) {
1132 return OK;
1133 }
1134
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001135 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001136 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1137 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1138 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001139 return UNKNOWN_ERROR;
1140 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001141 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001142 std::vector<sp<MediaCodecBuffer>> toBeQueued;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001143 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001144 size_t index;
1145 sp<MediaCodecBuffer> buffer;
1146 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001147 Mutexed<Input>::Locked input(mInput);
1148 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001149 if (i == 0) {
1150 ALOGW("[%s] start: cannot allocate memory at all", mName);
1151 return NO_MEMORY;
1152 } else {
1153 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
1154 mName, i);
1155 }
1156 break;
1157 }
1158 }
1159 if (buffer) {
1160 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1161 ALOGV("[%s] input buffer %zu available", mName, index);
1162 bool post = true;
1163 if (!configs->empty()) {
1164 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001165 configs->pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001166 if (buffer->capacity() >= config->size()) {
1167 memcpy(buffer->base(), config->data(), config->size());
1168 buffer->setRange(0, config->size());
1169 buffer->meta()->clear();
1170 buffer->meta()->setInt64("timeUs", 0);
1171 buffer->meta()->setInt32("csd", 1);
1172 post = false;
1173 } else {
1174 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
1175 mName, buffer->capacity(), config->size());
1176 }
1177 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001178 && (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001179 // WORKAROUND: Some apps expect CSD available without queueing
1180 // any input. Queue an empty buffer to get the CSD.
1181 buffer->setRange(0, 0);
1182 buffer->meta()->clear();
1183 buffer->meta()->setInt64("timeUs", 0);
1184 post = false;
1185 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001186 if (post) {
1187 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001188 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001189 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001190 }
1191 }
1192 }
1193 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
1194 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001195 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001196 }
1197 }
1198 return OK;
1199}
1200
1201void CCodecBufferChannel::stop() {
1202 mSync.stop();
1203 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1204 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001205 mInputSurface.reset();
1206 }
1207}
1208
1209void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1210 ALOGV("[%s] flush", mName);
1211 {
1212 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1213 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1214 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1215 continue;
1216 }
1217 if (work->input.buffers.empty()
1218 || work->input.buffers.front()->data().linearBlocks().empty()) {
1219 ALOGD("[%s] no linear codec config data found", mName);
1220 continue;
1221 }
1222 C2ReadView view =
1223 work->input.buffers.front()->data().linearBlocks().front().map().get();
1224 if (view.error() != C2_OK) {
1225 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1226 continue;
1227 }
1228 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1229 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1230 }
1231 }
1232 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001233 Mutexed<Input>::Locked input(mInput);
1234 input->buffers->flush();
1235 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001236 }
1237 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001238 Mutexed<Output>::Locked output(mOutput);
1239 output->buffers->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001240 }
Wonsik Kim6897f222019-01-30 13:29:24 -08001241 mReorderStash.lock()->flush();
Wonsik Kimab34ed62019-01-31 15:28:46 -08001242 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001243}
1244
1245void CCodecBufferChannel::onWorkDone(
1246 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001247 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001248 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001249 feedInputBufferIfAvailable();
1250 }
1251}
1252
1253void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001254 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001255 if (mInputSurface) {
1256 return;
1257 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001258 std::shared_ptr<C2Buffer> buffer =
1259 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001260 bool newInputSlotAvailable;
1261 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001262 Mutexed<Input>::Locked input(mInput);
1263 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1264 if (!newInputSlotAvailable) {
1265 (void)input->extraBuffers.expireComponentBuffer(buffer);
1266 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001267 }
1268 if (newInputSlotAvailable) {
1269 feedInputBufferIfAvailable();
1270 }
1271}
1272
1273bool CCodecBufferChannel::handleWork(
1274 std::unique_ptr<C2Work> work,
1275 const sp<AMessage> &outputFormat,
1276 const C2StreamInitDataInfo::output *initData) {
1277 if ((work->input.ordinal.frameIndex - mFirstValidFrameIndex.load()).peek() < 0) {
1278 // Discard frames from previous generation.
1279 ALOGD("[%s] Discard frames from previous generation.", mName);
1280 return false;
1281 }
1282
Wonsik Kim524b0582019-03-12 11:28:57 -07001283 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001284 || !work->worklets.front()
Wonsik Kim524b0582019-03-12 11:28:57 -07001285 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE))) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001286 mPipelineWatcher.lock()->onWorkDone(work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001287 }
1288
1289 if (work->result == C2_NOT_FOUND) {
1290 ALOGD("[%s] flushed work; ignored.", mName);
1291 return true;
1292 }
1293
1294 if (work->result != C2_OK) {
1295 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1296 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1297 return false;
1298 }
1299
1300 // NOTE: MediaCodec usage supposedly have only one worklet
1301 if (work->worklets.size() != 1u) {
1302 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1303 mName, work->worklets.size());
1304 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1305 return false;
1306 }
1307
1308 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1309
1310 std::shared_ptr<C2Buffer> buffer;
1311 // NOTE: MediaCodec usage supposedly have only one output stream.
1312 if (worklet->output.buffers.size() > 1u) {
1313 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1314 mName, worklet->output.buffers.size());
1315 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1316 return false;
1317 } else if (worklet->output.buffers.size() == 1u) {
1318 buffer = worklet->output.buffers[0];
1319 if (!buffer) {
1320 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1321 }
1322 }
1323
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001324 std::optional<uint32_t> newInputDelay, newPipelineDelay;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001325 while (!worklet->output.configUpdate.empty()) {
1326 std::unique_ptr<C2Param> param;
1327 worklet->output.configUpdate.back().swap(param);
1328 worklet->output.configUpdate.pop_back();
1329 switch (param->coreIndex().coreIndex()) {
1330 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1331 C2PortReorderBufferDepthTuning::output reorderDepth;
1332 if (reorderDepth.updateFrom(*param)) {
1333 mReorderStash.lock()->setDepth(reorderDepth.value);
1334 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1335 mName, reorderDepth.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001336 size_t numOutputSlots = mOutput.lock()->numSlots;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001337 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001338 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001339 output->maxDequeueBuffers = numOutputSlots + numInputSlots +
1340 reorderDepth.value + kRenderingDepth;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001341 if (output->surface) {
1342 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1343 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001344 } else {
1345 ALOGD("[%s] onWorkDone: failed to read reorder depth", mName);
1346 }
1347 break;
1348 }
1349 case C2PortReorderKeySetting::CORE_INDEX: {
1350 C2PortReorderKeySetting::output reorderKey;
1351 if (reorderKey.updateFrom(*param)) {
1352 mReorderStash.lock()->setKey(reorderKey.value);
1353 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1354 mName, reorderKey.value);
1355 } else {
1356 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1357 }
1358 break;
1359 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001360 case C2PortActualDelayTuning::CORE_INDEX: {
1361 if (param->isGlobal()) {
1362 C2ActualPipelineDelayTuning pipelineDelay;
1363 if (pipelineDelay.updateFrom(*param)) {
1364 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1365 mName, pipelineDelay.value);
1366 newPipelineDelay = pipelineDelay.value;
1367 (void)mPipelineWatcher.lock()->pipelineDelay(pipelineDelay.value);
1368 }
1369 }
1370 if (param->forInput()) {
1371 C2PortActualDelayTuning::input inputDelay;
1372 if (inputDelay.updateFrom(*param)) {
1373 ALOGV("[%s] onWorkDone: updating input delay %u",
1374 mName, inputDelay.value);
1375 newInputDelay = inputDelay.value;
1376 (void)mPipelineWatcher.lock()->inputDelay(inputDelay.value);
1377 }
1378 }
1379 if (param->forOutput()) {
1380 C2PortActualDelayTuning::output outputDelay;
1381 if (outputDelay.updateFrom(*param)) {
1382 ALOGV("[%s] onWorkDone: updating output delay %u",
1383 mName, outputDelay.value);
1384 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
1385
1386 bool outputBuffersChanged = false;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001387 size_t numOutputSlots = 0;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001388 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001389 {
1390 Mutexed<Output>::Locked output(mOutput);
1391 output->outputDelay = outputDelay.value;
1392 numOutputSlots = outputDelay.value + kSmoothnessFactor;
1393 if (output->numSlots < numOutputSlots) {
1394 output->numSlots = numOutputSlots;
1395 if (output->buffers->isArrayMode()) {
1396 OutputBuffersArray *array =
1397 (OutputBuffersArray *)output->buffers.get();
1398 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1399 mName, numOutputSlots);
1400 array->grow(numOutputSlots);
1401 outputBuffersChanged = true;
1402 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001403 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001404 numOutputSlots = output->numSlots;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001405 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001406
1407 if (outputBuffersChanged) {
1408 mCCodecCallback->onOutputBuffersChanged();
1409 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001410
1411 uint32_t depth = mReorderStash.lock()->depth();
1412 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001413 output->maxDequeueBuffers = numOutputSlots + numInputSlots +
1414 depth + kRenderingDepth;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001415 if (output->surface) {
1416 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1417 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001418 }
1419 }
1420 break;
1421 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001422 default:
1423 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1424 mName, param->index());
1425 break;
1426 }
1427 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001428 if (newInputDelay || newPipelineDelay) {
1429 Mutexed<Input>::Locked input(mInput);
1430 size_t newNumSlots =
1431 newInputDelay.value_or(input->inputDelay) +
1432 newPipelineDelay.value_or(input->pipelineDelay) +
1433 kSmoothnessFactor;
1434 if (input->buffers->isArrayMode()) {
1435 if (input->numSlots >= newNumSlots) {
1436 input->numExtraSlots = 0;
1437 } else {
1438 input->numExtraSlots = newNumSlots - input->numSlots;
1439 }
1440 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1441 mName, input->numExtraSlots);
1442 } else {
1443 input->numSlots = newNumSlots;
1444 }
1445 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001446
1447 if (outputFormat != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001448 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001449 ALOGD("[%s] onWorkDone: output format changed to %s",
1450 mName, outputFormat->debugString().c_str());
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001451 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001452
1453 AString mediaType;
1454 if (outputFormat->findString(KEY_MIME, &mediaType)
1455 && mediaType == MIMETYPE_AUDIO_RAW) {
1456 int32_t channelCount;
1457 int32_t sampleRate;
1458 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1459 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001460 output->buffers->updateSkipCutBuffer(sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001461 }
1462 }
1463 }
1464
1465 int32_t flags = 0;
1466 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1467 flags |= MediaCodec::BUFFER_FLAG_EOS;
1468 ALOGV("[%s] onWorkDone: output EOS", mName);
1469 }
1470
1471 sp<MediaCodecBuffer> outBuffer;
1472 size_t index;
1473
1474 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1475 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1476 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1477 // shall correspond to the client input timesamp (in customOrdinal). By using the
1478 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1479 // produces multiple output.
1480 c2_cntr64_t timestamp =
1481 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1482 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001483 if (mInputSurface != nullptr) {
1484 // When using input surface we need to restore the original input timestamp.
1485 timestamp = work->input.ordinal.customOrdinal;
1486 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001487 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1488 mName,
1489 work->input.ordinal.customOrdinal.peekll(),
1490 work->input.ordinal.timestamp.peekll(),
1491 worklet->output.ordinal.timestamp.peekll(),
1492 timestamp.peekll());
1493
1494 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001495 Mutexed<Output>::Locked output(mOutput);
1496 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001497 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1498 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1499 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1500
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001501 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001502 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001503 } else {
1504 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001505 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001506 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001507 return false;
1508 }
1509 }
1510
1511 if (!buffer && !flags) {
1512 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1513 mName, work->input.ordinal.frameIndex.peekull());
1514 return true;
1515 }
1516
1517 if (buffer) {
1518 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1519 // TODO: properly translate these to metadata
1520 switch (info->coreIndex().coreIndex()) {
1521 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001522 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001523 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1524 }
1525 break;
1526 default:
1527 break;
1528 }
1529 }
1530 }
1531
1532 {
1533 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1534 reorder->emplace(buffer, timestamp.peek(), flags, worklet->output.ordinal);
1535 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
1536 // Flush reorder stash
1537 reorder->setDepth(0);
1538 }
1539 }
1540 sendOutputBuffers();
1541 return true;
1542}
1543
1544void CCodecBufferChannel::sendOutputBuffers() {
1545 ReorderStash::Entry entry;
1546 sp<MediaCodecBuffer> outBuffer;
1547 size_t index;
1548
1549 while (true) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001550 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1551 if (!reorder->hasPending()) {
1552 break;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001553 }
Wonsik Kim38ad3412019-02-01 15:13:23 -08001554 if (!reorder->pop(&entry)) {
1555 break;
1556 }
1557
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001558 Mutexed<Output>::Locked output(mOutput);
1559 status_t err = output->buffers->registerBuffer(entry.buffer, &index, &outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001560 if (err != OK) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001561 bool outputBuffersChanged = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001562 if (err != WOULD_BLOCK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001563 if (!output->buffers->isArrayMode()) {
1564 output->buffers = output->buffers->toArrayMode(output->numSlots);
Wonsik Kim186fdbf2019-01-29 13:30:01 -08001565 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001566 OutputBuffersArray *array = (OutputBuffersArray *)output->buffers.get();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001567 array->realloc(entry.buffer);
Wonsik Kim38ad3412019-02-01 15:13:23 -08001568 outputBuffersChanged = true;
1569 }
1570 ALOGV("[%s] sendOutputBuffers: unable to register output buffer", mName);
1571 reorder->defer(entry);
1572
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001573 output.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08001574 reorder.unlock();
1575
1576 if (outputBuffersChanged) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001577 mCCodecCallback->onOutputBuffersChanged();
1578 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001579 return;
1580 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001581 output.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08001582 reorder.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001583
1584 outBuffer->meta()->setInt64("timeUs", entry.timestamp);
1585 outBuffer->meta()->setInt32("flags", entry.flags);
Wonsik Kim66427432019-03-21 15:06:22 -07001586 ALOGV("[%s] sendOutputBuffers: out buffer index = %zu [%p] => %p + %zu (%lld)",
1587 mName, index, outBuffer.get(), outBuffer->data(), outBuffer->size(),
1588 (long long)entry.timestamp);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001589 mCallback->onOutputBufferAvailable(index, outBuffer);
1590 }
1591}
1592
1593status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1594 static std::atomic_uint32_t surfaceGeneration{0};
1595 uint32_t generation = (getpid() << 10) |
1596 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1597 & ((1 << 10) - 1));
1598
1599 sp<IGraphicBufferProducer> producer;
1600 if (newSurface) {
1601 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001602 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Lee08515812019-06-05 11:16:32 -07001603 newSurface->setMaxDequeuedBufferCount(mOutputSurface.lock()->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001604 producer = newSurface->getIGraphicBufferProducer();
1605 producer->setGenerationNumber(generation);
1606 } else {
1607 ALOGE("[%s] setting output surface to null", mName);
1608 return INVALID_OPERATION;
1609 }
1610
1611 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1612 C2BlockPool::local_id_t outputPoolId;
1613 {
1614 Mutexed<BlockPools>::Locked pools(mBlockPools);
1615 outputPoolId = pools->outputPoolId;
1616 outputPoolIntf = pools->outputPoolIntf;
1617 }
1618
1619 if (outputPoolIntf) {
1620 if (mComponent->setOutputSurface(
1621 outputPoolId,
1622 producer,
1623 generation) != C2_OK) {
1624 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1625 return INVALID_OPERATION;
1626 }
1627 }
1628
1629 {
1630 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1631 output->surface = newSurface;
1632 output->generation = generation;
1633 }
1634
1635 return OK;
1636}
1637
Wonsik Kimab34ed62019-01-31 15:28:46 -08001638PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001639 // When client pushed EOS, we want all the work to be done quickly.
1640 // Otherwise, component may have stalled work due to input starvation up to
1641 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001642 size_t n = 0;
1643 if (!mInputMetEos) {
1644 size_t outputDelay = mOutput.lock()->outputDelay;
1645 Mutexed<Input>::Locked input(mInput);
1646 n = input->inputDelay + input->pipelineDelay + outputDelay;
1647 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001648 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001649}
1650
Pawin Vongmasa36653902018-11-15 00:10:25 -08001651void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1652 mMetaMode = mode;
1653}
1654
1655status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1656 // C2_OK is always translated to OK.
1657 if (c2s == C2_OK) {
1658 return OK;
1659 }
1660
1661 // Operation-dependent translation
1662 // TODO: Add as necessary
1663 switch (c2op) {
1664 case C2_OPERATION_Component_start:
1665 switch (c2s) {
1666 case C2_NO_MEMORY:
1667 return NO_MEMORY;
1668 default:
1669 return UNKNOWN_ERROR;
1670 }
1671 default:
1672 break;
1673 }
1674
1675 // Backup operation-agnostic translation
1676 switch (c2s) {
1677 case C2_BAD_INDEX:
1678 return BAD_INDEX;
1679 case C2_BAD_VALUE:
1680 return BAD_VALUE;
1681 case C2_BLOCKING:
1682 return WOULD_BLOCK;
1683 case C2_DUPLICATE:
1684 return ALREADY_EXISTS;
1685 case C2_NO_INIT:
1686 return NO_INIT;
1687 case C2_NO_MEMORY:
1688 return NO_MEMORY;
1689 case C2_NOT_FOUND:
1690 return NAME_NOT_FOUND;
1691 case C2_TIMED_OUT:
1692 return TIMED_OUT;
1693 case C2_BAD_STATE:
1694 case C2_CANCELED:
1695 case C2_CANNOT_DO:
1696 case C2_CORRUPTED:
1697 case C2_OMITTED:
1698 case C2_REFUSED:
1699 return UNKNOWN_ERROR;
1700 default:
1701 return -static_cast<status_t>(c2s);
1702 }
1703}
1704
1705} // namespace android