blob: 39f3f3596c855db23abb8cd4cfdd76a417bbc42c [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>
Robert Shih895fba92019-07-16 16:29:44 -070030#include <android/hardware/drm/1.0/types.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080031#include <android-base/stringprintf.h>
32#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070033#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080034#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070035#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080036#include <media/openmax/OMX_Core.h>
37#include <media/stagefright/foundation/ABuffer.h>
38#include <media/stagefright/foundation/ALookup.h>
39#include <media/stagefright/foundation/AMessage.h>
40#include <media/stagefright/foundation/AUtils.h>
41#include <media/stagefright/foundation/hexdump.h>
42#include <media/stagefright/MediaCodec.h>
43#include <media/stagefright/MediaCodecConstants.h>
44#include <media/MediaCodecBuffer.h>
45#include <system/window.h>
46
47#include "CCodecBufferChannel.h"
48#include "Codec2Buffer.h"
49#include "SkipCutBuffer.h"
50
51namespace android {
52
53using android::base::StringPrintf;
54using hardware::hidl_handle;
55using hardware::hidl_string;
56using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070057using hardware::fromHeap;
58using hardware::HidlMemory;
59
Pawin Vongmasa36653902018-11-15 00:10:25 -080060using namespace hardware::cas::V1_0;
61using namespace hardware::cas::native::V1_0;
62
63using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070064using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080065
Pawin Vongmasa36653902018-11-15 00:10:25 -080066namespace {
67
Wonsik Kim469c8342019-04-11 16:46:09 -070068constexpr size_t kSmoothnessFactor = 4;
69constexpr size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -080070
Sungtak Leeab6f2f32019-02-15 14:43:51 -080071// This is for keeping IGBP's buffer dropping logic in legacy mode other
72// than making it non-blocking. Do not change this value.
73const static size_t kDequeueTimeoutNs = 0;
74
Pawin Vongmasa36653902018-11-15 00:10:25 -080075} // namespace
76
77CCodecBufferChannel::QueueGuard::QueueGuard(
78 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
79 Mutex::Autolock l(mSync.mGuardLock);
80 // At this point it's guaranteed that mSync is not under state transition,
81 // as we are holding its mutex.
82
83 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
84 if (count->value == -1) {
85 mRunning = false;
86 } else {
87 ++count->value;
88 mRunning = true;
89 }
90}
91
92CCodecBufferChannel::QueueGuard::~QueueGuard() {
93 if (mRunning) {
94 // We are not holding mGuardLock at this point so that QueueSync::stop() can
95 // keep holding the lock until mCount reaches zero.
96 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
97 --count->value;
98 count->cond.broadcast();
99 }
100}
101
102void CCodecBufferChannel::QueueSync::start() {
103 Mutex::Autolock l(mGuardLock);
104 // If stopped, it goes to running state; otherwise no-op.
105 Mutexed<Counter>::Locked count(mCount);
106 if (count->value == -1) {
107 count->value = 0;
108 }
109}
110
111void CCodecBufferChannel::QueueSync::stop() {
112 Mutex::Autolock l(mGuardLock);
113 Mutexed<Counter>::Locked count(mCount);
114 if (count->value == -1) {
115 // no-op
116 return;
117 }
118 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
119 // mCount can only decrement. In other words, threads that acquired the lock
120 // are allowed to finish execution but additional threads trying to acquire
121 // the lock at this point will block, and then get QueueGuard at STOPPED
122 // state.
123 while (count->value != 0) {
124 count.waitForCondition(count->cond);
125 }
126 count->value = -1;
127}
128
Pawin Vongmasa36653902018-11-15 00:10:25 -0800129// CCodecBufferChannel::ReorderStash
130
131CCodecBufferChannel::ReorderStash::ReorderStash() {
132 clear();
133}
134
135void CCodecBufferChannel::ReorderStash::clear() {
136 mPending.clear();
137 mStash.clear();
138 mDepth = 0;
139 mKey = C2Config::ORDINAL;
140}
141
Wonsik Kim6897f222019-01-30 13:29:24 -0800142void CCodecBufferChannel::ReorderStash::flush() {
143 mPending.clear();
144 mStash.clear();
145}
146
Pawin Vongmasa36653902018-11-15 00:10:25 -0800147void CCodecBufferChannel::ReorderStash::setDepth(uint32_t depth) {
148 mPending.splice(mPending.end(), mStash);
149 mDepth = depth;
150}
Wonsik Kim66427432019-03-21 15:06:22 -0700151
Pawin Vongmasa36653902018-11-15 00:10:25 -0800152void CCodecBufferChannel::ReorderStash::setKey(C2Config::ordinal_key_t key) {
153 mPending.splice(mPending.end(), mStash);
154 mKey = key;
155}
156
157bool CCodecBufferChannel::ReorderStash::pop(Entry *entry) {
158 if (mPending.empty()) {
159 return false;
160 }
161 entry->buffer = mPending.front().buffer;
162 entry->timestamp = mPending.front().timestamp;
163 entry->flags = mPending.front().flags;
164 entry->ordinal = mPending.front().ordinal;
165 mPending.pop_front();
166 return true;
167}
168
169void CCodecBufferChannel::ReorderStash::emplace(
170 const std::shared_ptr<C2Buffer> &buffer,
171 int64_t timestamp,
172 int32_t flags,
173 const C2WorkOrdinalStruct &ordinal) {
Wonsik Kim66427432019-03-21 15:06:22 -0700174 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
175 if (!buffer && eos) {
176 // TRICKY: we may be violating ordering of the stash here. Because we
177 // don't expect any more emplace() calls after this, the ordering should
178 // not matter.
179 mStash.emplace_back(buffer, timestamp, flags, ordinal);
180 } else {
181 flags = flags & ~MediaCodec::BUFFER_FLAG_EOS;
182 auto it = mStash.begin();
183 for (; it != mStash.end(); ++it) {
184 if (less(ordinal, it->ordinal)) {
185 break;
186 }
187 }
188 mStash.emplace(it, buffer, timestamp, flags, ordinal);
189 if (eos) {
190 mStash.back().flags = mStash.back().flags | MediaCodec::BUFFER_FLAG_EOS;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800191 }
192 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800193 while (!mStash.empty() && mStash.size() > mDepth) {
194 mPending.push_back(mStash.front());
195 mStash.pop_front();
196 }
197}
198
199void CCodecBufferChannel::ReorderStash::defer(
200 const CCodecBufferChannel::ReorderStash::Entry &entry) {
201 mPending.push_front(entry);
202}
203
204bool CCodecBufferChannel::ReorderStash::hasPending() const {
205 return !mPending.empty();
206}
207
208bool CCodecBufferChannel::ReorderStash::less(
209 const C2WorkOrdinalStruct &o1, const C2WorkOrdinalStruct &o2) {
210 switch (mKey) {
211 case C2Config::ORDINAL: return o1.frameIndex < o2.frameIndex;
212 case C2Config::TIMESTAMP: return o1.timestamp < o2.timestamp;
213 case C2Config::CUSTOM: return o1.customOrdinal < o2.customOrdinal;
214 default:
215 ALOGD("Unrecognized key; default to timestamp");
216 return o1.frameIndex < o2.frameIndex;
217 }
218}
219
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700220// Input
221
222CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
223
Pawin Vongmasa36653902018-11-15 00:10:25 -0800224// CCodecBufferChannel
225
226CCodecBufferChannel::CCodecBufferChannel(
227 const std::shared_ptr<CCodecCallback> &callback)
228 : mHeapSeqNum(-1),
229 mCCodecCallback(callback),
230 mFrameIndex(0u),
231 mFirstValidFrameIndex(0u),
232 mMetaMode(MODE_NONE),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800233 mInputMetEos(false) {
Sungtak Leed7463d12019-09-04 16:01:00 -0700234 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700235 {
236 Mutexed<Input>::Locked input(mInput);
237 input->buffers.reset(new DummyInputBuffers(""));
238 input->extraBuffers.flush();
239 input->inputDelay = 0u;
240 input->pipelineDelay = 0u;
241 input->numSlots = kSmoothnessFactor;
242 input->numExtraSlots = 0u;
243 }
244 {
245 Mutexed<Output>::Locked output(mOutput);
246 output->outputDelay = 0u;
247 output->numSlots = kSmoothnessFactor;
248 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800249}
250
251CCodecBufferChannel::~CCodecBufferChannel() {
252 if (mCrypto != nullptr && mDealer != nullptr && mHeapSeqNum >= 0) {
253 mCrypto->unsetHeap(mHeapSeqNum);
254 }
255}
256
257void CCodecBufferChannel::setComponent(
258 const std::shared_ptr<Codec2Client::Component> &component) {
259 mComponent = component;
260 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
261 mName = mComponentName.c_str();
262}
263
264status_t CCodecBufferChannel::setInputSurface(
265 const std::shared_ptr<InputSurfaceWrapper> &surface) {
266 ALOGV("[%s] setInputSurface", mName);
267 mInputSurface = surface;
268 return mInputSurface->connect(mComponent);
269}
270
271status_t CCodecBufferChannel::signalEndOfInputStream() {
272 if (mInputSurface == nullptr) {
273 return INVALID_OPERATION;
274 }
275 return mInputSurface->signalEndOfInputStream();
276}
277
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700278status_t CCodecBufferChannel::queueInputBufferInternal(sp<MediaCodecBuffer> buffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800279 int64_t timeUs;
280 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
281
282 if (mInputMetEos) {
283 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
284 return OK;
285 }
286
287 int32_t flags = 0;
288 int32_t tmp = 0;
289 bool eos = false;
290 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
291 eos = true;
292 mInputMetEos = true;
293 ALOGV("[%s] input EOS", mName);
294 }
295 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
296 flags |= C2FrameData::FLAG_CODEC_CONFIG;
297 }
298 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
299 std::unique_ptr<C2Work> work(new C2Work);
300 work->input.ordinal.timestamp = timeUs;
301 work->input.ordinal.frameIndex = mFrameIndex++;
302 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
303 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
304 // Keep client timestamp in customOrdinal
305 work->input.ordinal.customOrdinal = timeUs;
306 work->input.buffers.clear();
307
Wonsik Kimab34ed62019-01-31 15:28:46 -0800308 uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
309 std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700310 sp<Codec2Buffer> copy;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800311
Pawin Vongmasa36653902018-11-15 00:10:25 -0800312 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700313 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800314 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700315 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800316 return -ENOENT;
317 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700318 // TODO: we want to delay copying buffers.
319 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
320 copy = input->buffers->cloneAndReleaseBuffer(buffer);
321 if (copy != nullptr) {
322 (void)input->extraBuffers.assignSlot(copy);
323 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
324 return UNKNOWN_ERROR;
325 }
326 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
327 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
328 mName, released ? "" : "not ");
329 buffer.clear();
330 } else {
331 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
332 "buffer starvation on component.", mName);
333 }
334 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800335 work->input.buffers.push_back(c2buffer);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800336 queuedBuffers.push_back(c2buffer);
337 } else if (eos) {
338 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800339 }
340 work->input.flags = (C2FrameData::flags_t)flags;
341 // TODO: fill info's
342
343 work->input.configUpdate = std::move(mParamsToBeSet);
344 work->worklets.clear();
345 work->worklets.emplace_back(new C2Worklet);
346
347 std::list<std::unique_ptr<C2Work>> items;
348 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800349 mPipelineWatcher.lock()->onWorkQueued(
350 queuedFrameIndex,
351 std::move(queuedBuffers),
352 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800353 c2_status_t err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800354 if (err != C2_OK) {
355 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
356 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800357
358 if (err == C2_OK && eos && buffer->size() > 0u) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800359 work.reset(new C2Work);
360 work->input.ordinal.timestamp = timeUs;
361 work->input.ordinal.frameIndex = mFrameIndex++;
362 // WORKAROUND: keep client timestamp in customOrdinal
363 work->input.ordinal.customOrdinal = timeUs;
364 work->input.buffers.clear();
365 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800366 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800367
Wonsik Kimab34ed62019-01-31 15:28:46 -0800368 queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
369 queuedBuffers.clear();
370
Pawin Vongmasa36653902018-11-15 00:10:25 -0800371 items.clear();
372 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -0800373
374 mPipelineWatcher.lock()->onWorkQueued(
375 queuedFrameIndex,
376 std::move(queuedBuffers),
377 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800378 err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -0800379 if (err != C2_OK) {
380 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
381 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800382 }
383 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700384 Mutexed<Input>::Locked input(mInput);
385 bool released = false;
386 if (buffer) {
387 released = input->buffers->releaseBuffer(buffer, nullptr, true);
388 } else if (copy) {
389 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
390 }
391 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
392 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800393 }
394
395 feedInputBufferIfAvailableInternal();
396 return err;
397}
398
399status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
400 QueueGuard guard(mSync);
401 if (!guard.isRunning()) {
402 ALOGD("[%s] setParameters is only supported in the running state.", mName);
403 return -ENOSYS;
404 }
405 mParamsToBeSet.insert(mParamsToBeSet.end(),
406 std::make_move_iterator(params.begin()),
407 std::make_move_iterator(params.end()));
408 params.clear();
409 return OK;
410}
411
412status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
413 QueueGuard guard(mSync);
414 if (!guard.isRunning()) {
415 ALOGD("[%s] No more buffers should be queued at current state.", mName);
416 return -ENOSYS;
417 }
418 return queueInputBufferInternal(buffer);
419}
420
421status_t CCodecBufferChannel::queueSecureInputBuffer(
422 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
423 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
424 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
425 AString *errorDetailMsg) {
426 QueueGuard guard(mSync);
427 if (!guard.isRunning()) {
428 ALOGD("[%s] No more buffers should be queued at current state.", mName);
429 return -ENOSYS;
430 }
431
432 if (!hasCryptoOrDescrambler()) {
433 return -ENOSYS;
434 }
435 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
436
437 ssize_t result = -1;
438 ssize_t codecDataOffset = 0;
439 if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700440 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800441 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700442 destination.type = DrmBufferType::NATIVE_HANDLE;
443 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800444 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700445 destination.type = DrmBufferType::SHARED_MEMORY;
446 IMemoryToSharedBuffer(
447 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800448 }
Robert Shih895fba92019-07-16 16:29:44 -0700449 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800450 encryptedBuffer->fillSourceBuffer(&source);
451 result = mCrypto->decrypt(
452 key, iv, mode, pattern, source, buffer->offset(),
453 subSamples, numSubSamples, destination, errorDetailMsg);
454 if (result < 0) {
455 return result;
456 }
Robert Shih895fba92019-07-16 16:29:44 -0700457 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800458 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
459 }
460 } else {
461 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
462 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
463 hidl_vec<SubSample> hidlSubSamples;
464 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
465
466 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
467 encryptedBuffer->fillSourceBuffer(&srcBuffer);
468
469 DestinationBuffer dstBuffer;
470 if (secure) {
471 dstBuffer.type = BufferType::NATIVE_HANDLE;
472 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
473 } else {
474 dstBuffer.type = BufferType::SHARED_MEMORY;
475 dstBuffer.nonsecureMemory = srcBuffer;
476 }
477
478 CasStatus status = CasStatus::OK;
479 hidl_string detailedError;
480 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
481
482 if (key != nullptr) {
483 sctrl = (ScramblingControl)key[0];
484 // Adjust for the PES offset
485 codecDataOffset = key[2] | (key[3] << 8);
486 }
487
488 auto returnVoid = mDescrambler->descramble(
489 sctrl,
490 hidlSubSamples,
491 srcBuffer,
492 0,
493 dstBuffer,
494 0,
495 [&status, &result, &detailedError] (
496 CasStatus _status, uint32_t _bytesWritten,
497 const hidl_string& _detailedError) {
498 status = _status;
499 result = (ssize_t)_bytesWritten;
500 detailedError = _detailedError;
501 });
502
503 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
504 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
505 mName, returnVoid.description().c_str(), status, result);
506 return UNKNOWN_ERROR;
507 }
508
509 if (result < codecDataOffset) {
510 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
511 return BAD_VALUE;
512 }
513
514 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
515
516 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
517 encryptedBuffer->copyDecryptedContentFromMemory(result);
518 }
519 }
520
521 buffer->setRange(codecDataOffset, result - codecDataOffset);
522 return queueInputBufferInternal(buffer);
523}
524
525void CCodecBufferChannel::feedInputBufferIfAvailable() {
526 QueueGuard guard(mSync);
527 if (!guard.isRunning()) {
528 ALOGV("[%s] We're not running --- no input buffer reported", mName);
529 return;
530 }
531 feedInputBufferIfAvailableInternal();
532}
533
534void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800535 if (mInputMetEos ||
536 mReorderStash.lock()->hasPending() ||
537 mPipelineWatcher.lock()->pipelineFull()) {
538 return;
539 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700540 Mutexed<Output>::Locked output(mOutput);
541 if (output->buffers->numClientBuffers() >= output->numSlots) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -0800542 return;
543 }
544 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700545 size_t numInputSlots = mInput.lock()->numSlots;
546 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800547 sp<MediaCodecBuffer> inBuffer;
548 size_t index;
549 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700550 Mutexed<Input>::Locked input(mInput);
551 if (input->buffers->numClientBuffers() >= input->numSlots) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800552 return;
553 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700554 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800555 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800556 break;
557 }
558 }
559 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
560 mCallback->onInputBufferAvailable(index, inBuffer);
561 }
562}
563
564status_t CCodecBufferChannel::renderOutputBuffer(
565 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800566 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800567 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800568 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800569 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700570 Mutexed<Output>::Locked output(mOutput);
571 if (output->buffers) {
572 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800573 }
574 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800575 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
576 // set to true.
577 sendOutputBuffers();
578 // input buffer feeding may have been gated by pending output buffers
579 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800580 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800581 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -0700582 std::call_once(mRenderWarningFlag, [this] {
583 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
584 "timestamp or render=true with non-video buffers. Apps should "
585 "call releaseOutputBuffer() with render=false for those.",
586 mName);
587 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800588 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800589 return INVALID_OPERATION;
590 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800591
592#if 0
593 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
594 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
595 for (const std::shared_ptr<const C2Info> &info : infoParams) {
596 AString res;
597 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
598 if (ix) res.append(", ");
599 res.append(*((int32_t*)info.get() + (ix / 4)));
600 }
601 ALOGV(" [%s]", res.c_str());
602 }
603#endif
604 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
605 std::static_pointer_cast<const C2StreamRotationInfo::output>(
606 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
607 bool flip = rotation && (rotation->flip & 1);
608 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
609 uint32_t transform = 0;
610 switch (quarters) {
611 case 0: // no rotation
612 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
613 break;
614 case 1: // 90 degrees counter-clockwise
615 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
616 : HAL_TRANSFORM_ROT_270;
617 break;
618 case 2: // 180 degrees
619 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
620 break;
621 case 3: // 90 degrees clockwise
622 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
623 : HAL_TRANSFORM_ROT_90;
624 break;
625 }
626
627 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
628 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
629 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
630 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
631 if (surfaceScaling) {
632 videoScalingMode = surfaceScaling->value;
633 }
634
635 // Use dataspace from format as it has the default aspects already applied
636 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
637 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
638
639 // HDR static info
640 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
641 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
642 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
643
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800644 // HDR10 plus info
645 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
646 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
647 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
648
Pawin Vongmasa36653902018-11-15 00:10:25 -0800649 {
650 Mutexed<OutputSurface>::Locked output(mOutputSurface);
651 if (output->surface == nullptr) {
652 ALOGI("[%s] cannot render buffer without surface", mName);
653 return OK;
654 }
655 }
656
657 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
658 if (blocks.size() != 1u) {
659 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
660 return UNKNOWN_ERROR;
661 }
662 const C2ConstGraphicBlock &block = blocks.front();
663
664 // TODO: revisit this after C2Fence implementation.
665 android::IGraphicBufferProducer::QueueBufferInput qbi(
666 timestampNs,
667 false, // droppable
668 dataSpace,
669 Rect(blocks.front().crop().left,
670 blocks.front().crop().top,
671 blocks.front().crop().right(),
672 blocks.front().crop().bottom()),
673 videoScalingMode,
674 transform,
675 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800676 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800677 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800678 if (hdrStaticInfo) {
679 struct android_smpte2086_metadata smpte2086_meta = {
680 .displayPrimaryRed = {
681 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
682 },
683 .displayPrimaryGreen = {
684 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
685 },
686 .displayPrimaryBlue = {
687 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
688 },
689 .whitePoint = {
690 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
691 },
692 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
693 .minLuminance = hdrStaticInfo->mastering.minLuminance,
694 };
695
696 struct android_cta861_3_metadata cta861_meta = {
697 .maxContentLightLevel = hdrStaticInfo->maxCll,
698 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
699 };
700
701 hdr.validTypes = HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3;
702 hdr.smpte2086 = smpte2086_meta;
703 hdr.cta8613 = cta861_meta;
704 }
705 if (hdr10PlusInfo) {
706 hdr.validTypes |= HdrMetadata::HDR10PLUS;
707 hdr.hdr10plus.assign(
708 hdr10PlusInfo->m.value,
709 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
710 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800711 qbi.setHdrMetadata(hdr);
712 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800713 // we don't have dirty regions
714 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800715 android::IGraphicBufferProducer::QueueBufferOutput qbo;
716 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
717 if (result != OK) {
718 ALOGI("[%s] queueBuffer failed: %d", mName, result);
719 return result;
720 }
721 ALOGV("[%s] queue buffer successful", mName);
722
723 int64_t mediaTimeUs = 0;
724 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
725 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
726
727 return OK;
728}
729
730status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
731 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
732 bool released = false;
733 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700734 Mutexed<Input>::Locked input(mInput);
735 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800736 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800737 }
738 }
739 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700740 Mutexed<Output>::Locked output(mOutput);
741 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800742 released = true;
743 }
744 }
745 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800746 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800747 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748 } else {
749 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
750 }
751 return OK;
752}
753
754void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
755 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700756 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800757
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700758 if (!input->buffers->isArrayMode()) {
759 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800760 }
761
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700762 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800763}
764
765void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
766 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700767 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800768
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700769 if (!output->buffers->isArrayMode()) {
770 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800771 }
772
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700773 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800774}
775
776status_t CCodecBufferChannel::start(
777 const sp<AMessage> &inputFormat, const sp<AMessage> &outputFormat) {
778 C2StreamBufferTypeSetting::input iStreamFormat(0u);
779 C2StreamBufferTypeSetting::output oStreamFormat(0u);
780 C2PortReorderBufferDepthTuning::output reorderDepth;
781 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800782 C2PortActualDelayTuning::input inputDelay(0);
783 C2PortActualDelayTuning::output outputDelay(0);
784 C2ActualPipelineDelayTuning pipelineDelay(0);
785
Pawin Vongmasa36653902018-11-15 00:10:25 -0800786 c2_status_t err = mComponent->query(
787 {
788 &iStreamFormat,
789 &oStreamFormat,
790 &reorderDepth,
791 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800792 &inputDelay,
793 &pipelineDelay,
794 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800795 },
796 {},
797 C2_DONT_BLOCK,
798 nullptr);
799 if (err == C2_BAD_INDEX) {
800 if (!iStreamFormat || !oStreamFormat) {
801 return UNKNOWN_ERROR;
802 }
803 } else if (err != C2_OK) {
804 return UNKNOWN_ERROR;
805 }
806
807 {
808 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
809 reorder->clear();
810 if (reorderDepth) {
811 reorder->setDepth(reorderDepth.value);
812 }
813 if (reorderKey) {
814 reorder->setKey(reorderKey.value);
815 }
816 }
Wonsik Kim078b58e2019-01-09 15:08:06 -0800817
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -0800818 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
819 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
820 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
821
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700822 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
823 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -0800824
Pawin Vongmasa36653902018-11-15 00:10:25 -0800825 // TODO: get this from input format
826 bool secure = mComponent->getName().find(".secure") != std::string::npos;
827
828 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
829 int poolMask = property_get_int32(
830 "debug.stagefright.c2-poolmask",
831 1 << C2PlatformAllocatorStore::ION |
832 1 << C2PlatformAllocatorStore::BUFFERQUEUE);
833
834 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800835 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800836 std::shared_ptr<C2BlockPool> pool;
837 {
838 Mutexed<BlockPools>::Locked pools(mBlockPools);
839
840 // set default allocator ID.
841 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
842 : C2PlatformAllocatorStore::ION;
843
844 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
845 // from component, create the input block pool with given ID. Otherwise, use default IDs.
846 std::vector<std::unique_ptr<C2Param>> params;
847 err = mComponent->query({ },
848 { C2PortAllocatorsTuning::input::PARAM_TYPE },
849 C2_DONT_BLOCK,
850 &params);
851 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
852 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
853 mName, params.size(), asString(err), err);
854 } else if (err == C2_OK && params.size() == 1) {
855 C2PortAllocatorsTuning::input *inputAllocators =
856 C2PortAllocatorsTuning::input::From(params[0].get());
857 if (inputAllocators && inputAllocators->flexCount() > 0) {
858 std::shared_ptr<C2Allocator> allocator;
859 // verify allocator IDs and resolve default allocator
860 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
861 if (allocator) {
862 pools->inputAllocatorId = allocator->getId();
863 } else {
864 ALOGD("[%s] component requested invalid input allocator ID %u",
865 mName, inputAllocators->m.values[0]);
866 }
867 }
868 }
869
870 // TODO: use C2Component wrapper to associate this pool with ourselves
871 if ((poolMask >> pools->inputAllocatorId) & 1) {
872 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
873 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
874 mName, pools->inputAllocatorId,
875 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
876 asString(err), err);
877 } else {
878 err = C2_NOT_FOUND;
879 }
880 if (err != C2_OK) {
881 C2BlockPool::local_id_t inputPoolId =
882 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
883 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
884 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
885 mName, (unsigned long long)inputPoolId,
886 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
887 asString(err), err);
888 if (err != C2_OK) {
889 return NO_MEMORY;
890 }
891 }
892 pools->inputPool = pool;
893 }
894
Wonsik Kim51051262018-11-28 13:59:05 -0800895 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700896 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -0700897 input->inputDelay = inputDelayValue;
898 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700899 input->numSlots = numInputSlots;
900 input->extraBuffers.flush();
901 input->numExtraSlots = 0u;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800902 if (graphic) {
903 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700904 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800905 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700906 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -0700907 // This is to ensure buffers do not get released prematurely.
908 // TODO: handle this without going into array mode
909 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800910 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700911 input->buffers.reset(new GraphicInputBuffers(numInputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800912 }
913 } else {
914 if (hasCryptoOrDescrambler()) {
915 int32_t capacity = kLinearBufferSize;
916 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
917 if ((size_t)capacity > kMaxLinearBufferSize) {
918 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
919 capacity = kMaxLinearBufferSize;
920 }
921 if (mDealer == nullptr) {
922 mDealer = new MemoryDealer(
923 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700924 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800925 "EncryptedLinearInputBuffers");
926 mDecryptDestination = mDealer->allocate((size_t)capacity);
927 }
928 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -0700929 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
930 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800931 } else {
932 mHeapSeqNum = -1;
933 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700934 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -0800935 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700936 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -0800937 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800938 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700939 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800940 }
941 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700942 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800943
944 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700945 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800946 } else {
947 // TODO: error
948 }
Wonsik Kim51051262018-11-28 13:59:05 -0800949
950 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700951 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -0800952 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800953 }
954
955 if (outputFormat != nullptr) {
956 sp<IGraphicBufferProducer> outputSurface;
957 uint32_t outputGeneration;
958 {
959 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -0700960 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -0700961 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -0700962 if (!secure) {
963 output->maxDequeueBuffers += numInputSlots;
964 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800965 outputSurface = output->surface ?
966 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -0800967 if (outputSurface) {
968 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
969 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800970 outputGeneration = output->generation;
971 }
972
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800973 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800974 C2BlockPool::local_id_t outputPoolId_;
975
976 {
977 Mutexed<BlockPools>::Locked pools(mBlockPools);
978
979 // set default allocator ID.
980 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
981 : C2PlatformAllocatorStore::ION;
982
983 // query C2PortAllocatorsTuning::output from component, or use default allocator if
984 // unsuccessful.
985 std::vector<std::unique_ptr<C2Param>> params;
986 err = mComponent->query({ },
987 { C2PortAllocatorsTuning::output::PARAM_TYPE },
988 C2_DONT_BLOCK,
989 &params);
990 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
991 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
992 mName, params.size(), asString(err), err);
993 } else if (err == C2_OK && params.size() == 1) {
994 C2PortAllocatorsTuning::output *outputAllocators =
995 C2PortAllocatorsTuning::output::From(params[0].get());
996 if (outputAllocators && outputAllocators->flexCount() > 0) {
997 std::shared_ptr<C2Allocator> allocator;
998 // verify allocator IDs and resolve default allocator
999 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1000 if (allocator) {
1001 pools->outputAllocatorId = allocator->getId();
1002 } else {
1003 ALOGD("[%s] component requested invalid output allocator ID %u",
1004 mName, outputAllocators->m.values[0]);
1005 }
1006 }
1007 }
1008
1009 // use bufferqueue if outputting to a surface.
1010 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1011 // if unsuccessful.
1012 if (outputSurface) {
1013 params.clear();
1014 err = mComponent->query({ },
1015 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1016 C2_DONT_BLOCK,
1017 &params);
1018 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1019 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1020 mName, params.size(), asString(err), err);
1021 } else if (err == C2_OK && params.size() == 1) {
1022 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1023 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1024 if (surfaceAllocator) {
1025 std::shared_ptr<C2Allocator> allocator;
1026 // verify allocator IDs and resolve default allocator
1027 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1028 if (allocator) {
1029 pools->outputAllocatorId = allocator->getId();
1030 } else {
1031 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1032 mName, surfaceAllocator->value);
1033 err = C2_BAD_VALUE;
1034 }
1035 }
1036 }
1037 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1038 && err != C2_OK
1039 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1040 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1041 }
1042 }
1043
1044 if ((poolMask >> pools->outputAllocatorId) & 1) {
1045 err = mComponent->createBlockPool(
1046 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1047 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1048 mName, pools->outputAllocatorId,
1049 (unsigned long long)pools->outputPoolId,
1050 asString(err));
1051 } else {
1052 err = C2_NOT_FOUND;
1053 }
1054 if (err != C2_OK) {
1055 // use basic pool instead
1056 pools->outputPoolId =
1057 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1058 }
1059
1060 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1061 // component.
1062 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1063 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1064
1065 std::vector<std::unique_ptr<C2SettingResult>> failures;
1066 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1067 ALOGD("[%s] Configured output block pool ids %llu => %s",
1068 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1069 outputPoolId_ = pools->outputPoolId;
1070 }
1071
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001072 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001073 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001074 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001075 if (graphic) {
1076 if (outputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001077 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001078 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001079 output->buffers.reset(new RawGraphicOutputBuffers(numOutputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001080 }
1081 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001082 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001083 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001084 output->buffers->setFormat(outputFormat->dup());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001085
1086
1087 // Try to set output surface to created block pool if given.
1088 if (outputSurface) {
1089 mComponent->setOutputSurface(
1090 outputPoolId_,
1091 outputSurface,
1092 outputGeneration);
1093 }
1094
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001095 if (oStreamFormat.value == C2BufferData::LINEAR) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001096 // WORKAROUND: if we're using early CSD workaround we convert to
1097 // array mode, to appease apps assuming the output
1098 // buffers to be of the same size.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001099 output->buffers = output->buffers->toArrayMode(numOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001100
1101 int32_t channelCount;
1102 int32_t sampleRate;
1103 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1104 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1105 int32_t delay = 0;
1106 int32_t padding = 0;;
1107 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1108 delay = 0;
1109 }
1110 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1111 padding = 0;
1112 }
1113 if (delay || padding) {
1114 // We need write access to the buffers, and we're already in
1115 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001116 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001117 }
1118 }
1119 }
1120 }
1121
1122 // Set up pipeline control. This has to be done after mInputBuffers and
1123 // mOutputBuffers are initialized to make sure that lingering callbacks
1124 // about buffers from the previous generation do not interfere with the
1125 // newly initialized pipeline capacity.
1126
Wonsik Kimab34ed62019-01-31 15:28:46 -08001127 {
1128 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001129 watcher->inputDelay(inputDelayValue)
1130 .pipelineDelay(pipelineDelayValue)
1131 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001132 .smoothnessFactor(kSmoothnessFactor);
1133 watcher->flush();
1134 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001135
1136 mInputMetEos = false;
1137 mSync.start();
1138 return OK;
1139}
1140
1141status_t CCodecBufferChannel::requestInitialInputBuffers() {
1142 if (mInputSurface) {
1143 return OK;
1144 }
1145
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001146 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001147 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1148 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1149 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001150 return UNKNOWN_ERROR;
1151 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001152 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001153 std::vector<sp<MediaCodecBuffer>> toBeQueued;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001154 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001155 size_t index;
1156 sp<MediaCodecBuffer> buffer;
1157 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001158 Mutexed<Input>::Locked input(mInput);
1159 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001160 if (i == 0) {
1161 ALOGW("[%s] start: cannot allocate memory at all", mName);
1162 return NO_MEMORY;
1163 } else {
1164 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
1165 mName, i);
1166 }
1167 break;
1168 }
1169 }
1170 if (buffer) {
1171 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1172 ALOGV("[%s] input buffer %zu available", mName, index);
1173 bool post = true;
1174 if (!configs->empty()) {
1175 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001176 configs->pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001177 if (buffer->capacity() >= config->size()) {
1178 memcpy(buffer->base(), config->data(), config->size());
1179 buffer->setRange(0, config->size());
1180 buffer->meta()->clear();
1181 buffer->meta()->setInt64("timeUs", 0);
1182 buffer->meta()->setInt32("csd", 1);
1183 post = false;
1184 } else {
1185 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
1186 mName, buffer->capacity(), config->size());
1187 }
1188 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001189 && (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001190 // WORKAROUND: Some apps expect CSD available without queueing
1191 // any input. Queue an empty buffer to get the CSD.
1192 buffer->setRange(0, 0);
1193 buffer->meta()->clear();
1194 buffer->meta()->setInt64("timeUs", 0);
1195 post = false;
1196 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001197 if (post) {
1198 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001199 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001200 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001201 }
1202 }
1203 }
1204 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
1205 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001206 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001207 }
1208 }
1209 return OK;
1210}
1211
1212void CCodecBufferChannel::stop() {
1213 mSync.stop();
1214 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1215 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001216 mInputSurface.reset();
1217 }
1218}
1219
1220void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1221 ALOGV("[%s] flush", mName);
1222 {
1223 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1224 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1225 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1226 continue;
1227 }
1228 if (work->input.buffers.empty()
1229 || work->input.buffers.front()->data().linearBlocks().empty()) {
1230 ALOGD("[%s] no linear codec config data found", mName);
1231 continue;
1232 }
1233 C2ReadView view =
1234 work->input.buffers.front()->data().linearBlocks().front().map().get();
1235 if (view.error() != C2_OK) {
1236 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1237 continue;
1238 }
1239 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1240 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1241 }
1242 }
1243 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001244 Mutexed<Input>::Locked input(mInput);
1245 input->buffers->flush();
1246 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001247 }
1248 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001249 Mutexed<Output>::Locked output(mOutput);
1250 output->buffers->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001251 }
Wonsik Kim6897f222019-01-30 13:29:24 -08001252 mReorderStash.lock()->flush();
Wonsik Kimab34ed62019-01-31 15:28:46 -08001253 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001254}
1255
1256void CCodecBufferChannel::onWorkDone(
1257 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001258 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001259 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001260 feedInputBufferIfAvailable();
1261 }
1262}
1263
1264void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001265 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001266 if (mInputSurface) {
1267 return;
1268 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001269 std::shared_ptr<C2Buffer> buffer =
1270 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001271 bool newInputSlotAvailable;
1272 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001273 Mutexed<Input>::Locked input(mInput);
1274 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1275 if (!newInputSlotAvailable) {
1276 (void)input->extraBuffers.expireComponentBuffer(buffer);
1277 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001278 }
1279 if (newInputSlotAvailable) {
1280 feedInputBufferIfAvailable();
1281 }
1282}
1283
1284bool CCodecBufferChannel::handleWork(
1285 std::unique_ptr<C2Work> work,
1286 const sp<AMessage> &outputFormat,
1287 const C2StreamInitDataInfo::output *initData) {
1288 if ((work->input.ordinal.frameIndex - mFirstValidFrameIndex.load()).peek() < 0) {
1289 // Discard frames from previous generation.
1290 ALOGD("[%s] Discard frames from previous generation.", mName);
1291 return false;
1292 }
1293
Wonsik Kim524b0582019-03-12 11:28:57 -07001294 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001295 || !work->worklets.front()
Wonsik Kim524b0582019-03-12 11:28:57 -07001296 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE))) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001297 mPipelineWatcher.lock()->onWorkDone(work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001298 }
1299
1300 if (work->result == C2_NOT_FOUND) {
1301 ALOGD("[%s] flushed work; ignored.", mName);
1302 return true;
1303 }
1304
1305 if (work->result != C2_OK) {
1306 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1307 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1308 return false;
1309 }
1310
1311 // NOTE: MediaCodec usage supposedly have only one worklet
1312 if (work->worklets.size() != 1u) {
1313 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1314 mName, work->worklets.size());
1315 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1316 return false;
1317 }
1318
1319 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1320
1321 std::shared_ptr<C2Buffer> buffer;
1322 // NOTE: MediaCodec usage supposedly have only one output stream.
1323 if (worklet->output.buffers.size() > 1u) {
1324 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1325 mName, worklet->output.buffers.size());
1326 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1327 return false;
1328 } else if (worklet->output.buffers.size() == 1u) {
1329 buffer = worklet->output.buffers[0];
1330 if (!buffer) {
1331 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1332 }
1333 }
1334
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001335 std::optional<uint32_t> newInputDelay, newPipelineDelay;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001336 while (!worklet->output.configUpdate.empty()) {
1337 std::unique_ptr<C2Param> param;
1338 worklet->output.configUpdate.back().swap(param);
1339 worklet->output.configUpdate.pop_back();
1340 switch (param->coreIndex().coreIndex()) {
1341 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1342 C2PortReorderBufferDepthTuning::output reorderDepth;
1343 if (reorderDepth.updateFrom(*param)) {
Sungtak Leed7463d12019-09-04 16:01:00 -07001344 bool secure = mComponent->getName().find(".secure") != std::string::npos;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001345 mReorderStash.lock()->setDepth(reorderDepth.value);
1346 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1347 mName, reorderDepth.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001348 size_t numOutputSlots = mOutput.lock()->numSlots;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001349 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001350 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001351 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001352 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001353 if (!secure) {
1354 output->maxDequeueBuffers += numInputSlots;
1355 }
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001356 if (output->surface) {
1357 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1358 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001359 } else {
1360 ALOGD("[%s] onWorkDone: failed to read reorder depth", mName);
1361 }
1362 break;
1363 }
1364 case C2PortReorderKeySetting::CORE_INDEX: {
1365 C2PortReorderKeySetting::output reorderKey;
1366 if (reorderKey.updateFrom(*param)) {
1367 mReorderStash.lock()->setKey(reorderKey.value);
1368 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1369 mName, reorderKey.value);
1370 } else {
1371 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1372 }
1373 break;
1374 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001375 case C2PortActualDelayTuning::CORE_INDEX: {
1376 if (param->isGlobal()) {
1377 C2ActualPipelineDelayTuning pipelineDelay;
1378 if (pipelineDelay.updateFrom(*param)) {
1379 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1380 mName, pipelineDelay.value);
1381 newPipelineDelay = pipelineDelay.value;
1382 (void)mPipelineWatcher.lock()->pipelineDelay(pipelineDelay.value);
1383 }
1384 }
1385 if (param->forInput()) {
1386 C2PortActualDelayTuning::input inputDelay;
1387 if (inputDelay.updateFrom(*param)) {
1388 ALOGV("[%s] onWorkDone: updating input delay %u",
1389 mName, inputDelay.value);
1390 newInputDelay = inputDelay.value;
1391 (void)mPipelineWatcher.lock()->inputDelay(inputDelay.value);
1392 }
1393 }
1394 if (param->forOutput()) {
1395 C2PortActualDelayTuning::output outputDelay;
1396 if (outputDelay.updateFrom(*param)) {
1397 ALOGV("[%s] onWorkDone: updating output delay %u",
1398 mName, outputDelay.value);
Sungtak Leed7463d12019-09-04 16:01:00 -07001399 bool secure = mComponent->getName().find(".secure") != std::string::npos;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001400 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
1401
1402 bool outputBuffersChanged = false;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001403 size_t numOutputSlots = 0;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001404 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001405 {
1406 Mutexed<Output>::Locked output(mOutput);
1407 output->outputDelay = outputDelay.value;
1408 numOutputSlots = outputDelay.value + kSmoothnessFactor;
1409 if (output->numSlots < numOutputSlots) {
1410 output->numSlots = numOutputSlots;
1411 if (output->buffers->isArrayMode()) {
1412 OutputBuffersArray *array =
1413 (OutputBuffersArray *)output->buffers.get();
1414 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1415 mName, numOutputSlots);
1416 array->grow(numOutputSlots);
1417 outputBuffersChanged = true;
1418 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001419 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001420 numOutputSlots = output->numSlots;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001421 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001422
1423 if (outputBuffersChanged) {
1424 mCCodecCallback->onOutputBuffersChanged();
1425 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001426
1427 uint32_t depth = mReorderStash.lock()->depth();
1428 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001429 output->maxDequeueBuffers = numOutputSlots + depth + kRenderingDepth;
1430 if (!secure) {
1431 output->maxDequeueBuffers += numInputSlots;
1432 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001433 if (output->surface) {
1434 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1435 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001436 }
1437 }
1438 break;
1439 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001440 default:
1441 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1442 mName, param->index());
1443 break;
1444 }
1445 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001446 if (newInputDelay || newPipelineDelay) {
1447 Mutexed<Input>::Locked input(mInput);
1448 size_t newNumSlots =
1449 newInputDelay.value_or(input->inputDelay) +
1450 newPipelineDelay.value_or(input->pipelineDelay) +
1451 kSmoothnessFactor;
1452 if (input->buffers->isArrayMode()) {
1453 if (input->numSlots >= newNumSlots) {
1454 input->numExtraSlots = 0;
1455 } else {
1456 input->numExtraSlots = newNumSlots - input->numSlots;
1457 }
1458 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1459 mName, input->numExtraSlots);
1460 } else {
1461 input->numSlots = newNumSlots;
1462 }
1463 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001464
1465 if (outputFormat != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001466 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001467 ALOGD("[%s] onWorkDone: output format changed to %s",
1468 mName, outputFormat->debugString().c_str());
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001469 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001470
1471 AString mediaType;
1472 if (outputFormat->findString(KEY_MIME, &mediaType)
1473 && mediaType == MIMETYPE_AUDIO_RAW) {
1474 int32_t channelCount;
1475 int32_t sampleRate;
1476 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1477 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001478 output->buffers->updateSkipCutBuffer(sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001479 }
1480 }
1481 }
1482
1483 int32_t flags = 0;
1484 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1485 flags |= MediaCodec::BUFFER_FLAG_EOS;
1486 ALOGV("[%s] onWorkDone: output EOS", mName);
1487 }
1488
1489 sp<MediaCodecBuffer> outBuffer;
1490 size_t index;
1491
1492 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1493 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1494 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1495 // shall correspond to the client input timesamp (in customOrdinal). By using the
1496 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1497 // produces multiple output.
1498 c2_cntr64_t timestamp =
1499 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1500 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001501 if (mInputSurface != nullptr) {
1502 // When using input surface we need to restore the original input timestamp.
1503 timestamp = work->input.ordinal.customOrdinal;
1504 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001505 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1506 mName,
1507 work->input.ordinal.customOrdinal.peekll(),
1508 work->input.ordinal.timestamp.peekll(),
1509 worklet->output.ordinal.timestamp.peekll(),
1510 timestamp.peekll());
1511
1512 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001513 Mutexed<Output>::Locked output(mOutput);
1514 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001515 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1516 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1517 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1518
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001519 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001520 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001521 } else {
1522 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001523 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001524 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001525 return false;
1526 }
1527 }
1528
1529 if (!buffer && !flags) {
1530 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1531 mName, work->input.ordinal.frameIndex.peekull());
1532 return true;
1533 }
1534
1535 if (buffer) {
1536 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1537 // TODO: properly translate these to metadata
1538 switch (info->coreIndex().coreIndex()) {
1539 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001540 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001541 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1542 }
1543 break;
1544 default:
1545 break;
1546 }
1547 }
1548 }
1549
1550 {
1551 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1552 reorder->emplace(buffer, timestamp.peek(), flags, worklet->output.ordinal);
1553 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
1554 // Flush reorder stash
1555 reorder->setDepth(0);
1556 }
1557 }
1558 sendOutputBuffers();
1559 return true;
1560}
1561
1562void CCodecBufferChannel::sendOutputBuffers() {
1563 ReorderStash::Entry entry;
1564 sp<MediaCodecBuffer> outBuffer;
1565 size_t index;
1566
1567 while (true) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001568 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1569 if (!reorder->hasPending()) {
1570 break;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001571 }
Wonsik Kim38ad3412019-02-01 15:13:23 -08001572 if (!reorder->pop(&entry)) {
1573 break;
1574 }
1575
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001576 Mutexed<Output>::Locked output(mOutput);
1577 status_t err = output->buffers->registerBuffer(entry.buffer, &index, &outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001578 if (err != OK) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001579 bool outputBuffersChanged = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001580 if (err != WOULD_BLOCK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001581 if (!output->buffers->isArrayMode()) {
1582 output->buffers = output->buffers->toArrayMode(output->numSlots);
Wonsik Kim186fdbf2019-01-29 13:30:01 -08001583 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001584 OutputBuffersArray *array = (OutputBuffersArray *)output->buffers.get();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001585 array->realloc(entry.buffer);
Wonsik Kim38ad3412019-02-01 15:13:23 -08001586 outputBuffersChanged = true;
1587 }
1588 ALOGV("[%s] sendOutputBuffers: unable to register output buffer", mName);
1589 reorder->defer(entry);
1590
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001591 output.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08001592 reorder.unlock();
1593
1594 if (outputBuffersChanged) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001595 mCCodecCallback->onOutputBuffersChanged();
1596 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001597 return;
1598 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001599 output.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08001600 reorder.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001601
1602 outBuffer->meta()->setInt64("timeUs", entry.timestamp);
1603 outBuffer->meta()->setInt32("flags", entry.flags);
Wonsik Kim66427432019-03-21 15:06:22 -07001604 ALOGV("[%s] sendOutputBuffers: out buffer index = %zu [%p] => %p + %zu (%lld)",
1605 mName, index, outBuffer.get(), outBuffer->data(), outBuffer->size(),
1606 (long long)entry.timestamp);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001607 mCallback->onOutputBufferAvailable(index, outBuffer);
1608 }
1609}
1610
1611status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1612 static std::atomic_uint32_t surfaceGeneration{0};
1613 uint32_t generation = (getpid() << 10) |
1614 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1615 & ((1 << 10) - 1));
1616
1617 sp<IGraphicBufferProducer> producer;
1618 if (newSurface) {
1619 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001620 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Lee08515812019-06-05 11:16:32 -07001621 newSurface->setMaxDequeuedBufferCount(mOutputSurface.lock()->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001622 producer = newSurface->getIGraphicBufferProducer();
1623 producer->setGenerationNumber(generation);
1624 } else {
1625 ALOGE("[%s] setting output surface to null", mName);
1626 return INVALID_OPERATION;
1627 }
1628
1629 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1630 C2BlockPool::local_id_t outputPoolId;
1631 {
1632 Mutexed<BlockPools>::Locked pools(mBlockPools);
1633 outputPoolId = pools->outputPoolId;
1634 outputPoolIntf = pools->outputPoolIntf;
1635 }
1636
1637 if (outputPoolIntf) {
1638 if (mComponent->setOutputSurface(
1639 outputPoolId,
1640 producer,
1641 generation) != C2_OK) {
1642 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1643 return INVALID_OPERATION;
1644 }
1645 }
1646
1647 {
1648 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1649 output->surface = newSurface;
1650 output->generation = generation;
1651 }
1652
1653 return OK;
1654}
1655
Wonsik Kimab34ed62019-01-31 15:28:46 -08001656PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001657 // When client pushed EOS, we want all the work to be done quickly.
1658 // Otherwise, component may have stalled work due to input starvation up to
1659 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001660 size_t n = 0;
1661 if (!mInputMetEos) {
1662 size_t outputDelay = mOutput.lock()->outputDelay;
1663 Mutexed<Input>::Locked input(mInput);
1664 n = input->inputDelay + input->pipelineDelay + outputDelay;
1665 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001666 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001667}
1668
Pawin Vongmasa36653902018-11-15 00:10:25 -08001669void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1670 mMetaMode = mode;
1671}
1672
1673status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1674 // C2_OK is always translated to OK.
1675 if (c2s == C2_OK) {
1676 return OK;
1677 }
1678
1679 // Operation-dependent translation
1680 // TODO: Add as necessary
1681 switch (c2op) {
1682 case C2_OPERATION_Component_start:
1683 switch (c2s) {
1684 case C2_NO_MEMORY:
1685 return NO_MEMORY;
1686 default:
1687 return UNKNOWN_ERROR;
1688 }
1689 default:
1690 break;
1691 }
1692
1693 // Backup operation-agnostic translation
1694 switch (c2s) {
1695 case C2_BAD_INDEX:
1696 return BAD_INDEX;
1697 case C2_BAD_VALUE:
1698 return BAD_VALUE;
1699 case C2_BLOCKING:
1700 return WOULD_BLOCK;
1701 case C2_DUPLICATE:
1702 return ALREADY_EXISTS;
1703 case C2_NO_INIT:
1704 return NO_INIT;
1705 case C2_NO_MEMORY:
1706 return NO_MEMORY;
1707 case C2_NOT_FOUND:
1708 return NAME_NOT_FOUND;
1709 case C2_TIMED_OUT:
1710 return TIMED_OUT;
1711 case C2_BAD_STATE:
1712 case C2_CANCELED:
1713 case C2_CANNOT_DO:
1714 case C2_CORRUPTED:
1715 case C2_OMITTED:
1716 case C2_REFUSED:
1717 return UNKNOWN_ERROR;
1718 default:
1719 return -static_cast<status_t>(c2s);
1720 }
1721}
1722
1723} // namespace android