blob: 0cbf62bb1b0888a80d34ba4af9b109c527c350d4 [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
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700213// Input
214
215CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
216
Pawin Vongmasa36653902018-11-15 00:10:25 -0800217// CCodecBufferChannel
218
219CCodecBufferChannel::CCodecBufferChannel(
220 const std::shared_ptr<CCodecCallback> &callback)
221 : mHeapSeqNum(-1),
222 mCCodecCallback(callback),
223 mFrameIndex(0u),
224 mFirstValidFrameIndex(0u),
225 mMetaMode(MODE_NONE),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800226 mInputMetEos(false) {
Sungtak Leee151ed62019-07-16 17:40:40 -0700227 mOutputSurface.lock()->maxDequeueBuffers = 2 * kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700228 {
229 Mutexed<Input>::Locked input(mInput);
230 input->buffers.reset(new DummyInputBuffers(""));
231 input->extraBuffers.flush();
232 input->inputDelay = 0u;
233 input->pipelineDelay = 0u;
234 input->numSlots = kSmoothnessFactor;
235 input->numExtraSlots = 0u;
236 }
237 {
238 Mutexed<Output>::Locked output(mOutput);
239 output->outputDelay = 0u;
240 output->numSlots = kSmoothnessFactor;
241 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800242}
243
244CCodecBufferChannel::~CCodecBufferChannel() {
245 if (mCrypto != nullptr && mDealer != nullptr && mHeapSeqNum >= 0) {
246 mCrypto->unsetHeap(mHeapSeqNum);
247 }
248}
249
250void CCodecBufferChannel::setComponent(
251 const std::shared_ptr<Codec2Client::Component> &component) {
252 mComponent = component;
253 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
254 mName = mComponentName.c_str();
255}
256
257status_t CCodecBufferChannel::setInputSurface(
258 const std::shared_ptr<InputSurfaceWrapper> &surface) {
259 ALOGV("[%s] setInputSurface", mName);
260 mInputSurface = surface;
261 return mInputSurface->connect(mComponent);
262}
263
264status_t CCodecBufferChannel::signalEndOfInputStream() {
265 if (mInputSurface == nullptr) {
266 return INVALID_OPERATION;
267 }
268 return mInputSurface->signalEndOfInputStream();
269}
270
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700271status_t CCodecBufferChannel::queueInputBufferInternal(sp<MediaCodecBuffer> buffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800272 int64_t timeUs;
273 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
274
275 if (mInputMetEos) {
276 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
277 return OK;
278 }
279
280 int32_t flags = 0;
281 int32_t tmp = 0;
282 bool eos = false;
283 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
284 eos = true;
285 mInputMetEos = true;
286 ALOGV("[%s] input EOS", mName);
287 }
288 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
289 flags |= C2FrameData::FLAG_CODEC_CONFIG;
290 }
291 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
292 std::unique_ptr<C2Work> work(new C2Work);
293 work->input.ordinal.timestamp = timeUs;
294 work->input.ordinal.frameIndex = mFrameIndex++;
295 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
296 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
297 // Keep client timestamp in customOrdinal
298 work->input.ordinal.customOrdinal = timeUs;
299 work->input.buffers.clear();
300
Wonsik Kimab34ed62019-01-31 15:28:46 -0800301 uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
302 std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700303 sp<Codec2Buffer> copy;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800304
Pawin Vongmasa36653902018-11-15 00:10:25 -0800305 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700306 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800307 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700308 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800309 return -ENOENT;
310 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700311 // TODO: we want to delay copying buffers.
312 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
313 copy = input->buffers->cloneAndReleaseBuffer(buffer);
314 if (copy != nullptr) {
315 (void)input->extraBuffers.assignSlot(copy);
316 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
317 return UNKNOWN_ERROR;
318 }
319 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
320 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
321 mName, released ? "" : "not ");
322 buffer.clear();
323 } else {
324 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
325 "buffer starvation on component.", mName);
326 }
327 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800328 work->input.buffers.push_back(c2buffer);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800329 queuedBuffers.push_back(c2buffer);
330 } else if (eos) {
331 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800332 }
333 work->input.flags = (C2FrameData::flags_t)flags;
334 // TODO: fill info's
335
336 work->input.configUpdate = std::move(mParamsToBeSet);
337 work->worklets.clear();
338 work->worklets.emplace_back(new C2Worklet);
339
340 std::list<std::unique_ptr<C2Work>> items;
341 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800342 mPipelineWatcher.lock()->onWorkQueued(
343 queuedFrameIndex,
344 std::move(queuedBuffers),
345 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800346 c2_status_t err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800347 if (err != C2_OK) {
348 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
349 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800350
351 if (err == C2_OK && eos && buffer->size() > 0u) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800352 work.reset(new C2Work);
353 work->input.ordinal.timestamp = timeUs;
354 work->input.ordinal.frameIndex = mFrameIndex++;
355 // WORKAROUND: keep client timestamp in customOrdinal
356 work->input.ordinal.customOrdinal = timeUs;
357 work->input.buffers.clear();
358 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800359 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800360
Wonsik Kimab34ed62019-01-31 15:28:46 -0800361 queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
362 queuedBuffers.clear();
363
Pawin Vongmasa36653902018-11-15 00:10:25 -0800364 items.clear();
365 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800366
367 mPipelineWatcher.lock()->onWorkQueued(
368 queuedFrameIndex,
369 std::move(queuedBuffers),
370 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800371 err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800372 if (err != C2_OK) {
373 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
374 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800375 }
376 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700377 Mutexed<Input>::Locked input(mInput);
378 bool released = false;
379 if (buffer) {
380 released = input->buffers->releaseBuffer(buffer, nullptr, true);
381 } else if (copy) {
382 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
383 }
384 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
385 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800386 }
387
388 feedInputBufferIfAvailableInternal();
389 return err;
390}
391
392status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
393 QueueGuard guard(mSync);
394 if (!guard.isRunning()) {
395 ALOGD("[%s] setParameters is only supported in the running state.", mName);
396 return -ENOSYS;
397 }
398 mParamsToBeSet.insert(mParamsToBeSet.end(),
399 std::make_move_iterator(params.begin()),
400 std::make_move_iterator(params.end()));
401 params.clear();
402 return OK;
403}
404
405status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
406 QueueGuard guard(mSync);
407 if (!guard.isRunning()) {
408 ALOGD("[%s] No more buffers should be queued at current state.", mName);
409 return -ENOSYS;
410 }
411 return queueInputBufferInternal(buffer);
412}
413
414status_t CCodecBufferChannel::queueSecureInputBuffer(
415 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
416 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
417 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
418 AString *errorDetailMsg) {
419 QueueGuard guard(mSync);
420 if (!guard.isRunning()) {
421 ALOGD("[%s] No more buffers should be queued at current state.", mName);
422 return -ENOSYS;
423 }
424
425 if (!hasCryptoOrDescrambler()) {
426 return -ENOSYS;
427 }
428 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
429
430 ssize_t result = -1;
431 ssize_t codecDataOffset = 0;
432 if (mCrypto != nullptr) {
433 ICrypto::DestinationBuffer destination;
434 if (secure) {
435 destination.mType = ICrypto::kDestinationTypeNativeHandle;
436 destination.mHandle = encryptedBuffer->handle();
437 } else {
438 destination.mType = ICrypto::kDestinationTypeSharedMemory;
439 destination.mSharedMemory = mDecryptDestination;
440 }
441 ICrypto::SourceBuffer source;
442 encryptedBuffer->fillSourceBuffer(&source);
443 result = mCrypto->decrypt(
444 key, iv, mode, pattern, source, buffer->offset(),
445 subSamples, numSubSamples, destination, errorDetailMsg);
446 if (result < 0) {
447 return result;
448 }
449 if (destination.mType == ICrypto::kDestinationTypeSharedMemory) {
450 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
451 }
452 } else {
453 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
454 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
455 hidl_vec<SubSample> hidlSubSamples;
456 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
457
458 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
459 encryptedBuffer->fillSourceBuffer(&srcBuffer);
460
461 DestinationBuffer dstBuffer;
462 if (secure) {
463 dstBuffer.type = BufferType::NATIVE_HANDLE;
464 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
465 } else {
466 dstBuffer.type = BufferType::SHARED_MEMORY;
467 dstBuffer.nonsecureMemory = srcBuffer;
468 }
469
470 CasStatus status = CasStatus::OK;
471 hidl_string detailedError;
472 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
473
474 if (key != nullptr) {
475 sctrl = (ScramblingControl)key[0];
476 // Adjust for the PES offset
477 codecDataOffset = key[2] | (key[3] << 8);
478 }
479
480 auto returnVoid = mDescrambler->descramble(
481 sctrl,
482 hidlSubSamples,
483 srcBuffer,
484 0,
485 dstBuffer,
486 0,
487 [&status, &result, &detailedError] (
488 CasStatus _status, uint32_t _bytesWritten,
489 const hidl_string& _detailedError) {
490 status = _status;
491 result = (ssize_t)_bytesWritten;
492 detailedError = _detailedError;
493 });
494
495 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
496 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
497 mName, returnVoid.description().c_str(), status, result);
498 return UNKNOWN_ERROR;
499 }
500
501 if (result < codecDataOffset) {
502 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
503 return BAD_VALUE;
504 }
505
506 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
507
508 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
509 encryptedBuffer->copyDecryptedContentFromMemory(result);
510 }
511 }
512
513 buffer->setRange(codecDataOffset, result - codecDataOffset);
514 return queueInputBufferInternal(buffer);
515}
516
517void CCodecBufferChannel::feedInputBufferIfAvailable() {
518 QueueGuard guard(mSync);
519 if (!guard.isRunning()) {
520 ALOGV("[%s] We're not running --- no input buffer reported", mName);
521 return;
522 }
523 feedInputBufferIfAvailableInternal();
524}
525
526void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800527 if (mInputMetEos ||
528 mReorderStash.lock()->hasPending() ||
529 mPipelineWatcher.lock()->pipelineFull()) {
530 return;
531 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700532 Mutexed<Output>::Locked output(mOutput);
533 if (output->buffers->numClientBuffers() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800534 return;
535 }
536 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700537 size_t numInputSlots = mInput.lock()->numSlots;
538 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800539 sp<MediaCodecBuffer> inBuffer;
540 size_t index;
541 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700542 Mutexed<Input>::Locked input(mInput);
543 if (input->buffers->numClientBuffers() >= input->numSlots) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800544 return;
545 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700546 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800547 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800548 break;
549 }
550 }
551 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
552 mCallback->onInputBufferAvailable(index, inBuffer);
553 }
554}
555
556status_t CCodecBufferChannel::renderOutputBuffer(
557 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800558 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800559 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800560 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800561 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700562 Mutexed<Output>::Locked output(mOutput);
563 if (output->buffers) {
564 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800565 }
566 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800567 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
568 // set to true.
569 sendOutputBuffers();
570 // input buffer feeding may have been gated by pending output buffers
571 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800572 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800573 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700574 std::call_once(mRenderWarningFlag, [this] {
575 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
576 "timestamp or render=true with non-video buffers. Apps should "
577 "call releaseOutputBuffer() with render=false for those.",
578 mName);
579 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800580 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800581 return INVALID_OPERATION;
582 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800583
584#if 0
585 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
586 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
587 for (const std::shared_ptr<const C2Info> &info : infoParams) {
588 AString res;
589 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
590 if (ix) res.append(", ");
591 res.append(*((int32_t*)info.get() + (ix / 4)));
592 }
593 ALOGV(" [%s]", res.c_str());
594 }
595#endif
596 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
597 std::static_pointer_cast<const C2StreamRotationInfo::output>(
598 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
599 bool flip = rotation && (rotation->flip & 1);
600 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
601 uint32_t transform = 0;
602 switch (quarters) {
603 case 0: // no rotation
604 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
605 break;
606 case 1: // 90 degrees counter-clockwise
607 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
608 : HAL_TRANSFORM_ROT_270;
609 break;
610 case 2: // 180 degrees
611 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
612 break;
613 case 3: // 90 degrees clockwise
614 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
615 : HAL_TRANSFORM_ROT_90;
616 break;
617 }
618
619 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
620 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
621 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
622 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
623 if (surfaceScaling) {
624 videoScalingMode = surfaceScaling->value;
625 }
626
627 // Use dataspace from format as it has the default aspects already applied
628 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
629 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
630
631 // HDR static info
632 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
633 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
634 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
635
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800636 // HDR10 plus info
637 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
638 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
639 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
640
Pawin Vongmasa36653902018-11-15 00:10:25 -0800641 {
642 Mutexed<OutputSurface>::Locked output(mOutputSurface);
643 if (output->surface == nullptr) {
644 ALOGI("[%s] cannot render buffer without surface", mName);
645 return OK;
646 }
647 }
648
649 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
650 if (blocks.size() != 1u) {
651 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
652 return UNKNOWN_ERROR;
653 }
654 const C2ConstGraphicBlock &block = blocks.front();
655
656 // TODO: revisit this after C2Fence implementation.
657 android::IGraphicBufferProducer::QueueBufferInput qbi(
658 timestampNs,
659 false, // droppable
660 dataSpace,
661 Rect(blocks.front().crop().left,
662 blocks.front().crop().top,
663 blocks.front().crop().right(),
664 blocks.front().crop().bottom()),
665 videoScalingMode,
666 transform,
667 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800668 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800669 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800670 if (hdrStaticInfo) {
671 struct android_smpte2086_metadata smpte2086_meta = {
672 .displayPrimaryRed = {
673 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
674 },
675 .displayPrimaryGreen = {
676 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
677 },
678 .displayPrimaryBlue = {
679 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
680 },
681 .whitePoint = {
682 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
683 },
684 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
685 .minLuminance = hdrStaticInfo->mastering.minLuminance,
686 };
687
688 struct android_cta861_3_metadata cta861_meta = {
689 .maxContentLightLevel = hdrStaticInfo->maxCll,
690 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
691 };
692
693 hdr.validTypes = HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3;
694 hdr.smpte2086 = smpte2086_meta;
695 hdr.cta8613 = cta861_meta;
696 }
697 if (hdr10PlusInfo) {
698 hdr.validTypes |= HdrMetadata::HDR10PLUS;
699 hdr.hdr10plus.assign(
700 hdr10PlusInfo->m.value,
701 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
702 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800703 qbi.setHdrMetadata(hdr);
704 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800705 // we don't have dirty regions
706 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800707 android::IGraphicBufferProducer::QueueBufferOutput qbo;
708 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
709 if (result != OK) {
710 ALOGI("[%s] queueBuffer failed: %d", mName, result);
711 return result;
712 }
713 ALOGV("[%s] queue buffer successful", mName);
714
715 int64_t mediaTimeUs = 0;
716 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
717 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
718
719 return OK;
720}
721
722status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
723 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
724 bool released = false;
725 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700726 Mutexed<Input>::Locked input(mInput);
727 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800728 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800729 }
730 }
731 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700732 Mutexed<Output>::Locked output(mOutput);
733 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800734 released = true;
735 }
736 }
737 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800738 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800739 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800740 } else {
741 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
742 }
743 return OK;
744}
745
746void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
747 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700748 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800749
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700750 if (!input->buffers->isArrayMode()) {
751 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800752 }
753
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700754 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800755}
756
757void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
758 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700759 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800760
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700761 if (!output->buffers->isArrayMode()) {
762 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800763 }
764
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700765 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800766}
767
768status_t CCodecBufferChannel::start(
769 const sp<AMessage> &inputFormat, const sp<AMessage> &outputFormat) {
770 C2StreamBufferTypeSetting::input iStreamFormat(0u);
771 C2StreamBufferTypeSetting::output oStreamFormat(0u);
772 C2PortReorderBufferDepthTuning::output reorderDepth;
773 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800774 C2PortActualDelayTuning::input inputDelay(0);
775 C2PortActualDelayTuning::output outputDelay(0);
776 C2ActualPipelineDelayTuning pipelineDelay(0);
777
Pawin Vongmasa36653902018-11-15 00:10:25 -0800778 c2_status_t err = mComponent->query(
779 {
780 &iStreamFormat,
781 &oStreamFormat,
782 &reorderDepth,
783 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800784 &inputDelay,
785 &pipelineDelay,
786 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800787 },
788 {},
789 C2_DONT_BLOCK,
790 nullptr);
791 if (err == C2_BAD_INDEX) {
792 if (!iStreamFormat || !oStreamFormat) {
793 return UNKNOWN_ERROR;
794 }
795 } else if (err != C2_OK) {
796 return UNKNOWN_ERROR;
797 }
798
799 {
800 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
801 reorder->clear();
802 if (reorderDepth) {
803 reorder->setDepth(reorderDepth.value);
804 }
805 if (reorderKey) {
806 reorder->setKey(reorderKey.value);
807 }
808 }
Wonsik Kim078b58e2019-01-09 15:08:06 -0800809
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800810 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
811 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
812 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
813
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700814 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
815 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800816
Pawin Vongmasa36653902018-11-15 00:10:25 -0800817 // TODO: get this from input format
818 bool secure = mComponent->getName().find(".secure") != std::string::npos;
819
820 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
821 int poolMask = property_get_int32(
822 "debug.stagefright.c2-poolmask",
823 1 << C2PlatformAllocatorStore::ION |
824 1 << C2PlatformAllocatorStore::BUFFERQUEUE);
825
826 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800827 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800828 std::shared_ptr<C2BlockPool> pool;
829 {
830 Mutexed<BlockPools>::Locked pools(mBlockPools);
831
832 // set default allocator ID.
833 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
834 : C2PlatformAllocatorStore::ION;
835
836 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
837 // from component, create the input block pool with given ID. Otherwise, use default IDs.
838 std::vector<std::unique_ptr<C2Param>> params;
839 err = mComponent->query({ },
840 { C2PortAllocatorsTuning::input::PARAM_TYPE },
841 C2_DONT_BLOCK,
842 &params);
843 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
844 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
845 mName, params.size(), asString(err), err);
846 } else if (err == C2_OK && params.size() == 1) {
847 C2PortAllocatorsTuning::input *inputAllocators =
848 C2PortAllocatorsTuning::input::From(params[0].get());
849 if (inputAllocators && inputAllocators->flexCount() > 0) {
850 std::shared_ptr<C2Allocator> allocator;
851 // verify allocator IDs and resolve default allocator
852 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
853 if (allocator) {
854 pools->inputAllocatorId = allocator->getId();
855 } else {
856 ALOGD("[%s] component requested invalid input allocator ID %u",
857 mName, inputAllocators->m.values[0]);
858 }
859 }
860 }
861
862 // TODO: use C2Component wrapper to associate this pool with ourselves
863 if ((poolMask >> pools->inputAllocatorId) & 1) {
864 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
865 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
866 mName, pools->inputAllocatorId,
867 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
868 asString(err), err);
869 } else {
870 err = C2_NOT_FOUND;
871 }
872 if (err != C2_OK) {
873 C2BlockPool::local_id_t inputPoolId =
874 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
875 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
876 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
877 mName, (unsigned long long)inputPoolId,
878 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
879 asString(err), err);
880 if (err != C2_OK) {
881 return NO_MEMORY;
882 }
883 }
884 pools->inputPool = pool;
885 }
886
Wonsik Kim51051262018-11-28 13:59:05 -0800887 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700888 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -0700889 input->inputDelay = inputDelayValue;
890 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700891 input->numSlots = numInputSlots;
892 input->extraBuffers.flush();
893 input->numExtraSlots = 0u;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800894 if (graphic) {
895 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700896 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800897 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700898 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -0700899 // This is to ensure buffers do not get released prematurely.
900 // TODO: handle this without going into array mode
901 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800902 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700903 input->buffers.reset(new GraphicInputBuffers(numInputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800904 }
905 } else {
906 if (hasCryptoOrDescrambler()) {
907 int32_t capacity = kLinearBufferSize;
908 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
909 if ((size_t)capacity > kMaxLinearBufferSize) {
910 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
911 capacity = kMaxLinearBufferSize;
912 }
913 if (mDealer == nullptr) {
914 mDealer = new MemoryDealer(
915 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700916 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800917 "EncryptedLinearInputBuffers");
918 mDecryptDestination = mDealer->allocate((size_t)capacity);
919 }
920 if (mCrypto != nullptr && mHeapSeqNum < 0) {
921 mHeapSeqNum = mCrypto->setHeap(mDealer->getMemoryHeap());
922 } else {
923 mHeapSeqNum = -1;
924 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700925 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -0800926 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700927 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -0800928 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800929 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700930 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800931 }
932 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700933 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800934
935 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700936 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800937 } else {
938 // TODO: error
939 }
Wonsik Kim51051262018-11-28 13:59:05 -0800940
941 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700942 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -0800943 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800944 }
945
946 if (outputFormat != nullptr) {
947 sp<IGraphicBufferProducer> outputSurface;
948 uint32_t outputGeneration;
949 {
950 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leee151ed62019-07-16 17:40:40 -0700951 output->maxDequeueBuffers = numOutputSlots + numInputSlots +
952 reorderDepth.value + kRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800953 outputSurface = output->surface ?
954 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -0800955 if (outputSurface) {
956 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
957 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800958 outputGeneration = output->generation;
959 }
960
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800961 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800962 C2BlockPool::local_id_t outputPoolId_;
963
964 {
965 Mutexed<BlockPools>::Locked pools(mBlockPools);
966
967 // set default allocator ID.
968 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
969 : C2PlatformAllocatorStore::ION;
970
971 // query C2PortAllocatorsTuning::output from component, or use default allocator if
972 // unsuccessful.
973 std::vector<std::unique_ptr<C2Param>> params;
974 err = mComponent->query({ },
975 { C2PortAllocatorsTuning::output::PARAM_TYPE },
976 C2_DONT_BLOCK,
977 &params);
978 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
979 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
980 mName, params.size(), asString(err), err);
981 } else if (err == C2_OK && params.size() == 1) {
982 C2PortAllocatorsTuning::output *outputAllocators =
983 C2PortAllocatorsTuning::output::From(params[0].get());
984 if (outputAllocators && outputAllocators->flexCount() > 0) {
985 std::shared_ptr<C2Allocator> allocator;
986 // verify allocator IDs and resolve default allocator
987 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
988 if (allocator) {
989 pools->outputAllocatorId = allocator->getId();
990 } else {
991 ALOGD("[%s] component requested invalid output allocator ID %u",
992 mName, outputAllocators->m.values[0]);
993 }
994 }
995 }
996
997 // use bufferqueue if outputting to a surface.
998 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
999 // if unsuccessful.
1000 if (outputSurface) {
1001 params.clear();
1002 err = mComponent->query({ },
1003 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1004 C2_DONT_BLOCK,
1005 &params);
1006 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1007 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1008 mName, params.size(), asString(err), err);
1009 } else if (err == C2_OK && params.size() == 1) {
1010 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1011 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1012 if (surfaceAllocator) {
1013 std::shared_ptr<C2Allocator> allocator;
1014 // verify allocator IDs and resolve default allocator
1015 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1016 if (allocator) {
1017 pools->outputAllocatorId = allocator->getId();
1018 } else {
1019 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1020 mName, surfaceAllocator->value);
1021 err = C2_BAD_VALUE;
1022 }
1023 }
1024 }
1025 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1026 && err != C2_OK
1027 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1028 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1029 }
1030 }
1031
1032 if ((poolMask >> pools->outputAllocatorId) & 1) {
1033 err = mComponent->createBlockPool(
1034 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1035 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1036 mName, pools->outputAllocatorId,
1037 (unsigned long long)pools->outputPoolId,
1038 asString(err));
1039 } else {
1040 err = C2_NOT_FOUND;
1041 }
1042 if (err != C2_OK) {
1043 // use basic pool instead
1044 pools->outputPoolId =
1045 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1046 }
1047
1048 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1049 // component.
1050 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1051 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1052
1053 std::vector<std::unique_ptr<C2SettingResult>> failures;
1054 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1055 ALOGD("[%s] Configured output block pool ids %llu => %s",
1056 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1057 outputPoolId_ = pools->outputPoolId;
1058 }
1059
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001060 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001061 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001062 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001063 if (graphic) {
1064 if (outputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001065 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001066 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001067 output->buffers.reset(new RawGraphicOutputBuffers(numOutputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001068 }
1069 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001070 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001071 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001072 output->buffers->setFormat(outputFormat->dup());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001073
1074
1075 // Try to set output surface to created block pool if given.
1076 if (outputSurface) {
1077 mComponent->setOutputSurface(
1078 outputPoolId_,
1079 outputSurface,
1080 outputGeneration);
1081 }
1082
1083 if (oStreamFormat.value == C2BufferData::LINEAR
1084 && mComponentName.find("c2.qti.") == std::string::npos) {
1085 // 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);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001136 c2_status_t err = mComponent->query({ &oStreamFormat }, {}, C2_DONT_BLOCK, nullptr);
1137 if (err != C2_OK) {
1138 return UNKNOWN_ERROR;
1139 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001140 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001141 std::vector<sp<MediaCodecBuffer>> toBeQueued;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001142 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001143 size_t index;
1144 sp<MediaCodecBuffer> buffer;
1145 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001146 Mutexed<Input>::Locked input(mInput);
1147 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001148 if (i == 0) {
1149 ALOGW("[%s] start: cannot allocate memory at all", mName);
1150 return NO_MEMORY;
1151 } else {
1152 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
1153 mName, i);
1154 }
1155 break;
1156 }
1157 }
1158 if (buffer) {
1159 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1160 ALOGV("[%s] input buffer %zu available", mName, index);
1161 bool post = true;
1162 if (!configs->empty()) {
1163 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001164 configs->pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001165 if (buffer->capacity() >= config->size()) {
1166 memcpy(buffer->base(), config->data(), config->size());
1167 buffer->setRange(0, config->size());
1168 buffer->meta()->clear();
1169 buffer->meta()->setInt64("timeUs", 0);
1170 buffer->meta()->setInt32("csd", 1);
1171 post = false;
1172 } else {
1173 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
1174 mName, buffer->capacity(), config->size());
1175 }
1176 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
1177 && mComponentName.find("c2.qti.") == std::string::npos) {
1178 // WORKAROUND: Some apps expect CSD available without queueing
1179 // any input. Queue an empty buffer to get the CSD.
1180 buffer->setRange(0, 0);
1181 buffer->meta()->clear();
1182 buffer->meta()->setInt64("timeUs", 0);
1183 post = false;
1184 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001185 if (post) {
1186 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001187 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001188 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001189 }
1190 }
1191 }
1192 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
1193 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001194 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001195 }
1196 }
1197 return OK;
1198}
1199
1200void CCodecBufferChannel::stop() {
1201 mSync.stop();
1202 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1203 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001204 mInputSurface.reset();
1205 }
1206}
1207
1208void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1209 ALOGV("[%s] flush", mName);
1210 {
1211 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1212 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1213 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1214 continue;
1215 }
1216 if (work->input.buffers.empty()
1217 || work->input.buffers.front()->data().linearBlocks().empty()) {
1218 ALOGD("[%s] no linear codec config data found", mName);
1219 continue;
1220 }
1221 C2ReadView view =
1222 work->input.buffers.front()->data().linearBlocks().front().map().get();
1223 if (view.error() != C2_OK) {
1224 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1225 continue;
1226 }
1227 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1228 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1229 }
1230 }
1231 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001232 Mutexed<Input>::Locked input(mInput);
1233 input->buffers->flush();
1234 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001235 }
1236 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001237 Mutexed<Output>::Locked output(mOutput);
1238 output->buffers->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001239 }
Wonsik Kim6897f222019-01-30 13:29:24 -08001240 mReorderStash.lock()->flush();
Wonsik Kimab34ed62019-01-31 15:28:46 -08001241 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001242}
1243
1244void CCodecBufferChannel::onWorkDone(
1245 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001246 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001247 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001248 feedInputBufferIfAvailable();
1249 }
1250}
1251
1252void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001253 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001254 if (mInputSurface) {
1255 return;
1256 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001257 std::shared_ptr<C2Buffer> buffer =
1258 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001259 bool newInputSlotAvailable;
1260 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001261 Mutexed<Input>::Locked input(mInput);
1262 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1263 if (!newInputSlotAvailable) {
1264 (void)input->extraBuffers.expireComponentBuffer(buffer);
1265 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001266 }
1267 if (newInputSlotAvailable) {
1268 feedInputBufferIfAvailable();
1269 }
1270}
1271
1272bool CCodecBufferChannel::handleWork(
1273 std::unique_ptr<C2Work> work,
1274 const sp<AMessage> &outputFormat,
1275 const C2StreamInitDataInfo::output *initData) {
1276 if ((work->input.ordinal.frameIndex - mFirstValidFrameIndex.load()).peek() < 0) {
1277 // Discard frames from previous generation.
1278 ALOGD("[%s] Discard frames from previous generation.", mName);
1279 return false;
1280 }
1281
Wonsik Kim524b0582019-03-12 11:28:57 -07001282 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001283 || !work->worklets.front()
Wonsik Kim524b0582019-03-12 11:28:57 -07001284 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE))) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001285 mPipelineWatcher.lock()->onWorkDone(work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001286 }
1287
1288 if (work->result == C2_NOT_FOUND) {
1289 ALOGD("[%s] flushed work; ignored.", mName);
1290 return true;
1291 }
1292
1293 if (work->result != C2_OK) {
1294 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1295 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1296 return false;
1297 }
1298
1299 // NOTE: MediaCodec usage supposedly have only one worklet
1300 if (work->worklets.size() != 1u) {
1301 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1302 mName, work->worklets.size());
1303 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1304 return false;
1305 }
1306
1307 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1308
1309 std::shared_ptr<C2Buffer> buffer;
1310 // NOTE: MediaCodec usage supposedly have only one output stream.
1311 if (worklet->output.buffers.size() > 1u) {
1312 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1313 mName, worklet->output.buffers.size());
1314 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1315 return false;
1316 } else if (worklet->output.buffers.size() == 1u) {
1317 buffer = worklet->output.buffers[0];
1318 if (!buffer) {
1319 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1320 }
1321 }
1322
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001323 std::optional<uint32_t> newInputDelay, newPipelineDelay;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001324 while (!worklet->output.configUpdate.empty()) {
1325 std::unique_ptr<C2Param> param;
1326 worklet->output.configUpdate.back().swap(param);
1327 worklet->output.configUpdate.pop_back();
1328 switch (param->coreIndex().coreIndex()) {
1329 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1330 C2PortReorderBufferDepthTuning::output reorderDepth;
1331 if (reorderDepth.updateFrom(*param)) {
1332 mReorderStash.lock()->setDepth(reorderDepth.value);
1333 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1334 mName, reorderDepth.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001335 size_t numOutputSlots = mOutput.lock()->numSlots;
Sungtak Leee151ed62019-07-16 17:40:40 -07001336 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001337 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leee151ed62019-07-16 17:40:40 -07001338 output->maxDequeueBuffers = numOutputSlots + numInputSlots +
1339 reorderDepth.value + kRenderingDepth;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001340 if (output->surface) {
1341 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1342 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001343 } else {
1344 ALOGD("[%s] onWorkDone: failed to read reorder depth", mName);
1345 }
1346 break;
1347 }
1348 case C2PortReorderKeySetting::CORE_INDEX: {
1349 C2PortReorderKeySetting::output reorderKey;
1350 if (reorderKey.updateFrom(*param)) {
1351 mReorderStash.lock()->setKey(reorderKey.value);
1352 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1353 mName, reorderKey.value);
1354 } else {
1355 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1356 }
1357 break;
1358 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001359 case C2PortActualDelayTuning::CORE_INDEX: {
1360 if (param->isGlobal()) {
1361 C2ActualPipelineDelayTuning pipelineDelay;
1362 if (pipelineDelay.updateFrom(*param)) {
1363 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1364 mName, pipelineDelay.value);
1365 newPipelineDelay = pipelineDelay.value;
1366 (void)mPipelineWatcher.lock()->pipelineDelay(pipelineDelay.value);
1367 }
1368 }
1369 if (param->forInput()) {
1370 C2PortActualDelayTuning::input inputDelay;
1371 if (inputDelay.updateFrom(*param)) {
1372 ALOGV("[%s] onWorkDone: updating input delay %u",
1373 mName, inputDelay.value);
1374 newInputDelay = inputDelay.value;
1375 (void)mPipelineWatcher.lock()->inputDelay(inputDelay.value);
1376 }
1377 }
1378 if (param->forOutput()) {
1379 C2PortActualDelayTuning::output outputDelay;
1380 if (outputDelay.updateFrom(*param)) {
1381 ALOGV("[%s] onWorkDone: updating output delay %u",
1382 mName, outputDelay.value);
1383 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
1384
1385 bool outputBuffersChanged = false;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001386 size_t numOutputSlots = 0;
Sungtak Leee151ed62019-07-16 17:40:40 -07001387 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001388 {
1389 Mutexed<Output>::Locked output(mOutput);
1390 output->outputDelay = outputDelay.value;
1391 numOutputSlots = outputDelay.value + kSmoothnessFactor;
1392 if (output->numSlots < numOutputSlots) {
1393 output->numSlots = numOutputSlots;
1394 if (output->buffers->isArrayMode()) {
1395 OutputBuffersArray *array =
1396 (OutputBuffersArray *)output->buffers.get();
1397 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1398 mName, numOutputSlots);
1399 array->grow(numOutputSlots);
1400 outputBuffersChanged = true;
1401 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001402 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001403 numOutputSlots = output->numSlots;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001404 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001405
1406 if (outputBuffersChanged) {
1407 mCCodecCallback->onOutputBuffersChanged();
1408 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001409
1410 uint32_t depth = mReorderStash.lock()->depth();
1411 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leee151ed62019-07-16 17:40:40 -07001412 output->maxDequeueBuffers = numOutputSlots + numInputSlots +
1413 depth + kRenderingDepth;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001414 if (output->surface) {
1415 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1416 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001417 }
1418 }
1419 break;
1420 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001421 default:
1422 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1423 mName, param->index());
1424 break;
1425 }
1426 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001427 if (newInputDelay || newPipelineDelay) {
1428 Mutexed<Input>::Locked input(mInput);
1429 size_t newNumSlots =
1430 newInputDelay.value_or(input->inputDelay) +
1431 newPipelineDelay.value_or(input->pipelineDelay) +
1432 kSmoothnessFactor;
1433 if (input->buffers->isArrayMode()) {
1434 if (input->numSlots >= newNumSlots) {
1435 input->numExtraSlots = 0;
1436 } else {
1437 input->numExtraSlots = newNumSlots - input->numSlots;
1438 }
1439 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1440 mName, input->numExtraSlots);
1441 } else {
1442 input->numSlots = newNumSlots;
1443 }
1444 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001445
1446 if (outputFormat != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001447 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001448 ALOGD("[%s] onWorkDone: output format changed to %s",
1449 mName, outputFormat->debugString().c_str());
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001450 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001451
1452 AString mediaType;
1453 if (outputFormat->findString(KEY_MIME, &mediaType)
1454 && mediaType == MIMETYPE_AUDIO_RAW) {
1455 int32_t channelCount;
1456 int32_t sampleRate;
1457 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1458 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001459 output->buffers->updateSkipCutBuffer(sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001460 }
1461 }
1462 }
1463
1464 int32_t flags = 0;
1465 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1466 flags |= MediaCodec::BUFFER_FLAG_EOS;
1467 ALOGV("[%s] onWorkDone: output EOS", mName);
1468 }
1469
1470 sp<MediaCodecBuffer> outBuffer;
1471 size_t index;
1472
1473 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1474 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1475 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1476 // shall correspond to the client input timesamp (in customOrdinal). By using the
1477 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1478 // produces multiple output.
1479 c2_cntr64_t timestamp =
1480 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1481 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001482 if (mInputSurface != nullptr) {
1483 // When using input surface we need to restore the original input timestamp.
1484 timestamp = work->input.ordinal.customOrdinal;
1485 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001486 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1487 mName,
1488 work->input.ordinal.customOrdinal.peekll(),
1489 work->input.ordinal.timestamp.peekll(),
1490 worklet->output.ordinal.timestamp.peekll(),
1491 timestamp.peekll());
1492
1493 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001494 Mutexed<Output>::Locked output(mOutput);
1495 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001496 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1497 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1498 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1499
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001500 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001501 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001502 } else {
1503 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001504 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001505 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001506 return false;
1507 }
1508 }
1509
1510 if (!buffer && !flags) {
1511 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1512 mName, work->input.ordinal.frameIndex.peekull());
1513 return true;
1514 }
1515
1516 if (buffer) {
1517 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1518 // TODO: properly translate these to metadata
1519 switch (info->coreIndex().coreIndex()) {
1520 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001521 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001522 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1523 }
1524 break;
1525 default:
1526 break;
1527 }
1528 }
1529 }
1530
1531 {
1532 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1533 reorder->emplace(buffer, timestamp.peek(), flags, worklet->output.ordinal);
1534 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
1535 // Flush reorder stash
1536 reorder->setDepth(0);
1537 }
1538 }
1539 sendOutputBuffers();
1540 return true;
1541}
1542
1543void CCodecBufferChannel::sendOutputBuffers() {
1544 ReorderStash::Entry entry;
1545 sp<MediaCodecBuffer> outBuffer;
1546 size_t index;
1547
1548 while (true) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001549 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1550 if (!reorder->hasPending()) {
1551 break;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001552 }
Wonsik Kim38ad3412019-02-01 15:13:23 -08001553 if (!reorder->pop(&entry)) {
1554 break;
1555 }
1556
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001557 Mutexed<Output>::Locked output(mOutput);
1558 status_t err = output->buffers->registerBuffer(entry.buffer, &index, &outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001559 if (err != OK) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001560 bool outputBuffersChanged = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001561 if (err != WOULD_BLOCK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001562 if (!output->buffers->isArrayMode()) {
1563 output->buffers = output->buffers->toArrayMode(output->numSlots);
Wonsik Kim186fdbf2019-01-29 13:30:01 -08001564 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001565 OutputBuffersArray *array = (OutputBuffersArray *)output->buffers.get();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001566 array->realloc(entry.buffer);
Wonsik Kim38ad3412019-02-01 15:13:23 -08001567 outputBuffersChanged = true;
1568 }
1569 ALOGV("[%s] sendOutputBuffers: unable to register output buffer", mName);
1570 reorder->defer(entry);
1571
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001572 output.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08001573 reorder.unlock();
1574
1575 if (outputBuffersChanged) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001576 mCCodecCallback->onOutputBuffersChanged();
1577 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001578 return;
1579 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001580 output.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08001581 reorder.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001582
1583 outBuffer->meta()->setInt64("timeUs", entry.timestamp);
1584 outBuffer->meta()->setInt32("flags", entry.flags);
Wonsik Kim66427432019-03-21 15:06:22 -07001585 ALOGV("[%s] sendOutputBuffers: out buffer index = %zu [%p] => %p + %zu (%lld)",
1586 mName, index, outBuffer.get(), outBuffer->data(), outBuffer->size(),
1587 (long long)entry.timestamp);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001588 mCallback->onOutputBufferAvailable(index, outBuffer);
1589 }
1590}
1591
1592status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1593 static std::atomic_uint32_t surfaceGeneration{0};
1594 uint32_t generation = (getpid() << 10) |
1595 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1596 & ((1 << 10) - 1));
1597
1598 sp<IGraphicBufferProducer> producer;
1599 if (newSurface) {
1600 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001601 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Lee08515812019-06-05 11:16:32 -07001602 newSurface->setMaxDequeuedBufferCount(mOutputSurface.lock()->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001603 producer = newSurface->getIGraphicBufferProducer();
1604 producer->setGenerationNumber(generation);
1605 } else {
1606 ALOGE("[%s] setting output surface to null", mName);
1607 return INVALID_OPERATION;
1608 }
1609
1610 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1611 C2BlockPool::local_id_t outputPoolId;
1612 {
1613 Mutexed<BlockPools>::Locked pools(mBlockPools);
1614 outputPoolId = pools->outputPoolId;
1615 outputPoolIntf = pools->outputPoolIntf;
1616 }
1617
1618 if (outputPoolIntf) {
1619 if (mComponent->setOutputSurface(
1620 outputPoolId,
1621 producer,
1622 generation) != C2_OK) {
1623 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1624 return INVALID_OPERATION;
1625 }
1626 }
1627
1628 {
1629 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1630 output->surface = newSurface;
1631 output->generation = generation;
1632 }
1633
1634 return OK;
1635}
1636
Wonsik Kimab34ed62019-01-31 15:28:46 -08001637PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001638 // When client pushed EOS, we want all the work to be done quickly.
1639 // Otherwise, component may have stalled work due to input starvation up to
1640 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001641 size_t n = 0;
1642 if (!mInputMetEos) {
1643 size_t outputDelay = mOutput.lock()->outputDelay;
1644 Mutexed<Input>::Locked input(mInput);
1645 n = input->inputDelay + input->pipelineDelay + outputDelay;
1646 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001647 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001648}
1649
Pawin Vongmasa36653902018-11-15 00:10:25 -08001650void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1651 mMetaMode = mode;
1652}
1653
1654status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1655 // C2_OK is always translated to OK.
1656 if (c2s == C2_OK) {
1657 return OK;
1658 }
1659
1660 // Operation-dependent translation
1661 // TODO: Add as necessary
1662 switch (c2op) {
1663 case C2_OPERATION_Component_start:
1664 switch (c2s) {
1665 case C2_NO_MEMORY:
1666 return NO_MEMORY;
1667 default:
1668 return UNKNOWN_ERROR;
1669 }
1670 default:
1671 break;
1672 }
1673
1674 // Backup operation-agnostic translation
1675 switch (c2s) {
1676 case C2_BAD_INDEX:
1677 return BAD_INDEX;
1678 case C2_BAD_VALUE:
1679 return BAD_VALUE;
1680 case C2_BLOCKING:
1681 return WOULD_BLOCK;
1682 case C2_DUPLICATE:
1683 return ALREADY_EXISTS;
1684 case C2_NO_INIT:
1685 return NO_INIT;
1686 case C2_NO_MEMORY:
1687 return NO_MEMORY;
1688 case C2_NOT_FOUND:
1689 return NAME_NOT_FOUND;
1690 case C2_TIMED_OUT:
1691 return TIMED_OUT;
1692 case C2_BAD_STATE:
1693 case C2_CANCELED:
1694 case C2_CANNOT_DO:
1695 case C2_CORRUPTED:
1696 case C2_OMITTED:
1697 case C2_REFUSED:
1698 return UNKNOWN_ERROR;
1699 default:
1700 return -static_cast<status_t>(c2s);
1701 }
1702}
1703
1704} // namespace android