blob: 2bcb7e2dcb7a291b107c7255a9e8bfe65d99496d [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();
Pin-chih Linaa18ea52019-11-19 18:48:50 +0800829 int poolMask = GetCodec2PoolMask();
830 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800831
832 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800833 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800834 std::shared_ptr<C2BlockPool> pool;
835 {
836 Mutexed<BlockPools>::Locked pools(mBlockPools);
837
838 // set default allocator ID.
839 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +0800840 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800841
842 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
843 // from component, create the input block pool with given ID. Otherwise, use default IDs.
844 std::vector<std::unique_ptr<C2Param>> params;
845 err = mComponent->query({ },
846 { C2PortAllocatorsTuning::input::PARAM_TYPE },
847 C2_DONT_BLOCK,
848 &params);
849 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
850 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
851 mName, params.size(), asString(err), err);
852 } else if (err == C2_OK && params.size() == 1) {
853 C2PortAllocatorsTuning::input *inputAllocators =
854 C2PortAllocatorsTuning::input::From(params[0].get());
855 if (inputAllocators && inputAllocators->flexCount() > 0) {
856 std::shared_ptr<C2Allocator> allocator;
857 // verify allocator IDs and resolve default allocator
858 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
859 if (allocator) {
860 pools->inputAllocatorId = allocator->getId();
861 } else {
862 ALOGD("[%s] component requested invalid input allocator ID %u",
863 mName, inputAllocators->m.values[0]);
864 }
865 }
866 }
867
868 // TODO: use C2Component wrapper to associate this pool with ourselves
869 if ((poolMask >> pools->inputAllocatorId) & 1) {
870 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
871 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
872 mName, pools->inputAllocatorId,
873 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
874 asString(err), err);
875 } else {
876 err = C2_NOT_FOUND;
877 }
878 if (err != C2_OK) {
879 C2BlockPool::local_id_t inputPoolId =
880 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
881 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
882 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
883 mName, (unsigned long long)inputPoolId,
884 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
885 asString(err), err);
886 if (err != C2_OK) {
887 return NO_MEMORY;
888 }
889 }
890 pools->inputPool = pool;
891 }
892
Wonsik Kim51051262018-11-28 13:59:05 -0800893 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700894 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -0700895 input->inputDelay = inputDelayValue;
896 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700897 input->numSlots = numInputSlots;
898 input->extraBuffers.flush();
899 input->numExtraSlots = 0u;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800900 if (graphic) {
901 if (mInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700902 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800903 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700904 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -0700905 // This is to ensure buffers do not get released prematurely.
906 // TODO: handle this without going into array mode
907 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800908 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700909 input->buffers.reset(new GraphicInputBuffers(numInputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800910 }
911 } else {
912 if (hasCryptoOrDescrambler()) {
913 int32_t capacity = kLinearBufferSize;
914 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
915 if ((size_t)capacity > kMaxLinearBufferSize) {
916 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
917 capacity = kMaxLinearBufferSize;
918 }
919 if (mDealer == nullptr) {
920 mDealer = new MemoryDealer(
921 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700922 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800923 "EncryptedLinearInputBuffers");
924 mDecryptDestination = mDealer->allocate((size_t)capacity);
925 }
926 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -0700927 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
928 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800929 } else {
930 mHeapSeqNum = -1;
931 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700932 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -0800933 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700934 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -0800935 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800936 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700937 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800938 }
939 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700940 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800941
942 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700943 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800944 } else {
945 // TODO: error
946 }
Wonsik Kim51051262018-11-28 13:59:05 -0800947
948 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700949 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -0800950 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800951 }
952
953 if (outputFormat != nullptr) {
954 sp<IGraphicBufferProducer> outputSurface;
955 uint32_t outputGeneration;
956 {
957 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -0700958 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -0700959 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -0700960 if (!secure) {
961 output->maxDequeueBuffers += numInputSlots;
962 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800963 outputSurface = output->surface ?
964 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -0800965 if (outputSurface) {
966 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
967 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800968 outputGeneration = output->generation;
969 }
970
Lajos Molnar3bb81cd2019-02-20 15:10:30 -0800971 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800972 C2BlockPool::local_id_t outputPoolId_;
973
974 {
975 Mutexed<BlockPools>::Locked pools(mBlockPools);
976
977 // set default allocator ID.
978 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +0800979 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800980
981 // query C2PortAllocatorsTuning::output from component, or use default allocator if
982 // unsuccessful.
983 std::vector<std::unique_ptr<C2Param>> params;
984 err = mComponent->query({ },
985 { C2PortAllocatorsTuning::output::PARAM_TYPE },
986 C2_DONT_BLOCK,
987 &params);
988 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
989 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
990 mName, params.size(), asString(err), err);
991 } else if (err == C2_OK && params.size() == 1) {
992 C2PortAllocatorsTuning::output *outputAllocators =
993 C2PortAllocatorsTuning::output::From(params[0].get());
994 if (outputAllocators && outputAllocators->flexCount() > 0) {
995 std::shared_ptr<C2Allocator> allocator;
996 // verify allocator IDs and resolve default allocator
997 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
998 if (allocator) {
999 pools->outputAllocatorId = allocator->getId();
1000 } else {
1001 ALOGD("[%s] component requested invalid output allocator ID %u",
1002 mName, outputAllocators->m.values[0]);
1003 }
1004 }
1005 }
1006
1007 // use bufferqueue if outputting to a surface.
1008 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1009 // if unsuccessful.
1010 if (outputSurface) {
1011 params.clear();
1012 err = mComponent->query({ },
1013 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1014 C2_DONT_BLOCK,
1015 &params);
1016 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1017 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1018 mName, params.size(), asString(err), err);
1019 } else if (err == C2_OK && params.size() == 1) {
1020 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1021 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1022 if (surfaceAllocator) {
1023 std::shared_ptr<C2Allocator> allocator;
1024 // verify allocator IDs and resolve default allocator
1025 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1026 if (allocator) {
1027 pools->outputAllocatorId = allocator->getId();
1028 } else {
1029 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1030 mName, surfaceAllocator->value);
1031 err = C2_BAD_VALUE;
1032 }
1033 }
1034 }
1035 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1036 && err != C2_OK
1037 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1038 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1039 }
1040 }
1041
1042 if ((poolMask >> pools->outputAllocatorId) & 1) {
1043 err = mComponent->createBlockPool(
1044 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1045 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1046 mName, pools->outputAllocatorId,
1047 (unsigned long long)pools->outputPoolId,
1048 asString(err));
1049 } else {
1050 err = C2_NOT_FOUND;
1051 }
1052 if (err != C2_OK) {
1053 // use basic pool instead
1054 pools->outputPoolId =
1055 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1056 }
1057
1058 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1059 // component.
1060 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1061 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1062
1063 std::vector<std::unique_ptr<C2SettingResult>> failures;
1064 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
1065 ALOGD("[%s] Configured output block pool ids %llu => %s",
1066 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1067 outputPoolId_ = pools->outputPoolId;
1068 }
1069
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001070 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001071 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001072 output->numSlots = numOutputSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001073 if (graphic) {
1074 if (outputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001075 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001076 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001077 output->buffers.reset(new RawGraphicOutputBuffers(numOutputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001078 }
1079 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001080 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001081 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001082 output->buffers->setFormat(outputFormat->dup());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001083
1084
1085 // Try to set output surface to created block pool if given.
1086 if (outputSurface) {
1087 mComponent->setOutputSurface(
1088 outputPoolId_,
1089 outputSurface,
1090 outputGeneration);
1091 }
1092
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001093 if (oStreamFormat.value == C2BufferData::LINEAR) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001094 // WORKAROUND: if we're using early CSD workaround we convert to
1095 // array mode, to appease apps assuming the output
1096 // buffers to be of the same size.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001097 output->buffers = output->buffers->toArrayMode(numOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001098
1099 int32_t channelCount;
1100 int32_t sampleRate;
1101 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1102 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1103 int32_t delay = 0;
1104 int32_t padding = 0;;
1105 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1106 delay = 0;
1107 }
1108 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1109 padding = 0;
1110 }
1111 if (delay || padding) {
1112 // We need write access to the buffers, and we're already in
1113 // array mode.
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001114 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001115 }
1116 }
1117 }
1118 }
1119
1120 // Set up pipeline control. This has to be done after mInputBuffers and
1121 // mOutputBuffers are initialized to make sure that lingering callbacks
1122 // about buffers from the previous generation do not interfere with the
1123 // newly initialized pipeline capacity.
1124
Wonsik Kimab34ed62019-01-31 15:28:46 -08001125 {
1126 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001127 watcher->inputDelay(inputDelayValue)
1128 .pipelineDelay(pipelineDelayValue)
1129 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08001130 .smoothnessFactor(kSmoothnessFactor);
1131 watcher->flush();
1132 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001133
1134 mInputMetEos = false;
1135 mSync.start();
1136 return OK;
1137}
1138
1139status_t CCodecBufferChannel::requestInitialInputBuffers() {
1140 if (mInputSurface) {
1141 return OK;
1142 }
1143
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001144 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001145 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1146 c2_status_t err = mComponent->query({ &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
1147 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001148 return UNKNOWN_ERROR;
1149 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001150 size_t numInputSlots = mInput.lock()->numSlots;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001151 std::vector<sp<MediaCodecBuffer>> toBeQueued;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001152 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001153 size_t index;
1154 sp<MediaCodecBuffer> buffer;
1155 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001156 Mutexed<Input>::Locked input(mInput);
1157 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001158 if (i == 0) {
1159 ALOGW("[%s] start: cannot allocate memory at all", mName);
1160 return NO_MEMORY;
1161 } else {
1162 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
1163 mName, i);
1164 }
1165 break;
1166 }
1167 }
1168 if (buffer) {
1169 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1170 ALOGV("[%s] input buffer %zu available", mName, index);
1171 bool post = true;
1172 if (!configs->empty()) {
1173 sp<ABuffer> config = configs->front();
Pawin Vongmasa472c7382019-03-26 18:13:58 -07001174 configs->pop_front();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001175 if (buffer->capacity() >= config->size()) {
1176 memcpy(buffer->base(), config->data(), config->size());
1177 buffer->setRange(0, config->size());
1178 buffer->meta()->clear();
1179 buffer->meta()->setInt64("timeUs", 0);
1180 buffer->meta()->setInt32("csd", 1);
1181 post = false;
1182 } else {
1183 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
1184 mName, buffer->capacity(), config->size());
1185 }
1186 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001187 && (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001188 // WORKAROUND: Some apps expect CSD available without queueing
1189 // any input. Queue an empty buffer to get the CSD.
1190 buffer->setRange(0, 0);
1191 buffer->meta()->clear();
1192 buffer->meta()->setInt64("timeUs", 0);
1193 post = false;
1194 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001195 if (post) {
1196 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001197 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001198 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001199 }
1200 }
1201 }
1202 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
1203 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001204 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001205 }
1206 }
1207 return OK;
1208}
1209
1210void CCodecBufferChannel::stop() {
1211 mSync.stop();
1212 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
1213 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001214 mInputSurface.reset();
1215 }
1216}
1217
1218void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1219 ALOGV("[%s] flush", mName);
1220 {
1221 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
1222 for (const std::unique_ptr<C2Work> &work : flushedWork) {
1223 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
1224 continue;
1225 }
1226 if (work->input.buffers.empty()
1227 || work->input.buffers.front()->data().linearBlocks().empty()) {
1228 ALOGD("[%s] no linear codec config data found", mName);
1229 continue;
1230 }
1231 C2ReadView view =
1232 work->input.buffers.front()->data().linearBlocks().front().map().get();
1233 if (view.error() != C2_OK) {
1234 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
1235 continue;
1236 }
1237 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
1238 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
1239 }
1240 }
1241 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001242 Mutexed<Input>::Locked input(mInput);
1243 input->buffers->flush();
1244 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001245 }
1246 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001247 Mutexed<Output>::Locked output(mOutput);
1248 output->buffers->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001249 }
Wonsik Kim6897f222019-01-30 13:29:24 -08001250 mReorderStash.lock()->flush();
Wonsik Kimab34ed62019-01-31 15:28:46 -08001251 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001252}
1253
1254void CCodecBufferChannel::onWorkDone(
1255 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001256 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001257 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001258 feedInputBufferIfAvailable();
1259 }
1260}
1261
1262void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08001263 uint64_t frameIndex, size_t arrayIndex) {
Pawin Vongmasa8e2cfb52019-05-15 05:20:52 -07001264 if (mInputSurface) {
1265 return;
1266 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001267 std::shared_ptr<C2Buffer> buffer =
1268 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001269 bool newInputSlotAvailable;
1270 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001271 Mutexed<Input>::Locked input(mInput);
1272 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
1273 if (!newInputSlotAvailable) {
1274 (void)input->extraBuffers.expireComponentBuffer(buffer);
1275 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001276 }
1277 if (newInputSlotAvailable) {
1278 feedInputBufferIfAvailable();
1279 }
1280}
1281
1282bool CCodecBufferChannel::handleWork(
1283 std::unique_ptr<C2Work> work,
1284 const sp<AMessage> &outputFormat,
1285 const C2StreamInitDataInfo::output *initData) {
1286 if ((work->input.ordinal.frameIndex - mFirstValidFrameIndex.load()).peek() < 0) {
1287 // Discard frames from previous generation.
1288 ALOGD("[%s] Discard frames from previous generation.", mName);
1289 return false;
1290 }
1291
Wonsik Kim524b0582019-03-12 11:28:57 -07001292 if (mInputSurface == nullptr && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08001293 || !work->worklets.front()
Wonsik Kim524b0582019-03-12 11:28:57 -07001294 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE))) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001295 mPipelineWatcher.lock()->onWorkDone(work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001296 }
1297
1298 if (work->result == C2_NOT_FOUND) {
1299 ALOGD("[%s] flushed work; ignored.", mName);
1300 return true;
1301 }
1302
1303 if (work->result != C2_OK) {
1304 ALOGD("[%s] work failed to complete: %d", mName, work->result);
1305 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
1306 return false;
1307 }
1308
1309 // NOTE: MediaCodec usage supposedly have only one worklet
1310 if (work->worklets.size() != 1u) {
1311 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
1312 mName, work->worklets.size());
1313 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1314 return false;
1315 }
1316
1317 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
1318
1319 std::shared_ptr<C2Buffer> buffer;
1320 // NOTE: MediaCodec usage supposedly have only one output stream.
1321 if (worklet->output.buffers.size() > 1u) {
1322 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
1323 mName, worklet->output.buffers.size());
1324 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1325 return false;
1326 } else if (worklet->output.buffers.size() == 1u) {
1327 buffer = worklet->output.buffers[0];
1328 if (!buffer) {
1329 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
1330 }
1331 }
1332
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001333 std::optional<uint32_t> newInputDelay, newPipelineDelay;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001334 while (!worklet->output.configUpdate.empty()) {
1335 std::unique_ptr<C2Param> param;
1336 worklet->output.configUpdate.back().swap(param);
1337 worklet->output.configUpdate.pop_back();
1338 switch (param->coreIndex().coreIndex()) {
1339 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
1340 C2PortReorderBufferDepthTuning::output reorderDepth;
1341 if (reorderDepth.updateFrom(*param)) {
Sungtak Leed7463d12019-09-04 16:01:00 -07001342 bool secure = mComponent->getName().find(".secure") != std::string::npos;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001343 mReorderStash.lock()->setDepth(reorderDepth.value);
1344 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
1345 mName, reorderDepth.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001346 size_t numOutputSlots = mOutput.lock()->numSlots;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001347 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001348 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001349 output->maxDequeueBuffers = numOutputSlots +
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001350 reorderDepth.value + kRenderingDepth;
Sungtak Leed7463d12019-09-04 16:01:00 -07001351 if (!secure) {
1352 output->maxDequeueBuffers += numInputSlots;
1353 }
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001354 if (output->surface) {
1355 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1356 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001357 } else {
1358 ALOGD("[%s] onWorkDone: failed to read reorder depth", mName);
1359 }
1360 break;
1361 }
1362 case C2PortReorderKeySetting::CORE_INDEX: {
1363 C2PortReorderKeySetting::output reorderKey;
1364 if (reorderKey.updateFrom(*param)) {
1365 mReorderStash.lock()->setKey(reorderKey.value);
1366 ALOGV("[%s] onWorkDone: updated reorder key to %u",
1367 mName, reorderKey.value);
1368 } else {
1369 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
1370 }
1371 break;
1372 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001373 case C2PortActualDelayTuning::CORE_INDEX: {
1374 if (param->isGlobal()) {
1375 C2ActualPipelineDelayTuning pipelineDelay;
1376 if (pipelineDelay.updateFrom(*param)) {
1377 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
1378 mName, pipelineDelay.value);
1379 newPipelineDelay = pipelineDelay.value;
1380 (void)mPipelineWatcher.lock()->pipelineDelay(pipelineDelay.value);
1381 }
1382 }
1383 if (param->forInput()) {
1384 C2PortActualDelayTuning::input inputDelay;
1385 if (inputDelay.updateFrom(*param)) {
1386 ALOGV("[%s] onWorkDone: updating input delay %u",
1387 mName, inputDelay.value);
1388 newInputDelay = inputDelay.value;
1389 (void)mPipelineWatcher.lock()->inputDelay(inputDelay.value);
1390 }
1391 }
1392 if (param->forOutput()) {
1393 C2PortActualDelayTuning::output outputDelay;
1394 if (outputDelay.updateFrom(*param)) {
1395 ALOGV("[%s] onWorkDone: updating output delay %u",
1396 mName, outputDelay.value);
Sungtak Leed7463d12019-09-04 16:01:00 -07001397 bool secure = mComponent->getName().find(".secure") != std::string::npos;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001398 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
1399
1400 bool outputBuffersChanged = false;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001401 size_t numOutputSlots = 0;
Sungtak Lee7a7b7422019-07-16 17:40:40 -07001402 size_t numInputSlots = mInput.lock()->numSlots;
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001403 {
1404 Mutexed<Output>::Locked output(mOutput);
1405 output->outputDelay = outputDelay.value;
1406 numOutputSlots = outputDelay.value + kSmoothnessFactor;
1407 if (output->numSlots < numOutputSlots) {
1408 output->numSlots = numOutputSlots;
1409 if (output->buffers->isArrayMode()) {
1410 OutputBuffersArray *array =
1411 (OutputBuffersArray *)output->buffers.get();
1412 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
1413 mName, numOutputSlots);
1414 array->grow(numOutputSlots);
1415 outputBuffersChanged = true;
1416 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001417 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001418 numOutputSlots = output->numSlots;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001419 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001420
1421 if (outputBuffersChanged) {
1422 mCCodecCallback->onOutputBuffersChanged();
1423 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001424
1425 uint32_t depth = mReorderStash.lock()->depth();
1426 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leed7463d12019-09-04 16:01:00 -07001427 output->maxDequeueBuffers = numOutputSlots + depth + kRenderingDepth;
1428 if (!secure) {
1429 output->maxDequeueBuffers += numInputSlots;
1430 }
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001431 if (output->surface) {
1432 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1433 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001434 }
1435 }
1436 break;
1437 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001438 default:
1439 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
1440 mName, param->index());
1441 break;
1442 }
1443 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001444 if (newInputDelay || newPipelineDelay) {
1445 Mutexed<Input>::Locked input(mInput);
1446 size_t newNumSlots =
1447 newInputDelay.value_or(input->inputDelay) +
1448 newPipelineDelay.value_or(input->pipelineDelay) +
1449 kSmoothnessFactor;
1450 if (input->buffers->isArrayMode()) {
1451 if (input->numSlots >= newNumSlots) {
1452 input->numExtraSlots = 0;
1453 } else {
1454 input->numExtraSlots = newNumSlots - input->numSlots;
1455 }
1456 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
1457 mName, input->numExtraSlots);
1458 } else {
1459 input->numSlots = newNumSlots;
1460 }
1461 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001462
1463 if (outputFormat != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001464 Mutexed<Output>::Locked output(mOutput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001465 ALOGD("[%s] onWorkDone: output format changed to %s",
1466 mName, outputFormat->debugString().c_str());
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001467 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001468
1469 AString mediaType;
1470 if (outputFormat->findString(KEY_MIME, &mediaType)
1471 && mediaType == MIMETYPE_AUDIO_RAW) {
1472 int32_t channelCount;
1473 int32_t sampleRate;
1474 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1475 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001476 output->buffers->updateSkipCutBuffer(sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001477 }
1478 }
1479 }
1480
1481 int32_t flags = 0;
1482 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
1483 flags |= MediaCodec::BUFFER_FLAG_EOS;
1484 ALOGV("[%s] onWorkDone: output EOS", mName);
1485 }
1486
1487 sp<MediaCodecBuffer> outBuffer;
1488 size_t index;
1489
1490 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
1491 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
1492 // the codec input timestamp, but client output timestamp should (reported in timeUs)
1493 // shall correspond to the client input timesamp (in customOrdinal). By using the
1494 // delta between the two, this allows for some timestamp deviation - e.g. if one input
1495 // produces multiple output.
1496 c2_cntr64_t timestamp =
1497 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
1498 - work->input.ordinal.timestamp;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001499 if (mInputSurface != nullptr) {
1500 // When using input surface we need to restore the original input timestamp.
1501 timestamp = work->input.ordinal.customOrdinal;
1502 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001503 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
1504 mName,
1505 work->input.ordinal.customOrdinal.peekll(),
1506 work->input.ordinal.timestamp.peekll(),
1507 worklet->output.ordinal.timestamp.peekll(),
1508 timestamp.peekll());
1509
1510 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001511 Mutexed<Output>::Locked output(mOutput);
1512 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001513 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
1514 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
1515 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
1516
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001517 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001518 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001519 } else {
1520 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001521 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001522 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001523 return false;
1524 }
1525 }
1526
1527 if (!buffer && !flags) {
1528 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
1529 mName, work->input.ordinal.frameIndex.peekull());
1530 return true;
1531 }
1532
1533 if (buffer) {
1534 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
1535 // TODO: properly translate these to metadata
1536 switch (info->coreIndex().coreIndex()) {
1537 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001538 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001539 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
1540 }
1541 break;
1542 default:
1543 break;
1544 }
1545 }
1546 }
1547
1548 {
1549 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1550 reorder->emplace(buffer, timestamp.peek(), flags, worklet->output.ordinal);
1551 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
1552 // Flush reorder stash
1553 reorder->setDepth(0);
1554 }
1555 }
1556 sendOutputBuffers();
1557 return true;
1558}
1559
1560void CCodecBufferChannel::sendOutputBuffers() {
1561 ReorderStash::Entry entry;
1562 sp<MediaCodecBuffer> outBuffer;
1563 size_t index;
1564
1565 while (true) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001566 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
1567 if (!reorder->hasPending()) {
1568 break;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001569 }
Wonsik Kim38ad3412019-02-01 15:13:23 -08001570 if (!reorder->pop(&entry)) {
1571 break;
1572 }
1573
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001574 Mutexed<Output>::Locked output(mOutput);
1575 status_t err = output->buffers->registerBuffer(entry.buffer, &index, &outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001576 if (err != OK) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001577 bool outputBuffersChanged = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001578 if (err != WOULD_BLOCK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001579 if (!output->buffers->isArrayMode()) {
1580 output->buffers = output->buffers->toArrayMode(output->numSlots);
Wonsik Kim186fdbf2019-01-29 13:30:01 -08001581 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001582 OutputBuffersArray *array = (OutputBuffersArray *)output->buffers.get();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001583 array->realloc(entry.buffer);
Wonsik Kim38ad3412019-02-01 15:13:23 -08001584 outputBuffersChanged = true;
1585 }
1586 ALOGV("[%s] sendOutputBuffers: unable to register output buffer", mName);
1587 reorder->defer(entry);
1588
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001589 output.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08001590 reorder.unlock();
1591
1592 if (outputBuffersChanged) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001593 mCCodecCallback->onOutputBuffersChanged();
1594 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001595 return;
1596 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001597 output.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08001598 reorder.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001599
1600 outBuffer->meta()->setInt64("timeUs", entry.timestamp);
1601 outBuffer->meta()->setInt32("flags", entry.flags);
Wonsik Kim66427432019-03-21 15:06:22 -07001602 ALOGV("[%s] sendOutputBuffers: out buffer index = %zu [%p] => %p + %zu (%lld)",
1603 mName, index, outBuffer.get(), outBuffer->data(), outBuffer->size(),
1604 (long long)entry.timestamp);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001605 mCallback->onOutputBufferAvailable(index, outBuffer);
1606 }
1607}
1608
1609status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
1610 static std::atomic_uint32_t surfaceGeneration{0};
1611 uint32_t generation = (getpid() << 10) |
1612 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
1613 & ((1 << 10) - 1));
1614
1615 sp<IGraphicBufferProducer> producer;
1616 if (newSurface) {
1617 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08001618 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Lee08515812019-06-05 11:16:32 -07001619 newSurface->setMaxDequeuedBufferCount(mOutputSurface.lock()->maxDequeueBuffers);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001620 producer = newSurface->getIGraphicBufferProducer();
1621 producer->setGenerationNumber(generation);
1622 } else {
1623 ALOGE("[%s] setting output surface to null", mName);
1624 return INVALID_OPERATION;
1625 }
1626
1627 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
1628 C2BlockPool::local_id_t outputPoolId;
1629 {
1630 Mutexed<BlockPools>::Locked pools(mBlockPools);
1631 outputPoolId = pools->outputPoolId;
1632 outputPoolIntf = pools->outputPoolIntf;
1633 }
1634
1635 if (outputPoolIntf) {
1636 if (mComponent->setOutputSurface(
1637 outputPoolId,
1638 producer,
1639 generation) != C2_OK) {
1640 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
1641 return INVALID_OPERATION;
1642 }
1643 }
1644
1645 {
1646 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1647 output->surface = newSurface;
1648 output->generation = generation;
1649 }
1650
1651 return OK;
1652}
1653
Wonsik Kimab34ed62019-01-31 15:28:46 -08001654PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001655 // When client pushed EOS, we want all the work to be done quickly.
1656 // Otherwise, component may have stalled work due to input starvation up to
1657 // the sum of the delay in the pipeline.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07001658 size_t n = 0;
1659 if (!mInputMetEos) {
1660 size_t outputDelay = mOutput.lock()->outputDelay;
1661 Mutexed<Input>::Locked input(mInput);
1662 n = input->inputDelay + input->pipelineDelay + outputDelay;
1663 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001664 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001665}
1666
Pawin Vongmasa36653902018-11-15 00:10:25 -08001667void CCodecBufferChannel::setMetaMode(MetaMode mode) {
1668 mMetaMode = mode;
1669}
1670
Wonsik Kim596187e2019-10-25 12:44:10 -07001671void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
1672 mCrypto = crypto;
1673}
1674
1675void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
1676 mDescrambler = descrambler;
1677}
1678
Pawin Vongmasa36653902018-11-15 00:10:25 -08001679status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
1680 // C2_OK is always translated to OK.
1681 if (c2s == C2_OK) {
1682 return OK;
1683 }
1684
1685 // Operation-dependent translation
1686 // TODO: Add as necessary
1687 switch (c2op) {
1688 case C2_OPERATION_Component_start:
1689 switch (c2s) {
1690 case C2_NO_MEMORY:
1691 return NO_MEMORY;
1692 default:
1693 return UNKNOWN_ERROR;
1694 }
1695 default:
1696 break;
1697 }
1698
1699 // Backup operation-agnostic translation
1700 switch (c2s) {
1701 case C2_BAD_INDEX:
1702 return BAD_INDEX;
1703 case C2_BAD_VALUE:
1704 return BAD_VALUE;
1705 case C2_BLOCKING:
1706 return WOULD_BLOCK;
1707 case C2_DUPLICATE:
1708 return ALREADY_EXISTS;
1709 case C2_NO_INIT:
1710 return NO_INIT;
1711 case C2_NO_MEMORY:
1712 return NO_MEMORY;
1713 case C2_NOT_FOUND:
1714 return NAME_NOT_FOUND;
1715 case C2_TIMED_OUT:
1716 return TIMED_OUT;
1717 case C2_BAD_STATE:
1718 case C2_CANCELED:
1719 case C2_CANNOT_DO:
1720 case C2_CORRUPTED:
1721 case C2_OMITTED:
1722 case C2_REFUSED:
1723 return UNKNOWN_ERROR;
1724 default:
1725 return -static_cast<status_t>(c2s);
1726 }
1727}
1728
1729} // namespace android