blob: e254af1130c5d589c265110d2ad55c0a09ae5b57 [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
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010018#include <utils/Errors.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080019#define LOG_TAG "CCodecBufferChannel"
My Name6bd9a7d2022-03-25 12:37:58 -070020#define ATRACE_TAG ATRACE_TAG_VIDEO
Pawin Vongmasa36653902018-11-15 00:10:25 -080021#include <utils/Log.h>
My Name6bd9a7d2022-03-25 12:37:58 -070022#include <utils/Trace.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080023
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070024#include <algorithm>
Wonsik Kim6b2c8be2021-09-28 05:11:04 -070025#include <atomic>
Pawin Vongmasae7bb8612020-06-04 06:15:22 -070026#include <list>
Pawin Vongmasa36653902018-11-15 00:10:25 -080027#include <numeric>
Arun Johnson326166e2023-07-28 19:11:52 +000028#include <thread>
29#include <chrono>
Pawin Vongmasa36653902018-11-15 00:10:25 -080030
Harish Mahendrakar38a99c22024-02-26 20:28:05 +053031#include <android_media_codec.h>
32
Pawin Vongmasa36653902018-11-15 00:10:25 -080033#include <C2AllocatorGralloc.h>
34#include <C2PlatformSupport.h>
35#include <C2BlockInternal.h>
36#include <C2Config.h>
37#include <C2Debug.h>
38
39#include <android/hardware/cas/native/1.0/IDescrambler.h>
Robert Shih895fba92019-07-16 16:29:44 -070040#include <android/hardware/drm/1.0/types.h>
Wonsik Kimc556d802024-10-15 21:42:25 +000041#include <android/sysprop/MediaProperties.sysprop.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070042#include <android-base/parseint.h>
Josh Hou8eddf4b2021-02-02 16:26:53 +080043#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080044#include <android-base/stringprintf.h>
Wonsik Kimfb7a7672019-12-27 17:13:33 -080045#include <binder/MemoryBase.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080046#include <binder/MemoryDealer.h>
Ray Essick18ea0452019-08-27 16:07:27 -070047#include <cutils/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080048#include <gui/Surface.h>
Robert Shih895fba92019-07-16 16:29:44 -070049#include <hidlmemory/FrameworkUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080050#include <media/openmax/OMX_Core.h>
51#include <media/stagefright/foundation/ABuffer.h>
52#include <media/stagefright/foundation/ALookup.h>
53#include <media/stagefright/foundation/AMessage.h>
54#include <media/stagefright/foundation/AUtils.h>
55#include <media/stagefright/foundation/hexdump.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080056#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070057#include <media/stagefright/SkipCutBuffer.h>
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +010058#include <media/stagefright/SurfaceUtils.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080059#include <media/MediaCodecBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070060#include <mediadrm/ICrypto.h>
Wonsik Kim3a692e62023-05-19 15:37:22 -070061#include <server_configurable_flags/get_flags.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080062#include <system/window.h>
63
64#include "CCodecBufferChannel.h"
65#include "Codec2Buffer.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080066
67namespace android {
68
69using android::base::StringPrintf;
70using hardware::hidl_handle;
71using hardware::hidl_string;
72using hardware::hidl_vec;
Robert Shih895fba92019-07-16 16:29:44 -070073using hardware::fromHeap;
74using hardware::HidlMemory;
Brian Lindahld7967a92023-08-10 10:12:49 -060075using server_configurable_flags::GetServerConfigurableFlag;
Robert Shih895fba92019-07-16 16:29:44 -070076
Pawin Vongmasa36653902018-11-15 00:10:25 -080077using namespace hardware::cas::V1_0;
78using namespace hardware::cas::native::V1_0;
79
80using CasStatus = hardware::cas::V1_0::Status;
Robert Shih895fba92019-07-16 16:29:44 -070081using DrmBufferType = hardware::drm::V1_0::BufferType;
Pawin Vongmasa36653902018-11-15 00:10:25 -080082
Pawin Vongmasa36653902018-11-15 00:10:25 -080083namespace {
84
Wonsik Kim469c8342019-04-11 16:46:09 -070085constexpr size_t kSmoothnessFactor = 4;
Pawin Vongmasa36653902018-11-15 00:10:25 -080086
Sungtak Leeab6f2f32019-02-15 14:43:51 -080087// This is for keeping IGBP's buffer dropping logic in legacy mode other
88// than making it non-blocking. Do not change this value.
89const static size_t kDequeueTimeoutNs = 0;
90
Brian Lindahld7967a92023-08-10 10:12:49 -060091static bool areRenderMetricsEnabled() {
92 std::string v = GetServerConfigurableFlag("media_native", "render_metrics_enabled", "false");
93 return v == "true";
94}
95
Arun Johnsonf4a81f72023-11-09 21:22:48 +000096// Flags can come with individual BufferInfos
97// when used with large frame audio
98constexpr static std::initializer_list<std::pair<uint32_t, uint32_t>> flagList = {
99 {BUFFER_FLAG_CODEC_CONFIG, C2FrameData::FLAG_CODEC_CONFIG},
100 {BUFFER_FLAG_END_OF_STREAM, C2FrameData::FLAG_END_OF_STREAM},
101 {BUFFER_FLAG_DECODE_ONLY, C2FrameData::FLAG_DROP_FRAME}
102};
103
104static uint32_t convertFlags(uint32_t flags, bool toC2) {
105 return std::transform_reduce(
106 flagList.begin(), flagList.end(),
107 0u,
108 std::bit_or{},
109 [flags, toC2](const std::pair<uint32_t, uint32_t> &entry) {
110 if (toC2) {
111 return (flags & entry.first) ? entry.second : 0;
112 } else {
113 return (flags & entry.second) ? entry.first : 0;
114 }
115 });
116}
117
Pawin Vongmasa36653902018-11-15 00:10:25 -0800118} // namespace
119
120CCodecBufferChannel::QueueGuard::QueueGuard(
121 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
122 Mutex::Autolock l(mSync.mGuardLock);
123 // At this point it's guaranteed that mSync is not under state transition,
124 // as we are holding its mutex.
125
126 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
127 if (count->value == -1) {
128 mRunning = false;
129 } else {
130 ++count->value;
131 mRunning = true;
132 }
133}
134
135CCodecBufferChannel::QueueGuard::~QueueGuard() {
136 if (mRunning) {
137 // We are not holding mGuardLock at this point so that QueueSync::stop() can
138 // keep holding the lock until mCount reaches zero.
139 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
140 --count->value;
141 count->cond.broadcast();
142 }
143}
144
145void CCodecBufferChannel::QueueSync::start() {
146 Mutex::Autolock l(mGuardLock);
147 // If stopped, it goes to running state; otherwise no-op.
148 Mutexed<Counter>::Locked count(mCount);
149 if (count->value == -1) {
150 count->value = 0;
151 }
152}
153
154void CCodecBufferChannel::QueueSync::stop() {
155 Mutex::Autolock l(mGuardLock);
156 Mutexed<Counter>::Locked count(mCount);
157 if (count->value == -1) {
158 // no-op
159 return;
160 }
161 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
162 // mCount can only decrement. In other words, threads that acquired the lock
163 // are allowed to finish execution but additional threads trying to acquire
164 // the lock at this point will block, and then get QueueGuard at STOPPED
165 // state.
166 while (count->value != 0) {
167 count.waitForCondition(count->cond);
168 }
169 count->value = -1;
170}
171
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700172// Input
173
174CCodecBufferChannel::Input::Input() : extraBuffers("extra") {}
175
Pawin Vongmasa36653902018-11-15 00:10:25 -0800176// CCodecBufferChannel
177
178CCodecBufferChannel::CCodecBufferChannel(
179 const std::shared_ptr<CCodecCallback> &callback)
180 : mHeapSeqNum(-1),
181 mCCodecCallback(callback),
182 mFrameIndex(0u),
183 mFirstValidFrameIndex(0u),
Brian Lindahld7967a92023-08-10 10:12:49 -0600184 mAreRenderMetricsEnabled(areRenderMetricsEnabled()),
Brian Lindahl2048d492023-04-05 08:49:23 -0600185 mIsSurfaceToDisplay(false),
186 mHasPresentFenceTimes(false),
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700187 mRenderingDepth(3u),
Pawin Vongmasa36653902018-11-15 00:10:25 -0800188 mMetaMode(MODE_NONE),
Sungtak Lee04b30352020-07-27 13:57:25 -0700189 mInputMetEos(false),
190 mSendEncryptedInfoBuffer(false) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700191 {
192 Mutexed<Input>::Locked input(mInput);
193 input->buffers.reset(new DummyInputBuffers(""));
194 input->extraBuffers.flush();
195 input->inputDelay = 0u;
196 input->pipelineDelay = 0u;
197 input->numSlots = kSmoothnessFactor;
198 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -0700199 input->lastFlushIndex = 0u;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700200 }
201 {
202 Mutexed<Output>::Locked output(mOutput);
203 output->outputDelay = 0u;
204 output->numSlots = kSmoothnessFactor;
Wonsik Kim3722abc2023-05-17 13:26:31 -0700205 output->bounded = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700206 }
David Stevensc3fbb282021-01-18 18:11:20 +0900207 {
208 Mutexed<BlockPools>::Locked pools(mBlockPools);
209 pools->outputPoolId = C2BlockPool::BASIC_LINEAR;
210 }
Wonsik Kimc556d802024-10-15 21:42:25 +0000211 if (android::media::codec::provider_->rendering_depth_removal()) {
212 constexpr int kAndroidApi202404 = 202404;
213 int vendorVersion = ::android::base::GetIntProperty("ro.vendor.api_level", -1);
214 using ::android::sysprop::MediaProperties::codec2_remove_rendering_depth;
215 if (vendorVersion > kAndroidApi202404 || codec2_remove_rendering_depth().value_or(false)) {
216 mRenderingDepth = 0;
217 }
218 } else {
219 std::string value = GetServerConfigurableFlag(
220 "media_native", "ccodec_rendering_depth", "3");
221 android::base::ParseInt(value, &mRenderingDepth);
222 }
Wonsik Kimb6ee72a2023-06-07 23:59:01 -0700223 mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800224}
225
226CCodecBufferChannel::~CCodecBufferChannel() {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800227 if (mCrypto != nullptr && mHeapSeqNum >= 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800228 mCrypto->unsetHeap(mHeapSeqNum);
229 }
230}
231
232void CCodecBufferChannel::setComponent(
233 const std::shared_ptr<Codec2Client::Component> &component) {
Sungtak Lee368452b2024-10-17 01:16:29 +0000234 std::atomic_store(&mComponent, component);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800235 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
236 mName = mComponentName.c_str();
237}
238
239status_t CCodecBufferChannel::setInputSurface(
240 const std::shared_ptr<InputSurfaceWrapper> &surface) {
241 ALOGV("[%s] setInputSurface", mName);
Wonsik Kimfca97a22024-08-30 20:20:42 +0000242 if (!surface) {
243 ALOGE("[%s] setInputSurface: surface must not be null", mName);
244 return BAD_VALUE;
245 }
246 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
247 inputSurface->numProcessingBuffersBalance = 0;
248 inputSurface->surface = surface;
249 mHasInputSurface = true;
Sungtak Lee368452b2024-10-17 01:16:29 +0000250 return inputSurface->surface->connect(std::atomic_load(&mComponent));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800251}
252
253status_t CCodecBufferChannel::signalEndOfInputStream() {
Wonsik Kimfca97a22024-08-30 20:20:42 +0000254 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
255 if (inputSurface->surface == nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800256 return INVALID_OPERATION;
257 }
Wonsik Kimfca97a22024-08-30 20:20:42 +0000258 return inputSurface->surface->signalEndOfInputStream();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800259}
260
Sungtak Lee04b30352020-07-27 13:57:25 -0700261status_t CCodecBufferChannel::queueInputBufferInternal(
262 sp<MediaCodecBuffer> buffer,
263 std::shared_ptr<C2LinearBlock> encryptedBlock,
264 size_t blockSize) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800265 int64_t timeUs;
266 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
267
268 if (mInputMetEos) {
269 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
270 return OK;
271 }
272
273 int32_t flags = 0;
274 int32_t tmp = 0;
275 bool eos = false;
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200276 bool tunnelFirstFrame = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800277 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
278 eos = true;
279 mInputMetEos = true;
280 ALOGV("[%s] input EOS", mName);
281 }
282 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
283 flags |= C2FrameData::FLAG_CODEC_CONFIG;
284 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200285 if (buffer->meta()->findInt32("tunnel-first-frame", &tmp) && tmp) {
286 tunnelFirstFrame = true;
287 }
Marc Kassis96343b42022-12-09 11:49:44 +0100288 if (buffer->meta()->findInt32("decode-only", &tmp) && tmp) {
289 flags |= C2FrameData::FLAG_DROP_FRAME;
290 }
Arun Johnsonf4a81f72023-11-09 21:22:48 +0000291 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu time: %lld",
292 mName, buffer->size(), (long long)timeUs);
Wonsik Kime1104ca2020-11-24 15:01:33 -0800293 std::list<std::unique_ptr<C2Work>> items;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800294 std::unique_ptr<C2Work> work(new C2Work);
295 work->input.ordinal.timestamp = timeUs;
296 work->input.ordinal.frameIndex = mFrameIndex++;
297 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
298 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
299 // Keep client timestamp in customOrdinal
300 work->input.ordinal.customOrdinal = timeUs;
301 work->input.buffers.clear();
302
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700303 sp<Codec2Buffer> copy;
Wonsik Kime1104ca2020-11-24 15:01:33 -0800304 bool usesFrameReassembler = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800305
Pawin Vongmasa36653902018-11-15 00:10:25 -0800306 if (buffer->size() > 0u) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700307 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800308 std::shared_ptr<C2Buffer> c2buffer;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700309 if (!input->buffers->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800310 return -ENOENT;
311 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700312 // TODO: we want to delay copying buffers.
313 if (input->extraBuffers.numComponentBuffers() < input->numExtraSlots) {
314 copy = input->buffers->cloneAndReleaseBuffer(buffer);
315 if (copy != nullptr) {
316 (void)input->extraBuffers.assignSlot(copy);
317 if (!input->extraBuffers.releaseSlot(copy, &c2buffer, false)) {
318 return UNKNOWN_ERROR;
319 }
320 bool released = input->buffers->releaseBuffer(buffer, nullptr, true);
321 ALOGV("[%s] queueInputBuffer: buffer copied; %sreleased",
322 mName, released ? "" : "not ");
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700323 buffer = copy;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700324 } else {
325 ALOGW("[%s] queueInputBuffer: failed to copy a buffer; this may cause input "
326 "buffer starvation on component.", mName);
327 }
328 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800329 if (input->frameReassembler) {
330 usesFrameReassembler = true;
331 input->frameReassembler.process(buffer, &items);
332 } else {
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900333 int32_t cvo = 0;
334 if (buffer->meta()->findInt32("cvo", &cvo)) {
335 int32_t rotation = cvo % 360;
336 // change rotation to counter-clock wise.
337 rotation = ((rotation <= 0) ? 0 : 360) - rotation;
338
339 Mutexed<OutputSurface>::Locked output(mOutputSurface);
340 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
341 output->rotation[frameIndex] = rotation;
342 }
Arun Johnsonf4a81f72023-11-09 21:22:48 +0000343 sp<RefBase> obj;
344 if (buffer->meta()->findObject("accessUnitInfo", &obj)) {
345 ALOGV("Filling C2Info from multiple access units");
346 sp<WrapperObject<std::vector<AccessUnitInfo>>> infos{
347 (decltype(infos.get()))obj.get()};
348 std::vector<AccessUnitInfo> &accessUnitInfoVec = infos->value;
349 std::vector<C2AccessUnitInfosStruct> multipleAccessUnitInfos;
350 uint32_t outFlags = 0;
351 for (int i = 0; i < accessUnitInfoVec.size(); i++) {
352 outFlags = 0;
353 outFlags = convertFlags(accessUnitInfoVec[i].mFlags, true);
354 if (eos && (outFlags & C2FrameData::FLAG_END_OF_STREAM)) {
355 outFlags &= (~C2FrameData::FLAG_END_OF_STREAM);
356 }
357 multipleAccessUnitInfos.emplace_back(
358 outFlags,
359 accessUnitInfoVec[i].mSize,
360 accessUnitInfoVec[i].mTimestamp);
361 ALOGV("%d) flags: %d, size: %d, time: %llu",
362 i, outFlags, accessUnitInfoVec[i].mSize,
363 (long long)accessUnitInfoVec[i].mTimestamp);
364
365 }
366 const std::shared_ptr<C2AccessUnitInfos::input> c2AccessUnitInfos =
367 C2AccessUnitInfos::input::AllocShared(
368 multipleAccessUnitInfos.size(), 0u, multipleAccessUnitInfos);
369 c2buffer->setInfo(c2AccessUnitInfos);
370 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800371 work->input.buffers.push_back(c2buffer);
372 if (encryptedBlock) {
373 work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
374 kParamIndexEncryptedBuffer,
375 encryptedBlock->share(0, blockSize, C2Fence())));
376 }
Sungtak Lee04b30352020-07-27 13:57:25 -0700377 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800378 } else if (eos) {
Wonsik Kimcc59ad82021-08-11 18:15:19 -0700379 Mutexed<Input>::Locked input(mInput);
380 if (input->frameReassembler) {
381 usesFrameReassembler = true;
382 // drain any pending items with eos
383 input->frameReassembler.process(buffer, &items);
384 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800385 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800386 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800387 if (usesFrameReassembler) {
388 if (!items.empty()) {
389 items.front()->input.configUpdate = std::move(mParamsToBeSet);
390 mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
391 }
392 } else {
393 work->input.flags = (C2FrameData::flags_t)flags;
Harish Mahendrakar38a99c22024-02-26 20:28:05 +0530394
Wonsik Kime1104ca2020-11-24 15:01:33 -0800395 // TODO: fill info's
Harish Mahendrakar38a99c22024-02-26 20:28:05 +0530396 if (android::media::codec::provider_->region_of_interest()
397 && android::media::codec::provider_->region_of_interest_support()) {
398 if (mInfoBuffers.size()) {
399 for (auto infoBuffer : mInfoBuffers) {
400 work->input.infoBuffers.emplace_back(*infoBuffer);
401 }
402 mInfoBuffers.clear();
403 }
404 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800405
Wonsik Kime1104ca2020-11-24 15:01:33 -0800406 work->input.configUpdate = std::move(mParamsToBeSet);
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200407 if (tunnelFirstFrame) {
408 C2StreamTunnelHoldRender::input tunnelHoldRender{
409 0u /* stream */,
410 C2_TRUE /* value */
411 };
412 work->input.configUpdate.push_back(C2Param::Copy(tunnelHoldRender));
413 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800414 work->worklets.clear();
415 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800416
Wonsik Kime1104ca2020-11-24 15:01:33 -0800417 items.push_back(std::move(work));
418
419 eos = eos && buffer->size() > 0u;
Wonsik Kimab34ed62019-01-31 15:28:46 -0800420 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800421 if (eos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800422 work.reset(new C2Work);
423 work->input.ordinal.timestamp = timeUs;
424 work->input.ordinal.frameIndex = mFrameIndex++;
425 // WORKAROUND: keep client timestamp in customOrdinal
426 work->input.ordinal.customOrdinal = timeUs;
427 work->input.buffers.clear();
428 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800429 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800430 items.push_back(std::move(work));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800431 }
Wonsik Kime1104ca2020-11-24 15:01:33 -0800432 c2_status_t err = C2_OK;
433 if (!items.empty()) {
My Name6bd9a7d2022-03-25 12:37:58 -0700434 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
435 "CCodecBufferChannel::queue(%s@ts=%lld)", mName, (long long)timeUs).c_str());
Wonsik Kime1104ca2020-11-24 15:01:33 -0800436 {
437 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
438 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
439 for (const std::unique_ptr<C2Work> &work : items) {
440 watcher->onWorkQueued(
441 work->input.ordinal.frameIndex.peeku(),
442 std::vector(work->input.buffers),
443 now);
444 }
445 }
Sungtak Lee368452b2024-10-17 01:16:29 +0000446 err = std::atomic_load(&mComponent)->queue(&items);
Wonsik Kime1104ca2020-11-24 15:01:33 -0800447 }
448 if (err != C2_OK) {
449 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
450 for (const std::unique_ptr<C2Work> &work : items) {
451 watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
452 }
453 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700454 Mutexed<Input>::Locked input(mInput);
455 bool released = false;
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700456 if (copy) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700457 released = input->extraBuffers.releaseSlot(copy, nullptr, true);
Wonsik Kimfb5ca492021-08-11 14:18:19 -0700458 } else if (buffer) {
459 released = input->buffers->releaseBuffer(buffer, nullptr, true);
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700460 }
461 ALOGV("[%s] queueInputBuffer: buffer%s %sreleased",
462 mName, (buffer == nullptr) ? "(copy)" : "", released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800463 }
464
465 feedInputBufferIfAvailableInternal();
466 return err;
467}
468
469status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
470 QueueGuard guard(mSync);
471 if (!guard.isRunning()) {
472 ALOGD("[%s] setParameters is only supported in the running state.", mName);
473 return -ENOSYS;
474 }
475 mParamsToBeSet.insert(mParamsToBeSet.end(),
476 std::make_move_iterator(params.begin()),
477 std::make_move_iterator(params.end()));
478 params.clear();
479 return OK;
480}
481
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800482status_t CCodecBufferChannel::attachBuffer(
483 const std::shared_ptr<C2Buffer> &c2Buffer,
484 const sp<MediaCodecBuffer> &buffer) {
485 if (!buffer->copy(c2Buffer)) {
486 return -ENOSYS;
487 }
488 return OK;
489}
490
491void CCodecBufferChannel::ensureDecryptDestination(size_t size) {
492 if (!mDecryptDestination || mDecryptDestination->size() < size) {
493 sp<IMemoryHeap> heap{new MemoryHeapBase(size * 2)};
494 if (mDecryptDestination && mCrypto && mHeapSeqNum >= 0) {
495 mCrypto->unsetHeap(mHeapSeqNum);
496 }
497 mDecryptDestination = new MemoryBase(heap, 0, size * 2);
498 if (mCrypto) {
499 mHeapSeqNum = mCrypto->setHeap(hardware::fromHeap(heap));
500 }
501 }
502}
503
504int32_t CCodecBufferChannel::getHeapSeqNum(const sp<HidlMemory> &memory) {
505 CHECK(mCrypto);
506 auto it = mHeapSeqNumMap.find(memory);
507 int32_t heapSeqNum = -1;
508 if (it == mHeapSeqNumMap.end()) {
509 heapSeqNum = mCrypto->setHeap(memory);
510 mHeapSeqNumMap.emplace(memory, heapSeqNum);
511 } else {
512 heapSeqNum = it->second;
513 }
514 return heapSeqNum;
515}
516
Arun Johnson564f3a92024-02-01 19:09:45 +0000517typedef WrapperObject<std::vector<AccessUnitInfo>> BufferInfosWrapper;
518typedef WrapperObject<std::vector<std::unique_ptr<CodecCryptoInfo>>> CryptoInfosWrapper;
519status_t CCodecBufferChannel::attachEncryptedBuffers(
520 const sp<hardware::HidlMemory> &memory,
521 size_t offset,
522 const sp<MediaCodecBuffer> &buffer,
523 bool secure,
524 AString* errorDetailMsg) {
525 static const C2MemoryUsage kDefaultReadWriteUsage{
526 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
527 if (!hasCryptoOrDescrambler()) {
528 ALOGE("attachEncryptedBuffers requires Crypto/descrambler object");
529 return -ENOSYS;
530 }
531 size_t size = 0;
532 CHECK(buffer->meta()->findSize("ssize", &size));
533 if (size == 0) {
534 buffer->setRange(0, 0);
535 return OK;
536 }
537 sp<RefBase> obj;
538 CHECK(buffer->meta()->findObject("cryptoInfos", &obj));
539 sp<CryptoInfosWrapper> cryptoInfos{(CryptoInfosWrapper *)obj.get()};
540 CHECK(buffer->meta()->findObject("accessUnitInfo", &obj));
541 sp<BufferInfosWrapper> bufferInfos{(BufferInfosWrapper *)obj.get()};
542 if (secure || (mCrypto == nullptr)) {
543 if (cryptoInfos->value.size() != 1) {
544 ALOGE("Cannot decrypt multiple access units");
545 return -ENOSYS;
546 }
547 // we are dealing with just one cryptoInfo or descrambler.
548 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[0]);
549 if (info == nullptr) {
550 ALOGE("Cannot decrypt, CryptoInfos are null.");
551 return -ENOSYS;
552 }
553 return attachEncryptedBuffer(
554 memory,
555 secure,
556 info->mKey,
557 info->mIv,
558 info->mMode,
559 info->mPattern,
560 offset,
561 info->mSubSamples,
562 info->mNumSubSamples,
563 buffer,
564 errorDetailMsg);
565 }
566 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
567 std::shared_ptr<C2LinearBlock> block;
568 c2_status_t err = pool->fetchLinearBlock(
569 size,
570 kDefaultReadWriteUsage,
571 &block);
572 if (err != C2_OK) {
573 ALOGI("[%s] attachEncryptedBuffers: fetchLinearBlock failed: size = %zu (%s) err = %d",
574 mName, size, secure ? "secure" : "non-secure", err);
575 return NO_MEMORY;
576 }
577 ensureDecryptDestination(size);
578 C2WriteView wView = block->map().get();
579 if (wView.error() != C2_OK) {
580 ALOGI("[%s] attachEncryptedBuffers: block map error: %d (non-secure)",
581 mName, wView.error());
582 return UNKNOWN_ERROR;
583 }
584
585 ssize_t result = -1;
Arun Johnson82174a12024-02-27 04:53:59 +0000586 size_t srcOffset = offset;
Arun Johnson564f3a92024-02-01 19:09:45 +0000587 size_t outBufferSize = 0;
588 uint32_t cryptoInfoIdx = 0;
589 int32_t heapSeqNum = getHeapSeqNum(memory);
590 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
591 hardware::drm::V1_0::DestinationBuffer dst;
592 dst.type = DrmBufferType::SHARED_MEMORY;
593 IMemoryToSharedBuffer(
594 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
595 for (int i = 0; i < bufferInfos->value.size(); i++) {
596 if (bufferInfos->value[i].mSize > 0) {
597 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[cryptoInfoIdx++]);
Arun Johnson82174a12024-02-27 04:53:59 +0000598 src.offset = srcOffset;
599 src.size = bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +0000600 result = mCrypto->decrypt(
601 (uint8_t*)info->mKey,
602 (uint8_t*)info->mIv,
603 info->mMode,
604 info->mPattern,
605 src,
Arun Johnson82174a12024-02-27 04:53:59 +0000606 0,
Arun Johnson564f3a92024-02-01 19:09:45 +0000607 info->mSubSamples,
608 info->mNumSubSamples,
609 dst,
610 errorDetailMsg);
Arun Johnson82174a12024-02-27 04:53:59 +0000611 srcOffset += bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +0000612 if (result < 0) {
613 ALOGI("[%s] attachEncryptedBuffers: decrypt failed: result = %zd",
614 mName, result);
615 return result;
616 }
617 if (wView.error() == C2_OK) {
618 if (wView.size() < result) {
619 ALOGI("[%s] attachEncryptedBuffers: block size too small:"
620 "size=%u result=%zd (non-secure)", mName, wView.size(), result);
621 return UNKNOWN_ERROR;
622 }
623 memcpy(wView.data(), mDecryptDestination->unsecurePointer(), result);
624 bufferInfos->value[i].mSize = result;
625 wView.setOffset(wView.offset() + result);
626 }
627 outBufferSize += result;
628 }
629 }
630 if (wView.error() == C2_OK) {
631 wView.setOffset(0);
632 }
633 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
Arun Johnson82174a12024-02-27 04:53:59 +0000634 block->share(0, outBufferSize, C2Fence{}))};
Arun Johnson564f3a92024-02-01 19:09:45 +0000635 if (!buffer->copy(c2Buffer)) {
636 ALOGI("[%s] attachEncryptedBuffers: buffer copy failed", mName);
637 return -ENOSYS;
638 }
639 return OK;
640}
641
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800642status_t CCodecBufferChannel::attachEncryptedBuffer(
643 const sp<hardware::HidlMemory> &memory,
644 bool secure,
645 const uint8_t *key,
646 const uint8_t *iv,
647 CryptoPlugin::Mode mode,
648 CryptoPlugin::Pattern pattern,
649 size_t offset,
650 const CryptoPlugin::SubSample *subSamples,
651 size_t numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000652 const sp<MediaCodecBuffer> &buffer,
653 AString* errorDetailMsg) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800654 static const C2MemoryUsage kSecureUsage{C2MemoryUsage::READ_PROTECTED, 0};
655 static const C2MemoryUsage kDefaultReadWriteUsage{
656 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
657
658 size_t size = 0;
659 for (size_t i = 0; i < numSubSamples; ++i) {
660 size += subSamples[i].mNumBytesOfClearData + subSamples[i].mNumBytesOfEncryptedData;
661 }
Wonsik Kim59e65362022-05-24 14:20:50 -0700662 if (size == 0) {
663 buffer->setRange(0, 0);
664 return OK;
665 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800666 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
667 std::shared_ptr<C2LinearBlock> block;
668 c2_status_t err = pool->fetchLinearBlock(
669 size,
670 secure ? kSecureUsage : kDefaultReadWriteUsage,
671 &block);
672 if (err != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700673 ALOGI("[%s] attachEncryptedBuffer: fetchLinearBlock failed: size = %zu (%s) err = %d",
674 mName, size, secure ? "secure" : "non-secure", err);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800675 return NO_MEMORY;
676 }
677 if (!secure) {
678 ensureDecryptDestination(size);
679 }
680 ssize_t result = -1;
681 ssize_t codecDataOffset = 0;
682 if (mCrypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800683 int32_t heapSeqNum = getHeapSeqNum(memory);
684 hardware::drm::V1_0::SharedBuffer src{(uint32_t)heapSeqNum, offset, size};
685 hardware::drm::V1_0::DestinationBuffer dst;
686 if (secure) {
687 dst.type = DrmBufferType::NATIVE_HANDLE;
688 dst.secureMemory = hardware::hidl_handle(block->handle());
689 } else {
690 dst.type = DrmBufferType::SHARED_MEMORY;
691 IMemoryToSharedBuffer(
692 mDecryptDestination, mHeapSeqNum, &dst.nonsecureMemory);
693 }
694 result = mCrypto->decrypt(
695 key, iv, mode, pattern, src, 0, subSamples, numSubSamples,
Arun Johnson634d0802023-02-14 22:07:51 +0000696 dst, errorDetailMsg);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800697 if (result < 0) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700698 ALOGI("[%s] attachEncryptedBuffer: decrypt failed: result = %zd", mName, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800699 return result;
700 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800701 } else {
702 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
703 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
704 hidl_vec<SubSample> hidlSubSamples;
705 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
706
707 hardware::cas::native::V1_0::SharedBuffer src{*memory, offset, size};
708 hardware::cas::native::V1_0::DestinationBuffer dst;
709 if (secure) {
710 dst.type = BufferType::NATIVE_HANDLE;
711 dst.secureMemory = hardware::hidl_handle(block->handle());
712 } else {
713 dst.type = BufferType::SHARED_MEMORY;
714 dst.nonsecureMemory = src;
715 }
716
717 CasStatus status = CasStatus::OK;
718 hidl_string detailedError;
719 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
720
721 if (key != nullptr) {
722 sctrl = (ScramblingControl)key[0];
723 // Adjust for the PES offset
724 codecDataOffset = key[2] | (key[3] << 8);
725 }
726
727 auto returnVoid = mDescrambler->descramble(
728 sctrl,
729 hidlSubSamples,
730 src,
731 0,
732 dst,
733 0,
734 [&status, &result, &detailedError] (
735 CasStatus _status, uint32_t _bytesWritten,
736 const hidl_string& _detailedError) {
737 status = _status;
738 result = (ssize_t)_bytesWritten;
739 detailedError = _detailedError;
740 });
Arun Johnson634d0802023-02-14 22:07:51 +0000741 if (errorDetailMsg) {
742 errorDetailMsg->setTo(detailedError.c_str(), detailedError.size());
743 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800744 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
745 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
746 mName, returnVoid.description().c_str(), status, result);
747 return UNKNOWN_ERROR;
748 }
749
750 if (result < codecDataOffset) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700751 ALOGD("[%s] invalid codec data offset: %zd, result %zd",
752 mName, codecDataOffset, result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800753 return BAD_VALUE;
754 }
755 }
756 if (!secure) {
757 C2WriteView view = block->map().get();
758 if (view.error() != C2_OK) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700759 ALOGI("[%s] attachEncryptedBuffer: block map error: %d (non-secure)",
760 mName, view.error());
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800761 return UNKNOWN_ERROR;
762 }
763 if (view.size() < result) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700764 ALOGI("[%s] attachEncryptedBuffer: block size too small: size=%u result=%zd "
765 "(non-secure)",
766 mName, view.size(), result);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800767 return UNKNOWN_ERROR;
768 }
769 memcpy(view.data(), mDecryptDestination->unsecurePointer(), result);
770 }
771 std::shared_ptr<C2Buffer> c2Buffer{C2Buffer::CreateLinearBuffer(
772 block->share(codecDataOffset, result - codecDataOffset, C2Fence{}))};
773 if (!buffer->copy(c2Buffer)) {
Wonsik Kim59e65362022-05-24 14:20:50 -0700774 ALOGI("[%s] attachEncryptedBuffer: buffer copy failed", mName);
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800775 return -ENOSYS;
776 }
777 return OK;
778}
779
Pawin Vongmasa36653902018-11-15 00:10:25 -0800780status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
781 QueueGuard guard(mSync);
782 if (!guard.isRunning()) {
783 ALOGD("[%s] No more buffers should be queued at current state.", mName);
784 return -ENOSYS;
785 }
786 return queueInputBufferInternal(buffer);
787}
788
789status_t CCodecBufferChannel::queueSecureInputBuffer(
790 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
791 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
792 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
793 AString *errorDetailMsg) {
794 QueueGuard guard(mSync);
795 if (!guard.isRunning()) {
796 ALOGD("[%s] No more buffers should be queued at current state.", mName);
797 return -ENOSYS;
798 }
799
800 if (!hasCryptoOrDescrambler()) {
801 return -ENOSYS;
802 }
803 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
804
Sungtak Lee04b30352020-07-27 13:57:25 -0700805 std::shared_ptr<C2LinearBlock> block;
806 size_t allocSize = buffer->size();
807 size_t bufferSize = 0;
808 c2_status_t blockRes = C2_OK;
809 bool copied = false;
Arun Johnson7ba67072023-11-06 22:23:04 +0000810 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
811 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
Sungtak Lee04b30352020-07-27 13:57:25 -0700812 if (mSendEncryptedInfoBuffer) {
813 static const C2MemoryUsage kDefaultReadWriteUsage{
814 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
815 constexpr int kAllocGranule0 = 1024 * 64;
816 constexpr int kAllocGranule1 = 1024 * 1024;
817 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
818 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
819 if (allocSize <= kAllocGranule1) {
820 bufferSize = align(allocSize, kAllocGranule0);
821 } else {
822 bufferSize = align(allocSize, kAllocGranule1);
823 }
824 blockRes = pool->fetchLinearBlock(
825 bufferSize, kDefaultReadWriteUsage, &block);
826
827 if (blockRes == C2_OK) {
828 C2WriteView view = block->map().get();
829 if (view.error() == C2_OK && view.size() == bufferSize) {
830 copied = true;
831 // TODO: only copy clear sections
832 memcpy(view.data(), buffer->data(), allocSize);
833 }
834 }
835 }
836
837 if (!copied) {
838 block.reset();
839 }
840
Pawin Vongmasa36653902018-11-15 00:10:25 -0800841 ssize_t result = -1;
842 ssize_t codecDataOffset = 0;
Wonsik Kim557c88c2020-03-13 11:03:52 -0700843 if (numSubSamples == 1
844 && subSamples[0].mNumBytesOfClearData == 0
845 && subSamples[0].mNumBytesOfEncryptedData == 0) {
846 // We don't need to go through crypto or descrambler if the input is empty.
847 result = 0;
848 } else if (mCrypto != nullptr) {
Robert Shih895fba92019-07-16 16:29:44 -0700849 hardware::drm::V1_0::DestinationBuffer destination;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800850 if (secure) {
Robert Shih895fba92019-07-16 16:29:44 -0700851 destination.type = DrmBufferType::NATIVE_HANDLE;
852 destination.secureMemory = hidl_handle(encryptedBuffer->handle());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800853 } else {
Robert Shih895fba92019-07-16 16:29:44 -0700854 destination.type = DrmBufferType::SHARED_MEMORY;
855 IMemoryToSharedBuffer(
856 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800857 }
Robert Shih895fba92019-07-16 16:29:44 -0700858 hardware::drm::V1_0::SharedBuffer source;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800859 encryptedBuffer->fillSourceBuffer(&source);
860 result = mCrypto->decrypt(
861 key, iv, mode, pattern, source, buffer->offset(),
862 subSamples, numSubSamples, destination, errorDetailMsg);
863 if (result < 0) {
Wonsik Kim557c88c2020-03-13 11:03:52 -0700864 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800865 return result;
866 }
Robert Shih895fba92019-07-16 16:29:44 -0700867 if (destination.type == DrmBufferType::SHARED_MEMORY) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800868 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
869 }
870 } else {
871 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
872 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
873 hidl_vec<SubSample> hidlSubSamples;
874 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
875
876 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
877 encryptedBuffer->fillSourceBuffer(&srcBuffer);
878
879 DestinationBuffer dstBuffer;
880 if (secure) {
881 dstBuffer.type = BufferType::NATIVE_HANDLE;
882 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
883 } else {
884 dstBuffer.type = BufferType::SHARED_MEMORY;
885 dstBuffer.nonsecureMemory = srcBuffer;
886 }
887
888 CasStatus status = CasStatus::OK;
889 hidl_string detailedError;
890 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
891
892 if (key != nullptr) {
893 sctrl = (ScramblingControl)key[0];
894 // Adjust for the PES offset
895 codecDataOffset = key[2] | (key[3] << 8);
896 }
897
898 auto returnVoid = mDescrambler->descramble(
899 sctrl,
900 hidlSubSamples,
901 srcBuffer,
902 0,
903 dstBuffer,
904 0,
905 [&status, &result, &detailedError] (
906 CasStatus _status, uint32_t _bytesWritten,
907 const hidl_string& _detailedError) {
908 status = _status;
909 result = (ssize_t)_bytesWritten;
910 detailedError = _detailedError;
911 });
912
913 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
914 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
915 mName, returnVoid.description().c_str(), status, result);
916 return UNKNOWN_ERROR;
917 }
918
919 if (result < codecDataOffset) {
920 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
921 return BAD_VALUE;
922 }
923
924 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
925
926 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
927 encryptedBuffer->copyDecryptedContentFromMemory(result);
928 }
929 }
930
931 buffer->setRange(codecDataOffset, result - codecDataOffset);
Sungtak Lee04b30352020-07-27 13:57:25 -0700932
933 return queueInputBufferInternal(buffer, block, bufferSize);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800934}
935
Arun Johnson564f3a92024-02-01 19:09:45 +0000936status_t CCodecBufferChannel::queueSecureInputBuffers(
937 const sp<MediaCodecBuffer> &buffer,
938 bool secure,
939 AString *errorDetailMsg) {
940 QueueGuard guard(mSync);
941 if (!guard.isRunning()) {
942 ALOGD("[%s] No more buffers should be queued at current state.", mName);
943 return -ENOSYS;
944 }
945
946 if (!hasCryptoOrDescrambler()) {
947 ALOGE("queueSecureInputBuffers requires a Crypto/descrambler Object");
948 return -ENOSYS;
949 }
950 sp<RefBase> obj;
951 CHECK(buffer->meta()->findObject("cryptoInfos", &obj));
952 sp<CryptoInfosWrapper> cryptoInfos{(CryptoInfosWrapper *)obj.get()};
953 CHECK(buffer->meta()->findObject("accessUnitInfo", &obj));
954 sp<BufferInfosWrapper> bufferInfos{(BufferInfosWrapper *)obj.get()};
955 if (secure || mCrypto == nullptr) {
956 if (cryptoInfos->value.size() != 1) {
957 ALOGE("Cannot decrypt multiple access units on native handles");
958 return -ENOSYS;
959 }
960 std::unique_ptr<CodecCryptoInfo> info = std::move(cryptoInfos->value[0]);
961 if (info == nullptr) {
962 ALOGE("Cannot decrypt, CryptoInfos are null");
963 return -ENOSYS;
964 }
965 return queueSecureInputBuffer(
966 buffer,
967 secure,
968 info->mKey,
969 info->mIv,
970 info->mMode,
971 info->mPattern,
972 info->mSubSamples,
973 info->mNumSubSamples,
974 errorDetailMsg);
975 }
976 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
977
978 std::shared_ptr<C2LinearBlock> block;
979 size_t allocSize = buffer->size();
980 size_t bufferSize = 0;
981 c2_status_t blockRes = C2_OK;
982 bool copied = false;
983 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
984 "CCodecBufferChannel::decrypt(%s)", mName).c_str());
985 if (mSendEncryptedInfoBuffer) {
986 static const C2MemoryUsage kDefaultReadWriteUsage{
987 C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
988 constexpr int kAllocGranule0 = 1024 * 64;
989 constexpr int kAllocGranule1 = 1024 * 1024;
990 std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
991 // round up encrypted sizes to limit fragmentation and encourage buffer reuse
992 if (allocSize <= kAllocGranule1) {
993 bufferSize = align(allocSize, kAllocGranule0);
994 } else {
995 bufferSize = align(allocSize, kAllocGranule1);
996 }
997 blockRes = pool->fetchLinearBlock(
998 bufferSize, kDefaultReadWriteUsage, &block);
999
1000 if (blockRes == C2_OK) {
1001 C2WriteView view = block->map().get();
1002 if (view.error() == C2_OK && view.size() == bufferSize) {
1003 copied = true;
1004 // TODO: only copy clear sections
1005 memcpy(view.data(), buffer->data(), allocSize);
1006 }
1007 }
1008 }
1009
1010 if (!copied) {
1011 block.reset();
1012 }
1013 // size of cryptoInfo and accessUnitInfo should be the same?
1014 ssize_t result = -1;
Arun Johnson82174a12024-02-27 04:53:59 +00001015 size_t srcOffset = 0;
Arun Johnson564f3a92024-02-01 19:09:45 +00001016 size_t outBufferSize = 0;
1017 uint32_t cryptoInfoIdx = 0;
1018 {
1019 // scoped this block to enable destruction of mappedBlock
1020 std::unique_ptr<EncryptedLinearBlockBuffer::MappedBlock> mappedBlock = nullptr;
1021 hardware::drm::V1_0::DestinationBuffer destination;
1022 destination.type = DrmBufferType::SHARED_MEMORY;
1023 IMemoryToSharedBuffer(
1024 mDecryptDestination, mHeapSeqNum, &destination.nonsecureMemory);
1025 encryptedBuffer->getMappedBlock(&mappedBlock);
1026 hardware::drm::V1_0::SharedBuffer source;
1027 encryptedBuffer->fillSourceBuffer(&source);
Arun Johnson82174a12024-02-27 04:53:59 +00001028 srcOffset = source.offset;
Arun Johnson564f3a92024-02-01 19:09:45 +00001029 for (int i = 0 ; i < bufferInfos->value.size(); i++) {
1030 if (bufferInfos->value[i].mSize > 0) {
1031 std::unique_ptr<CodecCryptoInfo> info =
1032 std::move(cryptoInfos->value[cryptoInfoIdx++]);
1033 if (info->mNumSubSamples == 1
1034 && info->mSubSamples[0].mNumBytesOfClearData == 0
1035 && info->mSubSamples[0].mNumBytesOfEncryptedData == 0) {
1036 // no data so we only populate the bufferInfo
1037 result = 0;
1038 } else {
Arun Johnson82174a12024-02-27 04:53:59 +00001039 source.offset = srcOffset;
1040 source.size = bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +00001041 result = mCrypto->decrypt(
1042 (uint8_t*)info->mKey,
1043 (uint8_t*)info->mIv,
1044 info->mMode,
1045 info->mPattern,
1046 source,
Arun Johnson82174a12024-02-27 04:53:59 +00001047 buffer->offset(),
Arun Johnson564f3a92024-02-01 19:09:45 +00001048 info->mSubSamples,
1049 info->mNumSubSamples,
1050 destination,
1051 errorDetailMsg);
Arun Johnson82174a12024-02-27 04:53:59 +00001052 srcOffset += bufferInfos->value[i].mSize;
Arun Johnson564f3a92024-02-01 19:09:45 +00001053 if (result < 0) {
1054 ALOGI("[%s] decrypt failed: result=%zd", mName, result);
1055 return result;
1056 }
1057 if (destination.type == DrmBufferType::SHARED_MEMORY && mappedBlock) {
1058 mappedBlock->copyDecryptedContent(mDecryptDestination, result);
1059 }
1060 bufferInfos->value[i].mSize = result;
1061 outBufferSize += result;
1062 }
1063 }
1064 }
Arun Johnson82174a12024-02-27 04:53:59 +00001065 buffer->setRange(0, outBufferSize);
Arun Johnson564f3a92024-02-01 19:09:45 +00001066 }
1067 return queueInputBufferInternal(buffer, block, bufferSize);
1068}
1069
Pawin Vongmasa36653902018-11-15 00:10:25 -08001070void CCodecBufferChannel::feedInputBufferIfAvailable() {
1071 QueueGuard guard(mSync);
1072 if (!guard.isRunning()) {
1073 ALOGV("[%s] We're not running --- no input buffer reported", mName);
1074 return;
1075 }
1076 feedInputBufferIfAvailableInternal();
1077}
1078
1079void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Taehwan Kimda0517d2020-09-16 17:29:37 +09001080 if (mInputMetEos) {
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001081 return;
Pawin Vongmasac3c536d2020-06-12 04:00:04 -07001082 }
Wonsik Kimfca97a22024-08-30 20:20:42 +00001083 int64_t numOutputSlots = 0;
1084 bool outputFull = [this, &numOutputSlots]() {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001085 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimfca97a22024-08-30 20:20:42 +00001086 if (!output->buffers) {
1087 ALOGV("[%s] feedInputBufferIfAvailableInternal: "
1088 "return because output buffers are null", mName);
1089 return true;
1090 }
1091 numOutputSlots = int64_t(output->numSlots);
1092 if (output->buffers->hasPending() ||
Wonsik Kim3722abc2023-05-17 13:26:31 -07001093 (!output->bounded && output->buffers->numActiveSlots() >= output->numSlots)) {
Wonsik Kimfca97a22024-08-30 20:20:42 +00001094 ALOGV("[%s] feedInputBufferIfAvailableInternal: "
1095 "return because there are no room for more output buffers", mName);
1096 return true;
1097 }
1098 return false;
1099 }();
1100 if (android::media::codec::provider_->input_surface_throttle()) {
1101 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
1102 if (inputSurface->surface) {
1103 if (inputSurface->numProcessingBuffersBalance <= numOutputSlots) {
1104 ++inputSurface->numProcessingBuffersBalance;
1105 ALOGV("[%s] feedInputBufferIfAvailableInternal: numProcessingBuffersBalance = %lld",
1106 mName, static_cast<long long>(inputSurface->numProcessingBuffersBalance));
1107 inputSurface->surface->onInputBufferEmptied();
1108 }
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001109 }
1110 }
Wonsik Kimfca97a22024-08-30 20:20:42 +00001111 if (outputFull) {
1112 return;
Wonsik Kim1951d932024-05-23 22:59:00 +00001113 }
Wonsik Kim0487b782020-10-28 11:45:50 -07001114 size_t numActiveSlots = 0;
1115 while (!mPipelineWatcher.lock()->pipelineFull()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001116 sp<MediaCodecBuffer> inBuffer;
1117 size_t index;
1118 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001119 Mutexed<Input>::Locked input(mInput);
Wonsik Kim0487b782020-10-28 11:45:50 -07001120 numActiveSlots = input->buffers->numActiveSlots();
1121 if (numActiveSlots >= input->numSlots) {
1122 break;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001123 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001124 if (!input->buffers->requestNewBuffer(&index, &inBuffer)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001125 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001126 break;
1127 }
1128 }
1129 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
1130 mCallback->onInputBufferAvailable(index, inBuffer);
1131 }
Wonsik Kim0487b782020-10-28 11:45:50 -07001132 ALOGV("[%s] # active slots after feedInputBufferIfAvailable = %zu", mName, numActiveSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001133}
1134
1135status_t CCodecBufferChannel::renderOutputBuffer(
1136 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001137 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001138 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001139 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001140 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001141 Mutexed<Output>::Locked output(mOutput);
1142 if (output->buffers) {
1143 released = output->buffers->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001144 }
1145 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001146 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
1147 // set to true.
1148 sendOutputBuffers();
1149 // input buffer feeding may have been gated by pending output buffers
1150 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001151 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001152 if (released) {
Wonsik Kimf7529dd2019-04-18 17:35:53 -07001153 std::call_once(mRenderWarningFlag, [this] {
1154 ALOGW("[%s] The app is calling releaseOutputBuffer() with "
1155 "timestamp or render=true with non-video buffers. Apps should "
1156 "call releaseOutputBuffer() with render=false for those.",
1157 mName);
1158 });
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001159 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001160 return INVALID_OPERATION;
1161 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001162
1163#if 0
1164 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
1165 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
1166 for (const std::shared_ptr<const C2Info> &info : infoParams) {
1167 AString res;
1168 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
1169 if (ix) res.append(", ");
1170 res.append(*((int32_t*)info.get() + (ix / 4)));
1171 }
1172 ALOGV(" [%s]", res.c_str());
1173 }
1174#endif
1175 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
1176 std::static_pointer_cast<const C2StreamRotationInfo::output>(
1177 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
1178 bool flip = rotation && (rotation->flip & 1);
1179 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
Byeongjo Park25c3a3d2020-06-12 17:24:21 +09001180
1181 {
1182 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1183 if (output->surface == nullptr) {
1184 ALOGI("[%s] cannot render buffer without surface", mName);
1185 return OK;
1186 }
1187 int64_t frameIndex;
1188 buffer->meta()->findInt64("frameIndex", &frameIndex);
1189 if (output->rotation.count(frameIndex) != 0) {
1190 auto it = output->rotation.find(frameIndex);
1191 quarters = (it->second / 90) & 3;
1192 output->rotation.erase(it);
1193 }
1194 }
1195
Pawin Vongmasa36653902018-11-15 00:10:25 -08001196 uint32_t transform = 0;
1197 switch (quarters) {
1198 case 0: // no rotation
1199 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
1200 break;
1201 case 1: // 90 degrees counter-clockwise
1202 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
1203 : HAL_TRANSFORM_ROT_270;
1204 break;
1205 case 2: // 180 degrees
1206 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
1207 break;
1208 case 3: // 90 degrees clockwise
1209 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
1210 : HAL_TRANSFORM_ROT_90;
1211 break;
1212 }
1213
1214 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
1215 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
1216 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
1217 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
1218 if (surfaceScaling) {
1219 videoScalingMode = surfaceScaling->value;
1220 }
1221
1222 // Use dataspace from format as it has the default aspects already applied
1223 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
1224 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
1225
1226 // HDR static info
1227 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
1228 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
1229 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
1230
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001231 // HDR10 plus info
1232 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
1233 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
1234 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
Yichi Chen54be23c2020-06-15 14:30:53 +08001235 if (hdr10PlusInfo && hdr10PlusInfo->flexCount() == 0) {
1236 hdr10PlusInfo.reset();
1237 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001238
Wonsik Kima79c5522022-01-18 16:29:24 -08001239 // HDR dynamic info
1240 std::shared_ptr<const C2StreamHdrDynamicMetadataInfo::output> hdrDynamicInfo =
1241 std::static_pointer_cast<const C2StreamHdrDynamicMetadataInfo::output>(
1242 c2Buffer->getInfo(C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE));
1243 // TODO: make this sticky & enable unset
1244 if (hdrDynamicInfo && hdrDynamicInfo->flexCount() == 0) {
1245 hdrDynamicInfo.reset();
1246 }
1247
1248 if (hdr10PlusInfo) {
1249 // C2StreamHdr10PlusInfo is deprecated; components should use
1250 // C2StreamHdrDynamicMetadataInfo
1251 // TODO: #metric
1252 if (hdrDynamicInfo) {
1253 // It is unexpected that C2StreamHdr10PlusInfo and
1254 // C2StreamHdrDynamicMetadataInfo is both present.
1255 // C2StreamHdrDynamicMetadataInfo takes priority.
1256 // TODO: #metric
1257 } else {
1258 std::shared_ptr<C2StreamHdrDynamicMetadataInfo::output> info =
1259 C2StreamHdrDynamicMetadataInfo::output::AllocShared(
1260 hdr10PlusInfo->flexCount(),
1261 0u,
1262 C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40);
1263 memcpy(info->m.data, hdr10PlusInfo->m.value, hdr10PlusInfo->flexCount());
1264 hdrDynamicInfo = info;
1265 }
1266 }
1267
Pawin Vongmasa36653902018-11-15 00:10:25 -08001268 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
1269 if (blocks.size() != 1u) {
1270 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
1271 return UNKNOWN_ERROR;
1272 }
1273 const C2ConstGraphicBlock &block = blocks.front();
Lubin Yin92427a52022-04-18 16:57:39 -07001274 C2Fence c2fence = block.fence();
1275 sp<Fence> fence = Fence::NO_FENCE;
1276 // TODO: it's not sufficient to just check isHW() and then construct android::fence from it.
1277 // Once C2Fence::type() is added, check the exact C2Fence type
1278 if (c2fence.isHW()) {
1279 int fenceFd = c2fence.fd();
1280 fence = sp<Fence>::make(fenceFd);
1281 if (!fence) {
1282 ALOGE("[%s] Failed to allocate a fence", mName);
1283 close(fenceFd);
1284 return NO_MEMORY;
1285 }
1286 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001287
1288 // TODO: revisit this after C2Fence implementation.
Brian Lindahl932bf602023-03-09 11:59:48 -07001289 IGraphicBufferProducer::QueueBufferInput qbi(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001290 timestampNs,
1291 false, // droppable
1292 dataSpace,
1293 Rect(blocks.front().crop().left,
1294 blocks.front().crop().top,
1295 blocks.front().crop().right(),
1296 blocks.front().crop().bottom()),
1297 videoScalingMode,
1298 transform,
Lubin Yin92427a52022-04-18 16:57:39 -07001299 fence, 0);
Wonsik Kima79c5522022-01-18 16:29:24 -08001300 if (hdrStaticInfo || hdrDynamicInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001301 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001302 if (hdrStaticInfo) {
wenchangliuf3f92882020-05-14 00:02:01 +08001303 // If mastering max and min luminance fields are 0, do not use them.
1304 // It indicates the value may not be present in the stream.
1305 if (hdrStaticInfo->mastering.maxLuminance > 0.0f &&
1306 hdrStaticInfo->mastering.minLuminance > 0.0f) {
1307 struct android_smpte2086_metadata smpte2086_meta = {
1308 .displayPrimaryRed = {
1309 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
1310 },
1311 .displayPrimaryGreen = {
1312 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
1313 },
1314 .displayPrimaryBlue = {
1315 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
1316 },
1317 .whitePoint = {
1318 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
1319 },
1320 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
1321 .minLuminance = hdrStaticInfo->mastering.minLuminance,
1322 };
Yichi Chen54be23c2020-06-15 14:30:53 +08001323 hdr.validTypes |= HdrMetadata::SMPTE2086;
wenchangliuf3f92882020-05-14 00:02:01 +08001324 hdr.smpte2086 = smpte2086_meta;
1325 }
Chong Zhang3bb2a7f2020-04-21 10:35:12 -07001326 // If the content light level fields are 0, do not use them, it
1327 // indicates the value may not be present in the stream.
1328 if (hdrStaticInfo->maxCll > 0.0f && hdrStaticInfo->maxFall > 0.0f) {
1329 struct android_cta861_3_metadata cta861_meta = {
1330 .maxContentLightLevel = hdrStaticInfo->maxCll,
1331 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
1332 };
1333 hdr.validTypes |= HdrMetadata::CTA861_3;
1334 hdr.cta8613 = cta861_meta;
1335 }
Taehwan Kim6b85f1e2022-04-07 17:41:44 +09001336
1337 // does not have valid info
1338 if (!(hdr.validTypes & (HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3))) {
1339 hdrStaticInfo.reset();
1340 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001341 }
Wonsik Kima79c5522022-01-18 16:29:24 -08001342 if (hdrDynamicInfo
1343 && hdrDynamicInfo->m.type_ == C2Config::HDR_DYNAMIC_METADATA_TYPE_SMPTE_2094_40) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001344 hdr.validTypes |= HdrMetadata::HDR10PLUS;
1345 hdr.hdr10plus.assign(
Wonsik Kima79c5522022-01-18 16:29:24 -08001346 hdrDynamicInfo->m.data,
1347 hdrDynamicInfo->m.data + hdrDynamicInfo->flexCount());
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001348 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001349 qbi.setHdrMetadata(hdr);
1350 }
Hongguangfc1478a2022-07-20 22:56:06 -07001351 SetMetadataToGralloc4Handle(dataSpace, hdrStaticInfo, hdrDynamicInfo, block.handle());
1352
Brian Lindahl932bf602023-03-09 11:59:48 -07001353 qbi.setSurfaceDamage(Region::INVALID_REGION); // we don't have dirty regions
1354 qbi.getFrameTimestamps = true; // we need to know when a frame is rendered
1355 IGraphicBufferProducer::QueueBufferOutput qbo;
Sungtak Lee368452b2024-10-17 01:16:29 +00001356 status_t result = std::atomic_load(&mComponent)->queueToOutputSurface(block, qbi, &qbo);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001357 if (result != OK) {
1358 ALOGI("[%s] queueBuffer failed: %d", mName, result);
Sungtak Lee47c018a2020-11-07 01:02:49 -08001359 if (result == NO_INIT) {
1360 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1361 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001362 return result;
1363 }
Josh Hou8eddf4b2021-02-02 16:26:53 +08001364
1365 if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
1366 ALOGD("[%s] queue buffer successful", mName);
1367 } else {
1368 ALOGV("[%s] queue buffer successful", mName);
1369 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001370
1371 int64_t mediaTimeUs = 0;
1372 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
Brian Lindahld7967a92023-08-10 10:12:49 -06001373 if (mAreRenderMetricsEnabled && mIsSurfaceToDisplay) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001374 trackReleasedFrame(qbo, mediaTimeUs, timestampNs);
1375 processRenderedFrames(qbo.frameTimestamps);
1376 } else {
1377 // When the surface is an intermediate surface, onFrameRendered is triggered immediately
1378 // when the frame is queued to the non-display surface
1379 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1380 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001381
1382 return OK;
1383}
1384
Brian Lindahl932bf602023-03-09 11:59:48 -07001385void CCodecBufferChannel::initializeFrameTrackingFor(ANativeWindow * window) {
Brian Lindahl2048d492023-04-05 08:49:23 -06001386 mTrackedFrames.clear();
1387
1388 int isSurfaceToDisplay = 0;
1389 window->query(window, NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, &isSurfaceToDisplay);
1390 mIsSurfaceToDisplay = isSurfaceToDisplay == 1;
1391 // No frame tracking is needed if we're not sending frames to the display
1392 if (!mIsSurfaceToDisplay) {
1393 // Return early so we don't call into SurfaceFlinger (requiring permissions)
1394 return;
1395 }
1396
Brian Lindahl932bf602023-03-09 11:59:48 -07001397 int hasPresentFenceTimes = 0;
1398 window->query(window, NATIVE_WINDOW_FRAME_TIMESTAMPS_SUPPORTS_PRESENT, &hasPresentFenceTimes);
1399 mHasPresentFenceTimes = hasPresentFenceTimes == 1;
Brian Lindahl119e0c22023-05-19 15:42:13 -06001400 if (!mHasPresentFenceTimes) {
Brian Lindahl932bf602023-03-09 11:59:48 -07001401 ALOGI("Using latch times for frame rendered signals - present fences not supported");
1402 }
Brian Lindahl932bf602023-03-09 11:59:48 -07001403}
1404
1405void CCodecBufferChannel::trackReleasedFrame(const IGraphicBufferProducer::QueueBufferOutput& qbo,
1406 int64_t mediaTimeUs, int64_t desiredRenderTimeNs) {
1407 // If the render time is earlier than now, then we're suggesting it should be rendered ASAP,
1408 // so track the frame as if the desired render time is now.
1409 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1410 if (desiredRenderTimeNs < nowNs) {
1411 desiredRenderTimeNs = nowNs;
1412 }
Brian Lindahlc8bd9272023-08-28 09:42:43 -06001413
1414 // If the render time is more than a second from now, then pretend the frame is supposed to be
1415 // rendered immediately, because that's what SurfaceFlinger heuristics will do. This is a tight
1416 // coupling, but is really the only way to optimize away unnecessary present fence checks in
1417 // processRenderedFrames.
1418 if (desiredRenderTimeNs > nowNs + 1*1000*1000*1000LL) {
1419 desiredRenderTimeNs = nowNs;
1420 }
1421
Brian Lindahl932bf602023-03-09 11:59:48 -07001422 // We've just queued a frame to the surface, so keep track of it and later check to see if it is
1423 // actually rendered.
1424 TrackedFrame frame;
1425 frame.number = qbo.nextFrameNumber - 1;
1426 frame.mediaTimeUs = mediaTimeUs;
1427 frame.desiredRenderTimeNs = desiredRenderTimeNs;
1428 frame.latchTime = -1;
1429 frame.presentFence = nullptr;
1430 mTrackedFrames.push_back(frame);
1431}
1432
1433void CCodecBufferChannel::processRenderedFrames(const FrameEventHistoryDelta& deltas) {
1434 // Grab the latch times and present fences from the frame event deltas
1435 for (const auto& delta : deltas) {
1436 for (auto& frame : mTrackedFrames) {
1437 if (delta.getFrameNumber() == frame.number) {
1438 delta.getLatchTime(&frame.latchTime);
1439 delta.getDisplayPresentFence(&frame.presentFence);
1440 }
1441 }
1442 }
1443
1444 // Scan all frames and check to see if the frames that SHOULD have been rendered by now, have,
1445 // in fact, been rendered.
1446 int64_t nowNs = systemTime(SYSTEM_TIME_MONOTONIC);
1447 while (!mTrackedFrames.empty()) {
1448 TrackedFrame & frame = mTrackedFrames.front();
1449 // Frames that should have been rendered at least 100ms in the past are checked
1450 if (frame.desiredRenderTimeNs > nowNs - 100*1000*1000LL) {
1451 break;
1452 }
1453
1454 // If we don't have a render time by now, then consider the frame as dropped
1455 int64_t renderTimeNs = getRenderTimeNs(frame);
1456 if (renderTimeNs != -1) {
1457 mCCodecCallback->onOutputFramesRendered(frame.mediaTimeUs, renderTimeNs);
1458 }
1459 mTrackedFrames.pop_front();
1460 }
1461}
1462
1463int64_t CCodecBufferChannel::getRenderTimeNs(const TrackedFrame& frame) {
1464 // If the device doesn't have accurate present fence times, then use the latch time as a proxy
1465 if (!mHasPresentFenceTimes) {
1466 if (frame.latchTime == -1) {
1467 ALOGD("no latch time for frame %d", (int) frame.number);
1468 return -1;
1469 }
1470 return frame.latchTime;
1471 }
1472
1473 if (frame.presentFence == nullptr) {
1474 ALOGW("no present fence for frame %d", (int) frame.number);
1475 return -1;
1476 }
1477
1478 nsecs_t actualRenderTimeNs = frame.presentFence->getSignalTime();
1479
1480 if (actualRenderTimeNs == Fence::SIGNAL_TIME_INVALID) {
1481 ALOGW("invalid signal time for frame %d", (int) frame.number);
1482 return -1;
1483 }
1484
1485 if (actualRenderTimeNs == Fence::SIGNAL_TIME_PENDING) {
1486 ALOGD("present fence has not fired for frame %d", (int) frame.number);
1487 return -1;
1488 }
1489
1490 return actualRenderTimeNs;
1491}
1492
1493void CCodecBufferChannel::pollForRenderedBuffers() {
1494 FrameEventHistoryDelta delta;
Sungtak Lee368452b2024-10-17 01:16:29 +00001495 std::atomic_load(&mComponent)->pollForRenderedFrames(&delta);
Brian Lindahl932bf602023-03-09 11:59:48 -07001496 processRenderedFrames(delta);
1497}
1498
Sungtak Lee214ce612023-11-01 10:01:13 +00001499void CCodecBufferChannel::onBufferReleasedFromOutputSurface(uint32_t generation) {
Sungtak Lee6700cc92023-11-22 18:04:05 +00001500 // Note: Since this is called asynchronously from IProducerListener not
1501 // knowing the internal state of CCodec/CCodecBufferChannel,
1502 // prevent mComponent from being destroyed by holding the shared reference
1503 // during this interface being executed.
Sungtak Lee368452b2024-10-17 01:16:29 +00001504 std::shared_ptr<Codec2Client::Component> comp = std::atomic_load(&mComponent);
Sungtak Lee6700cc92023-11-22 18:04:05 +00001505 if (comp) {
1506 comp->onBufferReleasedFromOutputSurface(generation);
1507 }
Sungtak Lee214ce612023-11-01 10:01:13 +00001508}
1509
Sungtak Lee1720e4c2024-07-31 21:15:26 +00001510void CCodecBufferChannel::onBufferAttachedToOutputSurface(uint32_t generation) {
1511 // Note: Since this is called asynchronously from IProducerListener not
1512 // knowing the internal state of CCodec/CCodecBufferChannel,
1513 // prevent mComponent from being destroyed by holding the shared reference
1514 // during this interface being executed.
Sungtak Lee368452b2024-10-17 01:16:29 +00001515 std::shared_ptr<Codec2Client::Component> comp = std::atomic_load(&mComponent);
Sungtak Lee1720e4c2024-07-31 21:15:26 +00001516 if (comp) {
1517 comp->onBufferAttachedToOutputSurface(generation);
1518 }
1519}
1520
Pawin Vongmasa36653902018-11-15 00:10:25 -08001521status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1522 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1523 bool released = false;
1524 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001525 Mutexed<Input>::Locked input(mInput);
1526 if (input->buffers && input->buffers->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001527 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001528 }
1529 }
1530 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001531 Mutexed<Output>::Locked output(mOutput);
1532 if (output->buffers && output->buffers->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001533 released = true;
1534 }
1535 }
1536 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001537 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001538 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001539 } else {
1540 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
1541 }
1542 return OK;
1543}
1544
1545void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1546 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001547 Mutexed<Input>::Locked input(mInput);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001548
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001549 if (!input->buffers) {
1550 ALOGE("getInputBufferArray: No Input Buffers allocated");
1551 return;
1552 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001553 if (!input->buffers->isArrayMode()) {
1554 input->buffers = input->buffers->toArrayMode(input->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001555 }
1556
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001557 input->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001558}
1559
1560void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
1561 array->clear();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001562 Mutexed<Output>::Locked output(mOutput);
Arun Johnson3ab32cd2022-06-10 18:58:01 +00001563 if (!output->buffers) {
1564 ALOGE("getOutputBufferArray: No Output Buffers allocated");
1565 return;
1566 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001567 if (!output->buffers->isArrayMode()) {
1568 output->buffers = output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001569 }
1570
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001571 output->buffers->getArray(array);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001572}
1573
1574status_t CCodecBufferChannel::start(
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001575 const sp<AMessage> &inputFormat,
1576 const sp<AMessage> &outputFormat,
1577 bool buffersBoundToCodec) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001578 C2StreamBufferTypeSetting::input iStreamFormat(0u);
1579 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001580 C2ComponentKindSetting kind;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001581 C2PortReorderBufferDepthTuning::output reorderDepth;
1582 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001583 C2PortActualDelayTuning::input inputDelay(0);
1584 C2PortActualDelayTuning::output outputDelay(0);
1585 C2ActualPipelineDelayTuning pipelineDelay(0);
Sungtak Lee04b30352020-07-27 13:57:25 -07001586 C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
Wonsik Kim078b58e2019-01-09 15:08:06 -08001587
Sungtak Lee368452b2024-10-17 01:16:29 +00001588 c2_status_t err = std::atomic_load(&mComponent)->query(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001589 {
1590 &iStreamFormat,
1591 &oStreamFormat,
Wonsik Kime1104ca2020-11-24 15:01:33 -08001592 &kind,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001593 &reorderDepth,
1594 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08001595 &inputDelay,
1596 &pipelineDelay,
1597 &outputDelay,
Sungtak Lee04b30352020-07-27 13:57:25 -07001598 &secureMode,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001599 },
1600 {},
1601 C2_DONT_BLOCK,
1602 nullptr);
1603 if (err == C2_BAD_INDEX) {
Wonsik Kime1104ca2020-11-24 15:01:33 -08001604 if (!iStreamFormat || !oStreamFormat || !kind) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001605 return UNKNOWN_ERROR;
1606 }
1607 } else if (err != C2_OK) {
1608 return UNKNOWN_ERROR;
1609 }
1610
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001611 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
1612 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
1613 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
1614
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001615 size_t numInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
1616 size_t numOutputSlots = outputDelayValue + kSmoothnessFactor;
Wonsik Kim078b58e2019-01-09 15:08:06 -08001617
Pawin Vongmasa36653902018-11-15 00:10:25 -08001618 // TODO: get this from input format
Sungtak Lee368452b2024-10-17 01:16:29 +00001619 bool secure = std::atomic_load(&mComponent)->getName().find(".secure") != std::string::npos;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001620
Sungtak Lee04b30352020-07-27 13:57:25 -07001621 // secure mode is a static parameter (shall not change in the executing state)
1622 mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
1623
Pawin Vongmasa36653902018-11-15 00:10:25 -08001624 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001625 int poolMask = GetCodec2PoolMask();
1626 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001627
1628 if (inputFormat != nullptr) {
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001629 bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001630 bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001631 C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
1632 API_REFLECTION |
1633 API_VALUES |
1634 API_CURRENT_VALUES |
1635 API_DEPENDENCY |
1636 API_SAME_INPUT_BUFFER);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001637 C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
1638 C2StreamSampleRateInfo::input sampleRate(0u);
1639 C2StreamChannelCountInfo::input channelCount(0u);
1640 C2StreamPcmEncodingInfo::input pcmEncoding(0u);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001641 std::shared_ptr<C2BlockPool> pool;
1642 {
1643 Mutexed<BlockPools>::Locked pools(mBlockPools);
1644
1645 // set default allocator ID.
1646 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001647 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001648
1649 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
1650 // from component, create the input block pool with given ID. Otherwise, use default IDs.
1651 std::vector<std::unique_ptr<C2Param>> params;
Wonsik Kimffb889a2020-05-28 11:32:25 -07001652 C2ApiFeaturesSetting featuresSetting{apiFeatures};
Wonsik Kime1104ca2020-11-24 15:01:33 -08001653 std::vector<C2Param *> stackParams({&featuresSetting});
1654 if (audioEncoder) {
1655 stackParams.push_back(&encoderFrameSize);
1656 stackParams.push_back(&sampleRate);
1657 stackParams.push_back(&channelCount);
1658 stackParams.push_back(&pcmEncoding);
1659 } else {
1660 encoderFrameSize.invalidate();
1661 sampleRate.invalidate();
1662 channelCount.invalidate();
1663 pcmEncoding.invalidate();
1664 }
Sungtak Lee368452b2024-10-17 01:16:29 +00001665 err = std::atomic_load(&mComponent)->query(stackParams,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001666 { C2PortAllocatorsTuning::input::PARAM_TYPE },
1667 C2_DONT_BLOCK,
1668 &params);
1669 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1670 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
1671 mName, params.size(), asString(err), err);
Wonsik Kimffb889a2020-05-28 11:32:25 -07001672 } else if (params.size() == 1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001673 C2PortAllocatorsTuning::input *inputAllocators =
1674 C2PortAllocatorsTuning::input::From(params[0].get());
1675 if (inputAllocators && inputAllocators->flexCount() > 0) {
1676 std::shared_ptr<C2Allocator> allocator;
1677 // verify allocator IDs and resolve default allocator
1678 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
1679 if (allocator) {
1680 pools->inputAllocatorId = allocator->getId();
1681 } else {
1682 ALOGD("[%s] component requested invalid input allocator ID %u",
1683 mName, inputAllocators->m.values[0]);
1684 }
1685 }
1686 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001687 if (featuresSetting) {
1688 apiFeatures = featuresSetting.value;
1689 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001690
1691 // TODO: use C2Component wrapper to associate this pool with ourselves
1692 if ((poolMask >> pools->inputAllocatorId) & 1) {
1693 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
1694 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
1695 mName, pools->inputAllocatorId,
1696 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1697 asString(err), err);
1698 } else {
1699 err = C2_NOT_FOUND;
1700 }
1701 if (err != C2_OK) {
1702 C2BlockPool::local_id_t inputPoolId =
1703 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1704 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
1705 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
1706 mName, (unsigned long long)inputPoolId,
1707 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
1708 asString(err), err);
1709 if (err != C2_OK) {
1710 return NO_MEMORY;
1711 }
1712 }
1713 pools->inputPool = pool;
1714 }
1715
Wonsik Kim51051262018-11-28 13:59:05 -08001716 bool forceArrayMode = false;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001717 Mutexed<Input>::Locked input(mInput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001718 input->inputDelay = inputDelayValue;
1719 input->pipelineDelay = pipelineDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001720 input->numSlots = numInputSlots;
1721 input->extraBuffers.flush();
1722 input->numExtraSlots = 0u;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07001723 input->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kime1104ca2020-11-24 15:01:33 -08001724 if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
1725 input->frameReassembler.init(
1726 pool,
1727 {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
1728 encoderFrameSize.value,
1729 sampleRate.value,
1730 channelCount.value,
1731 pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
1732 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07001733 bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
1734 // For encrypted content, framework decrypts source buffer (ashmem) into
1735 // C2Buffers. Thus non-conforming codecs can process these.
Wonsik Kime1104ca2020-11-24 15:01:33 -08001736 if (!buffersBoundToCodec
1737 && !input->frameReassembler
1738 && (hasCryptoOrDescrambler() || conforming)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001739 input->buffers.reset(new SlotInputBuffers(mName));
1740 } else if (graphic) {
Wonsik Kimfca97a22024-08-30 20:20:42 +00001741 if (mHasInputSurface) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001742 input->buffers.reset(new DummyInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001743 } else if (mMetaMode == MODE_ANW) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001744 input->buffers.reset(new GraphicMetadataInputBuffers(mName));
Wonsik Kim1221fd12019-07-12 12:52:05 -07001745 // This is to ensure buffers do not get released prematurely.
1746 // TODO: handle this without going into array mode
1747 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001748 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001749 input->buffers.reset(new GraphicInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001750 }
1751 } else {
1752 if (hasCryptoOrDescrambler()) {
1753 int32_t capacity = kLinearBufferSize;
1754 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
1755 if ((size_t)capacity > kMaxLinearBufferSize) {
1756 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
1757 capacity = kMaxLinearBufferSize;
1758 }
1759 if (mDealer == nullptr) {
1760 mDealer = new MemoryDealer(
1761 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001762 * (numInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001763 "EncryptedLinearInputBuffers");
1764 mDecryptDestination = mDealer->allocate((size_t)capacity);
1765 }
1766 if (mCrypto != nullptr && mHeapSeqNum < 0) {
Robert Shih895fba92019-07-16 16:29:44 -07001767 sp<HidlMemory> heap = fromHeap(mDealer->getMemoryHeap());
1768 mHeapSeqNum = mCrypto->setHeap(heap);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001769 } else {
1770 mHeapSeqNum = -1;
1771 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001772 input->buffers.reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001773 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001774 numInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08001775 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001776 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001777 input->buffers.reset(new LinearInputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001778 }
1779 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001780 input->buffers->setFormat(inputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001781
1782 if (err == C2_OK) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001783 input->buffers->setPool(pool);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001784 } else {
1785 // TODO: error
1786 }
Wonsik Kim51051262018-11-28 13:59:05 -08001787
1788 if (forceArrayMode) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001789 input->buffers = input->buffers->toArrayMode(numInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08001790 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001791 }
1792
1793 if (outputFormat != nullptr) {
1794 sp<IGraphicBufferProducer> outputSurface;
1795 uint32_t outputGeneration;
Sungtak Leea714f112021-03-16 05:40:03 -07001796 int maxDequeueCount = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001797 {
1798 Mutexed<OutputSurface>::Locked output(mOutputSurface);
Sungtak Leea714f112021-03-16 05:40:03 -07001799 maxDequeueCount = output->maxDequeueBuffers = numOutputSlots +
Wonsik Kim3a692e62023-05-19 15:37:22 -07001800 reorderDepth.value + mRenderingDepth;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001801 outputSurface = output->surface ?
1802 output->surface->getIGraphicBufferProducer() : nullptr;
Wonsik Kimf5e5c832019-02-21 11:36:05 -08001803 if (outputSurface) {
1804 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
1805 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001806 outputGeneration = output->generation;
1807 }
1808
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08001809 bool graphic = (oStreamFormat.value == C2BufferData::GRAPHIC);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001810 C2BlockPool::local_id_t outputPoolId_;
David Stevensc3fbb282021-01-18 18:11:20 +09001811 C2BlockPool::local_id_t prevOutputPoolId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001812
1813 {
1814 Mutexed<BlockPools>::Locked pools(mBlockPools);
1815
David Stevensc3fbb282021-01-18 18:11:20 +09001816 prevOutputPoolId = pools->outputPoolId;
1817
Pawin Vongmasa36653902018-11-15 00:10:25 -08001818 // set default allocator ID.
1819 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
Pin-chih Linaa18ea52019-11-19 18:48:50 +08001820 : preferredLinearId;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001821
1822 // query C2PortAllocatorsTuning::output from component, or use default allocator if
1823 // unsuccessful.
1824 std::vector<std::unique_ptr<C2Param>> params;
Sungtak Lee368452b2024-10-17 01:16:29 +00001825 err = std::atomic_load(&mComponent)->query({ },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001826 { C2PortAllocatorsTuning::output::PARAM_TYPE },
1827 C2_DONT_BLOCK,
1828 &params);
1829 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1830 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
1831 mName, params.size(), asString(err), err);
1832 } else if (err == C2_OK && params.size() == 1) {
1833 C2PortAllocatorsTuning::output *outputAllocators =
1834 C2PortAllocatorsTuning::output::From(params[0].get());
1835 if (outputAllocators && outputAllocators->flexCount() > 0) {
1836 std::shared_ptr<C2Allocator> allocator;
1837 // verify allocator IDs and resolve default allocator
1838 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
1839 if (allocator) {
1840 pools->outputAllocatorId = allocator->getId();
1841 } else {
1842 ALOGD("[%s] component requested invalid output allocator ID %u",
1843 mName, outputAllocators->m.values[0]);
1844 }
1845 }
1846 }
1847
1848 // use bufferqueue if outputting to a surface.
1849 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
1850 // if unsuccessful.
1851 if (outputSurface) {
1852 params.clear();
Sungtak Lee368452b2024-10-17 01:16:29 +00001853 err = std::atomic_load(&mComponent)->query({ },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001854 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
1855 C2_DONT_BLOCK,
1856 &params);
1857 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
1858 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
1859 mName, params.size(), asString(err), err);
1860 } else if (err == C2_OK && params.size() == 1) {
1861 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
1862 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
1863 if (surfaceAllocator) {
1864 std::shared_ptr<C2Allocator> allocator;
1865 // verify allocator IDs and resolve default allocator
1866 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
1867 if (allocator) {
1868 pools->outputAllocatorId = allocator->getId();
1869 } else {
1870 ALOGD("[%s] component requested invalid surface output allocator ID %u",
1871 mName, surfaceAllocator->value);
1872 err = C2_BAD_VALUE;
1873 }
1874 }
1875 }
1876 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
1877 && err != C2_OK
1878 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
1879 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
1880 }
1881 }
1882
1883 if ((poolMask >> pools->outputAllocatorId) & 1) {
Sungtak Lee368452b2024-10-17 01:16:29 +00001884 err = std::atomic_load(&mComponent)->createBlockPool(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001885 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
1886 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
1887 mName, pools->outputAllocatorId,
1888 (unsigned long long)pools->outputPoolId,
1889 asString(err));
1890 } else {
1891 err = C2_NOT_FOUND;
1892 }
1893 if (err != C2_OK) {
1894 // use basic pool instead
1895 pools->outputPoolId =
1896 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
1897 }
1898
1899 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
1900 // component.
1901 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
1902 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
1903
1904 std::vector<std::unique_ptr<C2SettingResult>> failures;
Sungtak Lee368452b2024-10-17 01:16:29 +00001905 err = std::atomic_load(&mComponent)->config(
1906 { poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001907 ALOGD("[%s] Configured output block pool ids %llu => %s",
1908 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
1909 outputPoolId_ = pools->outputPoolId;
1910 }
1911
David Stevensc3fbb282021-01-18 18:11:20 +09001912 if (prevOutputPoolId != C2BlockPool::BASIC_LINEAR
1913 && prevOutputPoolId != C2BlockPool::BASIC_GRAPHIC) {
Sungtak Lee368452b2024-10-17 01:16:29 +00001914 c2_status_t err = std::atomic_load(&mComponent)->destroyBlockPool(prevOutputPoolId);
David Stevensc3fbb282021-01-18 18:11:20 +09001915 if (err != C2_OK) {
1916 ALOGW("Failed to clean up previous block pool %llu - %s (%d)\n",
1917 (unsigned long long) prevOutputPoolId, asString(err), err);
1918 }
1919 }
1920
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001921 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimbdffead2019-07-01 12:00:07 -07001922 output->outputDelay = outputDelayValue;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001923 output->numSlots = numOutputSlots;
Wonsik Kim3722abc2023-05-17 13:26:31 -07001924 output->bounded = bool(outputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001925 if (graphic) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001926 if (outputSurface || !buffersBoundToCodec) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001927 output->buffers.reset(new GraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001928 } else {
Wonsik Kim41d83432020-04-27 16:40:49 -07001929 output->buffers.reset(new RawGraphicOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001930 }
1931 } else {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001932 output->buffers.reset(new LinearOutputBuffers(mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001933 }
Wonsik Kime4716c02020-02-28 10:42:21 -08001934 output->buffers->setFormat(outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001935
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001936 output->buffers->clearStash();
1937 if (reorderDepth) {
1938 output->buffers->setReorderDepth(reorderDepth.value);
1939 }
1940 if (reorderKey) {
1941 output->buffers->setReorderKey(reorderKey.value);
1942 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001943
1944 // Try to set output surface to created block pool if given.
1945 if (outputSurface) {
Sungtak Lee368452b2024-10-17 01:16:29 +00001946 std::atomic_load(&mComponent)->setOutputSurface(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001947 outputPoolId_,
1948 outputSurface,
Sungtak Leedb14cba2021-04-10 00:50:23 -07001949 outputGeneration,
1950 maxDequeueCount);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001951 } else {
1952 // configure CPU read consumer usage
1953 C2StreamUsageTuning::output outputUsage{0u, C2MemoryUsage::CPU_READ};
1954 std::vector<std::unique_ptr<C2SettingResult>> failures;
Sungtak Lee368452b2024-10-17 01:16:29 +00001955 err = std::atomic_load(&mComponent)->config({ &outputUsage }, C2_MAY_BLOCK, &failures);
Lajos Molnar78aa7c92021-02-18 21:39:01 -08001956 // do not print error message for now as most components may not yet
1957 // support this setting
1958 ALOGD_IF(err != C2_BAD_INDEX, "[%s] Configured output usage [%#llx]",
1959 mName, (long long)outputUsage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001960 }
1961
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07001962 if (oStreamFormat.value == C2BufferData::LINEAR) {
Wonsik Kim58713302020-01-29 22:25:23 -08001963 if (buffersBoundToCodec) {
1964 // WORKAROUND: if we're using early CSD workaround we convert to
1965 // array mode, to appease apps assuming the output
1966 // buffers to be of the same size.
1967 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1968 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001969
1970 int32_t channelCount;
1971 int32_t sampleRate;
1972 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
1973 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
1974 int32_t delay = 0;
1975 int32_t padding = 0;;
1976 if (!outputFormat->findInt32("encoder-delay", &delay)) {
1977 delay = 0;
1978 }
1979 if (!outputFormat->findInt32("encoder-padding", &padding)) {
1980 padding = 0;
1981 }
1982 if (delay || padding) {
Arun Johnson52d323e2024-01-05 21:16:56 +00001983 // We need write access to the buffers, so turn them into array mode.
1984 // TODO: b/321930152 - define SkipCutOutputBuffers that takes output from
1985 // component, runs it through SkipCutBuffer and allocate local buffer to be
1986 // used by fwk. Make initSkipCutBuffer() return OutputBuffers similar to
1987 // toArrayMode().
1988 if (!output->buffers->isArrayMode()) {
1989 output->buffers = output->buffers->toArrayMode(numOutputSlots);
1990 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001991 output->buffers->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001992 }
1993 }
1994 }
Wonsik Kimec585c32021-10-01 01:11:00 -07001995
1996 int32_t tunneled = 0;
1997 if (!outputFormat->findInt32("android._tunneled", &tunneled)) {
1998 tunneled = 0;
1999 }
2000 mTunneled = (tunneled != 0);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002001 }
2002
2003 // Set up pipeline control. This has to be done after mInputBuffers and
2004 // mOutputBuffers are initialized to make sure that lingering callbacks
2005 // about buffers from the previous generation do not interfere with the
2006 // newly initialized pipeline capacity.
2007
Wonsik Kim62545252021-01-20 11:25:41 -08002008 if (inputFormat || outputFormat) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002009 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002010 watcher->inputDelay(inputDelayValue)
2011 .pipelineDelay(pipelineDelayValue)
2012 .outputDelay(outputDelayValue)
Houxiang Dai0b573282023-03-11 18:31:56 +08002013 .smoothnessFactor(kSmoothnessFactor)
2014 .tunneled(mTunneled);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002015 watcher->flush();
2016 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002017
2018 mInputMetEos = false;
2019 mSync.start();
2020 return OK;
2021}
2022
Wonsik Kim34b28b42022-05-20 15:49:32 -07002023status_t CCodecBufferChannel::prepareInitialInputBuffers(
Arun Johnson326166e2023-07-28 19:11:52 +00002024 std::map<size_t, sp<MediaCodecBuffer>> *clientInputBuffers, bool retry) {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002025 if (mHasInputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002026 return OK;
2027 }
2028
Wonsik Kim34b28b42022-05-20 15:49:32 -07002029 size_t numInputSlots = mInput.lock()->numSlots;
Arun Johnson326166e2023-07-28 19:11:52 +00002030 int retryCount = 1;
2031 for (; clientInputBuffers->empty() && retryCount >= 0; retryCount--) {
2032 {
2033 Mutexed<Input>::Locked input(mInput);
2034 while (clientInputBuffers->size() < numInputSlots) {
2035 size_t index;
2036 sp<MediaCodecBuffer> buffer;
2037 if (!input->buffers->requestNewBuffer(&index, &buffer)) {
2038 break;
2039 }
2040 clientInputBuffers->emplace(index, buffer);
Wonsik Kim34b28b42022-05-20 15:49:32 -07002041 }
Arun Johnson326166e2023-07-28 19:11:52 +00002042 }
2043 if (!retry || (retryCount <= 0)) {
2044 break;
2045 }
2046 if (clientInputBuffers->empty()) {
2047 // wait: buffer may be in transit from component.
2048 std::this_thread::sleep_for(std::chrono::milliseconds(4));
Wonsik Kim34b28b42022-05-20 15:49:32 -07002049 }
2050 }
2051 if (clientInputBuffers->empty()) {
2052 ALOGW("[%s] start: cannot allocate memory at all", mName);
2053 return NO_MEMORY;
2054 } else if (clientInputBuffers->size() < numInputSlots) {
2055 ALOGD("[%s] start: cannot allocate memory for all slots, "
2056 "only %zu buffers allocated",
2057 mName, clientInputBuffers->size());
2058 } else {
2059 ALOGV("[%s] %zu initial input buffers available",
2060 mName, clientInputBuffers->size());
2061 }
2062 return OK;
2063}
2064
2065status_t CCodecBufferChannel::requestInitialInputBuffers(
2066 std::map<size_t, sp<MediaCodecBuffer>> &&clientInputBuffers) {
Wonsik Kim8f67e732024-10-19 04:13:05 +00002067 std::optional<QueueGuard> guard;
2068 if (android::media::codec::provider_->codec_buffer_state_cleanup()) {
2069 guard.emplace(mSync);
2070 if (!guard->isRunning()) {
2071 ALOGD("[%s] skip requestInitialInputBuffers when not running", mName);
2072 return OK;
2073 }
2074 }
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002075 C2StreamBufferTypeSetting::output oStreamFormat(0u);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07002076 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Sungtak Lee368452b2024-10-17 01:16:29 +00002077 c2_status_t err = std::atomic_load(&mComponent)->query(
2078 { &oStreamFormat, &prepend }, {}, C2_DONT_BLOCK, nullptr);
Wonsik Kim8ab25aa2019-06-24 16:37:37 -07002079 if (err != C2_OK && err != C2_BAD_INDEX) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002080 return UNKNOWN_ERROR;
2081 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002082
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002083 std::list<std::unique_ptr<C2Work>> flushedConfigs;
2084 mFlushedConfigs.lock()->swap(flushedConfigs);
2085 if (!flushedConfigs.empty()) {
Wonsik Kim92df7e42021-11-04 16:02:03 -07002086 {
2087 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2088 PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
2089 for (const std::unique_ptr<C2Work> &work : flushedConfigs) {
2090 watcher->onWorkQueued(
2091 work->input.ordinal.frameIndex.peeku(),
2092 std::vector(work->input.buffers),
2093 now);
2094 }
2095 }
Sungtak Lee368452b2024-10-17 01:16:29 +00002096 err = std::atomic_load(&mComponent)->queue(&flushedConfigs);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002097 if (err != C2_OK) {
2098 ALOGW("[%s] Error while queueing a flushed config", mName);
2099 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002100 }
2101 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002102 if (oStreamFormat.value == C2BufferData::LINEAR &&
Wonsik Kim34b28b42022-05-20 15:49:32 -07002103 (!prepend || prepend.value == PREPEND_HEADER_TO_NONE) &&
2104 !clientInputBuffers.empty()) {
2105 size_t minIndex = clientInputBuffers.begin()->first;
2106 sp<MediaCodecBuffer> minBuffer = clientInputBuffers.begin()->second;
2107 for (const auto &[index, buffer] : clientInputBuffers) {
2108 if (minBuffer->capacity() > buffer->capacity()) {
2109 minIndex = index;
2110 minBuffer = buffer;
2111 }
2112 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002113 // WORKAROUND: Some apps expect CSD available without queueing
2114 // any input. Queue an empty buffer to get the CSD.
Wonsik Kim34b28b42022-05-20 15:49:32 -07002115 minBuffer->setRange(0, 0);
2116 minBuffer->meta()->clear();
2117 minBuffer->meta()->setInt64("timeUs", 0);
2118 if (queueInputBufferInternal(minBuffer) != OK) {
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002119 ALOGW("[%s] Error while queueing an empty buffer to get CSD",
2120 mName);
2121 return UNKNOWN_ERROR;
2122 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07002123 clientInputBuffers.erase(minIndex);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002124 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002125
Wonsik Kim34b28b42022-05-20 15:49:32 -07002126 for (const auto &[index, buffer] : clientInputBuffers) {
2127 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002128 }
Pawin Vongmasae7bb8612020-06-04 06:15:22 -07002129
Pawin Vongmasa36653902018-11-15 00:10:25 -08002130 return OK;
2131}
2132
2133void CCodecBufferChannel::stop() {
2134 mSync.stop();
2135 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302136 mInfoBuffers.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002137}
2138
Sungtak Lee99144332023-01-26 11:03:14 +00002139void CCodecBufferChannel::stopUseOutputSurface(bool pushBlankBuffer) {
2140 sp<Surface> surface = mOutputSurface.lock()->surface;
2141 if (surface) {
Sungtak Leed964e2e2022-07-30 08:43:58 +00002142 C2BlockPool::local_id_t outputPoolId;
2143 {
2144 Mutexed<BlockPools>::Locked pools(mBlockPools);
2145 outputPoolId = pools->outputPoolId;
2146 }
Sungtak Lee368452b2024-10-17 01:16:29 +00002147 std::shared_ptr<Codec2Client::Component> comp = std::atomic_load(&mComponent);
2148 if (comp) comp->stopUsingOutputSurface(outputPoolId);
Sungtak Lee99144332023-01-26 11:03:14 +00002149
2150 if (pushBlankBuffer) {
2151 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(surface.get());
2152 if (anw) {
2153 pushBlankBuffersToNativeWindow(anw.get());
2154 }
2155 }
Sungtak Leed964e2e2022-07-30 08:43:58 +00002156 }
2157}
2158
Wonsik Kim936a89c2020-05-08 16:07:50 -07002159void CCodecBufferChannel::reset() {
2160 stop();
Wonsik Kim62545252021-01-20 11:25:41 -08002161 mPipelineWatcher.lock()->flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002162 {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002163 mHasInputSurface = false;
2164 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
2165 inputSurface->surface.reset();
2166 }
2167 {
Wonsik Kim936a89c2020-05-08 16:07:50 -07002168 Mutexed<Input>::Locked input(mInput);
2169 input->buffers.reset(new DummyInputBuffers(""));
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002170 input->extraBuffers.flush();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002171 }
2172 {
2173 Mutexed<Output>::Locked output(mOutput);
2174 output->buffers.reset();
2175 }
Brian Lindahl932bf602023-03-09 11:59:48 -07002176 // reset the frames that are being tracked for onFrameRendered callbacks
2177 mTrackedFrames.clear();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002178}
2179
2180void CCodecBufferChannel::release() {
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302181 mInfoBuffers.clear();
Sungtak Lee368452b2024-10-17 01:16:29 +00002182 std::shared_ptr<Codec2Client::Component> nullComp;
2183 std::atomic_store(&mComponent, nullComp);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002184 mInputAllocator.reset();
2185 mOutputSurface.lock()->surface.clear();
2186 {
2187 Mutexed<BlockPools>::Locked blockPools{mBlockPools};
2188 blockPools->inputPool.reset();
2189 blockPools->outputPoolIntf.reset();
2190 }
Wonsik Kima2e3cdd2020-05-20 15:14:42 -07002191 setCrypto(nullptr);
2192 setDescrambler(nullptr);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002193}
2194
Pawin Vongmasa36653902018-11-15 00:10:25 -08002195void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
2196 ALOGV("[%s] flush", mName);
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002197 std::list<std::unique_ptr<C2Work>> configs;
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002198 mInput.lock()->lastFlushIndex = mFrameIndex.load(std::memory_order_relaxed);
Wonsik Kim92df7e42021-11-04 16:02:03 -07002199 {
2200 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2201 for (const std::unique_ptr<C2Work> &work : flushedWork) {
2202 uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
2203 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
2204 watcher->onWorkDone(frameIndex);
2205 continue;
2206 }
2207 if (work->input.buffers.empty()
2208 || work->input.buffers.front() == nullptr
2209 || work->input.buffers.front()->data().linearBlocks().empty()) {
2210 ALOGD("[%s] no linear codec config data found", mName);
2211 watcher->onWorkDone(frameIndex);
2212 continue;
2213 }
2214 std::unique_ptr<C2Work> copy(new C2Work);
2215 copy->input.flags = C2FrameData::flags_t(
2216 work->input.flags | C2FrameData::FLAG_DROP_FRAME);
2217 copy->input.ordinal = work->input.ordinal;
2218 copy->input.ordinal.frameIndex = mFrameIndex++;
2219 for (size_t i = 0; i < work->input.buffers.size(); ++i) {
2220 copy->input.buffers.push_back(watcher->onInputBufferReleased(frameIndex, i));
2221 }
2222 for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
2223 copy->input.configUpdate.push_back(C2Param::Copy(*param));
2224 }
2225 copy->input.infoBuffers.insert(
2226 copy->input.infoBuffers.begin(),
2227 work->input.infoBuffers.begin(),
2228 work->input.infoBuffers.end());
2229 copy->worklets.emplace_back(new C2Worklet);
2230 configs.push_back(std::move(copy));
2231 watcher->onWorkDone(frameIndex);
2232 ALOGV("[%s] stashed flushed codec config data", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002233 }
2234 }
Wonsik Kim5ebfcb22021-01-05 18:58:15 -08002235 mFlushedConfigs.lock()->swap(configs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002236 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002237 Mutexed<Input>::Locked input(mInput);
2238 input->buffers->flush();
2239 input->extraBuffers.flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002240 }
2241 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002242 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002243 if (output->buffers) {
2244 output->buffers->flush(flushedWork);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002245 output->buffers->flushStash();
Wonsik Kim936a89c2020-05-08 16:07:50 -07002246 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002247 }
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302248 mInfoBuffers.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002249}
2250
2251void CCodecBufferChannel::onWorkDone(
2252 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002253 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002254 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002255 feedInputBufferIfAvailable();
2256 }
2257}
2258
2259void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08002260 uint64_t frameIndex, size_t arrayIndex) {
2261 std::shared_ptr<C2Buffer> buffer =
2262 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002263 bool newInputSlotAvailable = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002264 {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002265 Mutexed<Input>::Locked input(mInput);
Wonsik Kim6b2c8be2021-09-28 05:11:04 -07002266 if (input->lastFlushIndex >= frameIndex) {
2267 ALOGD("[%s] Ignoring stale input buffer done callback: "
2268 "last flush index = %lld, frameIndex = %lld",
2269 mName, input->lastFlushIndex.peekll(), (long long)frameIndex);
2270 } else {
2271 newInputSlotAvailable = input->buffers->expireComponentBuffer(buffer);
2272 if (!newInputSlotAvailable) {
2273 (void)input->extraBuffers.expireComponentBuffer(buffer);
2274 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002275 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002276 }
2277 if (newInputSlotAvailable) {
2278 feedInputBufferIfAvailable();
2279 }
2280}
2281
2282bool CCodecBufferChannel::handleWork(
2283 std::unique_ptr<C2Work> work,
2284 const sp<AMessage> &outputFormat,
2285 const C2StreamInitDataInfo::output *initData) {
Wonsik Kim936a89c2020-05-08 16:07:50 -07002286 {
Wonsik Kima4e049d2020-04-28 19:42:23 +00002287 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002288 if (!output->buffers) {
2289 return false;
2290 }
Wonsik Kime75a5da2020-02-14 17:29:03 -08002291 }
2292
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002293 // Whether the output buffer should be reported to the client or not.
2294 bool notifyClient = false;
2295
2296 if (work->result == C2_OK){
2297 notifyClient = true;
2298 } else if (work->result == C2_NOT_FOUND) {
2299 ALOGD("[%s] flushed work; ignored.", mName);
2300 } else {
2301 // C2_OK and C2_NOT_FOUND are the only results that we accept for processing
2302 // the config update.
2303 ALOGD("[%s] work failed to complete: %d", mName, work->result);
2304 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
2305 return false;
2306 }
2307
2308 if ((work->input.ordinal.frameIndex -
2309 mFirstValidFrameIndex.load()).peek() < 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002310 // Discard frames from previous generation.
2311 ALOGD("[%s] Discard frames from previous generation.", mName);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002312 notifyClient = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002313 }
2314
Wonsik Kimfca97a22024-08-30 20:20:42 +00002315 if (!mHasInputSurface && (work->worklets.size() != 1u
Pawin Vongmasa36653902018-11-15 00:10:25 -08002316 || !work->worklets.front()
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002317 || !(work->worklets.front()->output.flags &
2318 C2FrameData::FLAG_INCOMPLETE))) {
2319 mPipelineWatcher.lock()->onWorkDone(
2320 work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002321 }
2322
2323 // NOTE: MediaCodec usage supposedly have only one worklet
2324 if (work->worklets.size() != 1u) {
2325 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
2326 mName, work->worklets.size());
2327 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2328 return false;
2329 }
2330
2331 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
2332
2333 std::shared_ptr<C2Buffer> buffer;
2334 // NOTE: MediaCodec usage supposedly have only one output stream.
2335 if (worklet->output.buffers.size() > 1u) {
2336 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
2337 mName, worklet->output.buffers.size());
2338 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2339 return false;
2340 } else if (worklet->output.buffers.size() == 1u) {
2341 buffer = worklet->output.buffers[0];
2342 if (!buffer) {
2343 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
2344 }
2345 }
2346
Wonsik Kim3dedf682021-05-03 10:57:09 -07002347 std::optional<uint32_t> newInputDelay, newPipelineDelay, newOutputDelay, newReorderDepth;
2348 std::optional<C2Config::ordinal_key_t> newReorderKey;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002349 bool needMaxDequeueBufferCountUpdate = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002350 while (!worklet->output.configUpdate.empty()) {
2351 std::unique_ptr<C2Param> param;
2352 worklet->output.configUpdate.back().swap(param);
2353 worklet->output.configUpdate.pop_back();
2354 switch (param->coreIndex().coreIndex()) {
2355 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
2356 C2PortReorderBufferDepthTuning::output reorderDepth;
2357 if (reorderDepth.updateFrom(*param)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002358 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
2359 mName, reorderDepth.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002360 newReorderDepth = reorderDepth.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002361 needMaxDequeueBufferCountUpdate = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002362 } else {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002363 ALOGD("[%s] onWorkDone: failed to read reorder depth",
2364 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002365 }
2366 break;
2367 }
2368 case C2PortReorderKeySetting::CORE_INDEX: {
2369 C2PortReorderKeySetting::output reorderKey;
2370 if (reorderKey.updateFrom(*param)) {
Wonsik Kim3dedf682021-05-03 10:57:09 -07002371 newReorderKey = reorderKey.value;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002372 ALOGV("[%s] onWorkDone: updated reorder key to %u",
2373 mName, reorderKey.value);
2374 } else {
2375 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
2376 }
2377 break;
2378 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002379 case C2PortActualDelayTuning::CORE_INDEX: {
2380 if (param->isGlobal()) {
2381 C2ActualPipelineDelayTuning pipelineDelay;
2382 if (pipelineDelay.updateFrom(*param)) {
2383 ALOGV("[%s] onWorkDone: updating pipeline delay %u",
2384 mName, pipelineDelay.value);
2385 newPipelineDelay = pipelineDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002386 (void)mPipelineWatcher.lock()->pipelineDelay(
2387 pipelineDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002388 }
2389 }
2390 if (param->forInput()) {
2391 C2PortActualDelayTuning::input inputDelay;
2392 if (inputDelay.updateFrom(*param)) {
2393 ALOGV("[%s] onWorkDone: updating input delay %u",
2394 mName, inputDelay.value);
2395 newInputDelay = inputDelay.value;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002396 (void)mPipelineWatcher.lock()->inputDelay(
2397 inputDelay.value);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002398 }
2399 }
2400 if (param->forOutput()) {
2401 C2PortActualDelayTuning::output outputDelay;
2402 if (outputDelay.updateFrom(*param)) {
2403 ALOGV("[%s] onWorkDone: updating output delay %u",
2404 mName, outputDelay.value);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002405 (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
Wonsik Kim3dedf682021-05-03 10:57:09 -07002406 newOutputDelay = outputDelay.value;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002407 needMaxDequeueBufferCountUpdate = true;
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002408
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002409 }
2410 }
2411 break;
2412 }
ted.sunb1fbfdb2020-06-23 14:03:41 +08002413 case C2PortTunnelSystemTime::CORE_INDEX: {
2414 C2PortTunnelSystemTime::output frameRenderTime;
2415 if (frameRenderTime.updateFrom(*param)) {
2416 ALOGV("[%s] onWorkDone: frame rendered (sys:%lld ns, media:%lld us)",
2417 mName, (long long)frameRenderTime.value,
2418 (long long)worklet->output.ordinal.timestamp.peekll());
2419 mCCodecCallback->onOutputFramesRendered(
2420 worklet->output.ordinal.timestamp.peek(), frameRenderTime.value);
2421 }
2422 break;
2423 }
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +02002424 case C2StreamTunnelHoldRender::CORE_INDEX: {
2425 C2StreamTunnelHoldRender::output firstTunnelFrameHoldRender;
2426 if (!(worklet->output.flags & C2FrameData::FLAG_INCOMPLETE)) break;
2427 if (!firstTunnelFrameHoldRender.updateFrom(*param)) break;
2428 if (firstTunnelFrameHoldRender.value != C2_TRUE) break;
2429 ALOGV("[%s] onWorkDone: first tunnel frame ready", mName);
2430 mCCodecCallback->onFirstTunnelFrameReady();
2431 break;
2432 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002433 default:
2434 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2435 mName, param->index());
2436 break;
2437 }
2438 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002439 if (newInputDelay || newPipelineDelay) {
2440 Mutexed<Input>::Locked input(mInput);
2441 size_t newNumSlots =
2442 newInputDelay.value_or(input->inputDelay) +
2443 newPipelineDelay.value_or(input->pipelineDelay) +
2444 kSmoothnessFactor;
Xu Lai5732cab2023-03-16 19:50:18 +08002445 input->inputDelay = newInputDelay.value_or(input->inputDelay);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002446 if (input->buffers->isArrayMode()) {
2447 if (input->numSlots >= newNumSlots) {
2448 input->numExtraSlots = 0;
2449 } else {
2450 input->numExtraSlots = newNumSlots - input->numSlots;
2451 }
2452 ALOGV("[%s] onWorkDone: updated number of extra slots to %zu (input array mode)",
2453 mName, input->numExtraSlots);
2454 } else {
2455 input->numSlots = newNumSlots;
2456 }
2457 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002458 size_t numOutputSlots = 0;
2459 uint32_t reorderDepth = 0;
2460 bool outputBuffersChanged = false;
2461 if (newReorderKey || newReorderDepth || needMaxDequeueBufferCountUpdate) {
2462 Mutexed<Output>::Locked output(mOutput);
2463 if (!output->buffers) {
2464 return false;
Wonsik Kim315e40a2020-09-09 14:11:50 -07002465 }
Wonsik Kim3dedf682021-05-03 10:57:09 -07002466 numOutputSlots = output->numSlots;
2467 if (newReorderKey) {
2468 output->buffers->setReorderKey(newReorderKey.value());
2469 }
2470 if (newReorderDepth) {
2471 output->buffers->setReorderDepth(newReorderDepth.value());
2472 }
2473 reorderDepth = output->buffers->getReorderDepth();
2474 if (newOutputDelay) {
2475 output->outputDelay = newOutputDelay.value();
2476 numOutputSlots = newOutputDelay.value() + kSmoothnessFactor;
2477 if (output->numSlots < numOutputSlots) {
2478 output->numSlots = numOutputSlots;
2479 if (output->buffers->isArrayMode()) {
2480 OutputBuffersArray *array =
2481 (OutputBuffersArray *)output->buffers.get();
2482 ALOGV("[%s] onWorkDone: growing output buffer array to %zu",
2483 mName, numOutputSlots);
2484 array->grow(numOutputSlots);
2485 outputBuffersChanged = true;
2486 }
2487 }
2488 }
2489 numOutputSlots = output->numSlots;
2490 }
2491 if (outputBuffersChanged) {
2492 mCCodecCallback->onOutputBuffersChanged();
2493 }
2494 if (needMaxDequeueBufferCountUpdate) {
Wonsik Kim84f439f2021-05-03 10:57:09 -07002495 int maxDequeueCount = 0;
Sungtak Leea714f112021-03-16 05:40:03 -07002496 {
2497 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2498 maxDequeueCount = output->maxDequeueBuffers =
Wonsik Kim3a692e62023-05-19 15:37:22 -07002499 numOutputSlots + reorderDepth + mRenderingDepth;
Sungtak Leea714f112021-03-16 05:40:03 -07002500 if (output->surface) {
2501 output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
2502 }
2503 }
2504 if (maxDequeueCount > 0) {
Sungtak Lee368452b2024-10-17 01:16:29 +00002505 std::atomic_load(&mComponent)->setOutputSurfaceMaxDequeueCount(maxDequeueCount);
Wonsik Kim315e40a2020-09-09 14:11:50 -07002506 }
2507 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002508
Pawin Vongmasa36653902018-11-15 00:10:25 -08002509 int32_t flags = 0;
2510 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
My Named4d22242022-03-28 13:53:32 -07002511 flags |= BUFFER_FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002512 ALOGV("[%s] onWorkDone: output EOS", mName);
2513 }
2514
Pawin Vongmasa36653902018-11-15 00:10:25 -08002515 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2516 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2517 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2518 // shall correspond to the client input timesamp (in customOrdinal). By using the
2519 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2520 // produces multiple output.
2521 c2_cntr64_t timestamp =
2522 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2523 - work->input.ordinal.timestamp;
Wonsik Kimfca97a22024-08-30 20:20:42 +00002524 if (mHasInputSurface) {
Wonsik Kim95ba0162019-03-19 15:51:54 -07002525 // When using input surface we need to restore the original input timestamp.
2526 timestamp = work->input.ordinal.customOrdinal;
2527 }
My Name6bd9a7d2022-03-25 12:37:58 -07002528 ScopedTrace trace(ATRACE_TAG, android::base::StringPrintf(
2529 "CCodecBufferChannel::onWorkDone(%s@ts=%lld)", mName, timestamp.peekll()).c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002530 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2531 mName,
2532 work->input.ordinal.customOrdinal.peekll(),
2533 work->input.ordinal.timestamp.peekll(),
2534 worklet->output.ordinal.timestamp.peekll(),
2535 timestamp.peekll());
2536
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002537 // csd cannot be re-ordered and will always arrive first.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002538 if (initData != nullptr) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002539 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim72a71012023-02-06 17:35:21 -08002540 if (!output->buffers) {
2541 return false;
2542 }
2543 if (outputFormat) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002544 output->buffers->updateSkipCutBuffer(outputFormat);
2545 output->buffers->setFormat(outputFormat);
2546 }
2547 if (!notifyClient) {
2548 return false;
2549 }
2550 size_t index;
2551 sp<MediaCodecBuffer> outBuffer;
Wonsik Kim72a71012023-02-06 17:35:21 -08002552 if (output->buffers->registerCsd(initData, &index, &outBuffer) == OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002553 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
My Named4d22242022-03-28 13:53:32 -07002554 outBuffer->meta()->setInt32("flags", BUFFER_FLAG_CODEC_CONFIG);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002555 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2556
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002557 // TRICKY: we want popped buffers reported in order, so sending
2558 // the callback while holding the lock here. This assumes that
2559 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2560 // callbacks are always sent with the Output lock held.
Pawin Vongmasa36653902018-11-15 00:10:25 -08002561 mCallback->onOutputBufferAvailable(index, outBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002562 } else {
2563 ALOGD("[%s] onWorkDone: unable to register csd", mName);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002564 output.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002565 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002566 return false;
2567 }
2568 }
2569
Wonsik Kimec585c32021-10-01 01:11:00 -07002570 bool drop = false;
2571 if (worklet->output.flags & C2FrameData::FLAG_DROP_FRAME) {
2572 ALOGV("[%s] onWorkDone: drop buffer but keep metadata", mName);
2573 drop = true;
2574 }
2575
Marc Kassisec910342022-11-25 11:43:05 +01002576 // Workaround: if C2FrameData::FLAG_DROP_FRAME is not implemented in
2577 // HAL, the flag is then removed in the corresponding output buffer.
2578 if (work->input.flags & C2FrameData::FLAG_DROP_FRAME) {
2579 flags |= BUFFER_FLAG_DECODE_ONLY;
2580 }
2581
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002582 if (notifyClient && !buffer && !flags) {
Wonsik Kimec585c32021-10-01 01:11:00 -07002583 if (mTunneled && drop && outputFormat) {
Houxiang Daie74e5062022-05-19 15:32:54 +08002584 if (mOutputFormat != outputFormat) {
2585 ALOGV("[%s] onWorkDone: Keep tunneled, drop frame with format change (%lld)",
2586 mName, work->input.ordinal.frameIndex.peekull());
2587 mOutputFormat = outputFormat;
2588 } else {
2589 ALOGV("[%s] onWorkDone: Not reporting output buffer without format change (%lld)",
2590 mName, work->input.ordinal.frameIndex.peekull());
2591 notifyClient = false;
2592 }
Wonsik Kimec585c32021-10-01 01:11:00 -07002593 } else {
2594 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2595 mName, work->input.ordinal.frameIndex.peekull());
2596 notifyClient = false;
2597 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002598 }
2599
2600 if (buffer) {
2601 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2602 // TODO: properly translate these to metadata
2603 switch (info->coreIndex().coreIndex()) {
2604 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
Lajos Molnar3bb81cd2019-02-20 15:10:30 -08002605 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2Config::SYNC_FRAME) {
My Named4d22242022-03-28 13:53:32 -07002606 flags |= BUFFER_FLAG_KEY_FRAME;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002607 }
2608 break;
2609 default:
2610 break;
2611 }
2612 }
2613 }
2614
2615 {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002616 Mutexed<Output>::Locked output(mOutput);
Wonsik Kimc23cc402020-05-28 14:53:40 -07002617 if (!output->buffers) {
2618 return false;
2619 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002620 output->buffers->pushToStash(
2621 buffer,
2622 notifyClient,
2623 timestamp.peek(),
2624 flags,
2625 outputFormat,
2626 worklet->output.ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002627 }
2628 sendOutputBuffers();
2629 return true;
2630}
2631
2632void CCodecBufferChannel::sendOutputBuffers() {
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002633 OutputBuffers::BufferAction action;
Wonsik Kima4e049d2020-04-28 19:42:23 +00002634 size_t index;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002635 sp<MediaCodecBuffer> outBuffer;
2636 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002637
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002638 constexpr int kMaxReallocTry = 5;
2639 int reallocTryNum = 0;
2640
Pawin Vongmasa36653902018-11-15 00:10:25 -08002641 while (true) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002642 Mutexed<Output>::Locked output(mOutput);
Wonsik Kim936a89c2020-05-08 16:07:50 -07002643 if (!output->buffers) {
2644 return;
2645 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002646 action = output->buffers->popFromStashAndRegister(
2647 &c2Buffer, &index, &outBuffer);
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002648 if (action != OutputBuffers::REALLOCATE) {
2649 reallocTryNum = 0;
2650 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002651 switch (action) {
2652 case OutputBuffers::SKIP:
2653 return;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002654 case OutputBuffers::NOTIFY_CLIENT:
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002655 {
Wonsik Kim5c2c8902023-05-09 10:53:15 -07002656 // TRICKY: we want popped buffers reported in order, so sending
2657 // the callback while holding the lock here. This assumes that
2658 // onOutputBufferAvailable() does not block. onOutputBufferAvailable()
2659 // callbacks are always sent with the Output lock held.
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002660 if (c2Buffer) {
2661 std::shared_ptr<const C2AccessUnitInfos::output> bufferMetadata =
2662 std::static_pointer_cast<const C2AccessUnitInfos::output>(
2663 c2Buffer->getInfo(C2AccessUnitInfos::output::PARAM_TYPE));
2664 if (bufferMetadata && bufferMetadata->flexCount() > 0) {
2665 uint32_t flag = 0;
2666 std::vector<AccessUnitInfo> accessUnitInfos;
2667 for (int nMeta = 0; nMeta < bufferMetadata->flexCount(); nMeta++) {
2668 const C2AccessUnitInfosStruct &bufferMetadataStruct =
2669 bufferMetadata->m.values[nMeta];
2670 flag = convertFlags(bufferMetadataStruct.flags, false);
2671 accessUnitInfos.emplace_back(flag,
Arun Johnson9c6e91e2024-09-10 18:46:02 +00002672 bufferMetadataStruct.size,
2673 bufferMetadataStruct.timestamp);
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002674 }
2675 sp<WrapperObject<std::vector<AccessUnitInfo>>> obj{
2676 new WrapperObject<std::vector<AccessUnitInfo>>{accessUnitInfos}};
2677 outBuffer->meta()->setObject("accessUnitInfo", obj);
2678 }
2679 }
Wonsik Kim9dbb4162024-09-24 19:25:14 +00002680 mCallback->onOutputBufferAvailable(index, outBuffer);
2681 [[fallthrough]];
2682 }
2683 case OutputBuffers::DISCARD: {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002684 if (mHasInputSurface && android::media::codec::provider_->input_surface_throttle()) {
2685 Mutexed<InputSurface>::Locked inputSurface(mInputSurface);
2686 --inputSurface->numProcessingBuffersBalance;
Wonsik Kim9dbb4162024-09-24 19:25:14 +00002687 ALOGV("[%s] onWorkDone: numProcessingBuffersBalance = %lld",
2688 mName, static_cast<long long>(inputSurface->numProcessingBuffersBalance));
Wonsik Kimfca97a22024-08-30 20:20:42 +00002689 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002690 break;
Arun Johnsonf4a81f72023-11-09 21:22:48 +00002691 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002692 case OutputBuffers::REALLOCATE:
Sungtak Lee8ceef4d2022-06-15 00:49:26 +00002693 if (++reallocTryNum > kMaxReallocTry) {
2694 output.unlock();
2695 ALOGE("[%s] sendOutputBuffers: tried %d realloc and failed",
2696 mName, kMaxReallocTry);
2697 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2698 return;
2699 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002700 if (!output->buffers->isArrayMode()) {
2701 output->buffers =
2702 output->buffers->toArrayMode(output->numSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002703 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002704 static_cast<OutputBuffersArray*>(output->buffers.get())->
2705 realloc(c2Buffer);
2706 output.unlock();
2707 mCCodecCallback->onOutputBuffersChanged();
Wonsik Kim4ada73d2020-05-26 14:58:07 -07002708 break;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07002709 case OutputBuffers::RETRY:
2710 ALOGV("[%s] sendOutputBuffers: unable to register output buffer",
2711 mName);
2712 return;
2713 default:
2714 LOG_ALWAYS_FATAL("[%s] sendOutputBuffers: "
2715 "corrupted BufferAction value (%d) "
2716 "returned from popFromStashAndRegister.",
2717 mName, int(action));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002718 return;
2719 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002720 }
2721}
2722
Sungtak Lee214ce612023-11-01 10:01:13 +00002723status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface,
2724 uint32_t generation, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002725 sp<IGraphicBufferProducer> producer;
Sungtak Lee99144332023-01-26 11:03:14 +00002726 int maxDequeueCount;
2727 sp<Surface> oldSurface;
2728 {
2729 Mutexed<OutputSurface>::Locked outputSurface(mOutputSurface);
2730 maxDequeueCount = outputSurface->maxDequeueBuffers;
2731 oldSurface = outputSurface->surface;
2732 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002733 if (newSurface) {
2734 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Sungtak Leeab6f2f32019-02-15 14:43:51 -08002735 newSurface->setDequeueTimeout(kDequeueTimeoutNs);
Sungtak Leedb14cba2021-04-10 00:50:23 -07002736 newSurface->setMaxDequeuedBufferCount(maxDequeueCount);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002737 producer = newSurface->getIGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002738 } else {
2739 ALOGE("[%s] setting output surface to null", mName);
2740 return INVALID_OPERATION;
2741 }
2742
2743 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2744 C2BlockPool::local_id_t outputPoolId;
2745 {
2746 Mutexed<BlockPools>::Locked pools(mBlockPools);
2747 outputPoolId = pools->outputPoolId;
2748 outputPoolIntf = pools->outputPoolIntf;
2749 }
2750
2751 if (outputPoolIntf) {
Sungtak Lee368452b2024-10-17 01:16:29 +00002752 if (std::atomic_load(&mComponent)->setOutputSurface(
Pawin Vongmasa36653902018-11-15 00:10:25 -08002753 outputPoolId,
2754 producer,
Sungtak Leedb14cba2021-04-10 00:50:23 -07002755 generation,
2756 maxDequeueCount) != C2_OK) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002757 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2758 return INVALID_OPERATION;
2759 }
2760 }
2761
2762 {
2763 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2764 output->surface = newSurface;
2765 output->generation = generation;
Brian Lindahl932bf602023-03-09 11:59:48 -07002766 initializeFrameTrackingFor(static_cast<ANativeWindow *>(newSurface.get()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002767 }
2768
Sungtak Lee99144332023-01-26 11:03:14 +00002769 if (oldSurface && pushBlankBuffer) {
2770 // When ReleaseSurface was set from MediaCodec,
2771 // pushing a blank buffer at the end might be necessary.
2772 sp<ANativeWindow> anw = static_cast<ANativeWindow *>(oldSurface.get());
2773 if (anw) {
2774 pushBlankBuffersToNativeWindow(anw.get());
2775 }
2776 }
2777
Pawin Vongmasa36653902018-11-15 00:10:25 -08002778 return OK;
2779}
2780
Wonsik Kimab34ed62019-01-31 15:28:46 -08002781PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002782 // Otherwise, component may have stalled work due to input starvation up to
2783 // the sum of the delay in the pipeline.
Wonsik Kim31512192022-05-02 18:22:37 -07002784 // TODO(b/231253301): When client pushed EOS, the pipeline could have less
2785 // number of frames.
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002786 size_t n = 0;
Wonsik Kim31512192022-05-02 18:22:37 -07002787 size_t outputDelay = mOutput.lock()->outputDelay;
2788 {
Wonsik Kimf0e7d222019-06-28 12:33:16 -07002789 Mutexed<Input>::Locked input(mInput);
2790 n = input->inputDelay + input->pipelineDelay + outputDelay;
2791 }
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002792 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002793}
2794
Pawin Vongmasa36653902018-11-15 00:10:25 -08002795void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2796 mMetaMode = mode;
2797}
2798
Wonsik Kim596187e2019-10-25 12:44:10 -07002799void CCodecBufferChannel::setCrypto(const sp<ICrypto> &crypto) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002800 if (mCrypto != nullptr) {
2801 for (std::pair<wp<HidlMemory>, int32_t> entry : mHeapSeqNumMap) {
2802 mCrypto->unsetHeap(entry.second);
2803 }
2804 mHeapSeqNumMap.clear();
2805 if (mHeapSeqNum >= 0) {
2806 mCrypto->unsetHeap(mHeapSeqNum);
2807 mHeapSeqNum = -1;
2808 }
2809 }
Wonsik Kim596187e2019-10-25 12:44:10 -07002810 mCrypto = crypto;
2811}
2812
2813void CCodecBufferChannel::setDescrambler(const sp<IDescrambler> &descrambler) {
2814 mDescrambler = descrambler;
2815}
2816
Songyue Han1e6769b2023-08-30 18:09:27 +00002817uint32_t CCodecBufferChannel::getBuffersPixelFormat(bool isEncoder) {
2818 if (isEncoder) {
2819 return getInputBuffersPixelFormat();
2820 } else {
2821 return getOutputBuffersPixelFormat();
2822 }
2823}
2824
2825uint32_t CCodecBufferChannel::getInputBuffersPixelFormat() {
2826 Mutexed<Input>::Locked input(mInput);
2827 if (input->buffers == nullptr) {
2828 return PIXEL_FORMAT_UNKNOWN;
2829 }
2830 return input->buffers->getPixelFormatIfApplicable();
2831}
2832
2833uint32_t CCodecBufferChannel::getOutputBuffersPixelFormat() {
2834 Mutexed<Output>::Locked output(mOutput);
2835 if (output->buffers == nullptr) {
2836 return PIXEL_FORMAT_UNKNOWN;
2837 }
2838 return output->buffers->getPixelFormatIfApplicable();
2839}
2840
2841void CCodecBufferChannel::resetBuffersPixelFormat(bool isEncoder) {
2842 if (isEncoder) {
2843 Mutexed<Input>::Locked input(mInput);
2844 if (input->buffers == nullptr) {
2845 return;
2846 }
2847 input->buffers->resetPixelFormatIfApplicable();
2848 } else {
2849 Mutexed<Output>::Locked output(mOutput);
2850 if (output->buffers == nullptr) {
2851 return;
2852 }
2853 output->buffers->resetPixelFormatIfApplicable();
2854 }
2855}
2856
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302857void CCodecBufferChannel::setInfoBuffer(const std::shared_ptr<C2InfoBuffer> &buffer) {
Wonsik Kimfca97a22024-08-30 20:20:42 +00002858 if (!mHasInputSurface) {
Harish Mahendrakar2b095d92024-05-13 16:51:15 -07002859 mInfoBuffers.push_back(buffer);
2860 } else {
2861 std::list<std::unique_ptr<C2Work>> items;
2862 std::unique_ptr<C2Work> work(new C2Work);
2863 work->input.infoBuffers.emplace_back(*buffer);
2864 work->worklets.emplace_back(new C2Worklet);
2865 items.push_back(std::move(work));
Harish Mahendrakar2b095d92024-05-13 16:51:15 -07002866 }
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302867}
2868
Pawin Vongmasa36653902018-11-15 00:10:25 -08002869status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2870 // C2_OK is always translated to OK.
2871 if (c2s == C2_OK) {
2872 return OK;
2873 }
2874
2875 // Operation-dependent translation
2876 // TODO: Add as necessary
2877 switch (c2op) {
2878 case C2_OPERATION_Component_start:
2879 switch (c2s) {
2880 case C2_NO_MEMORY:
2881 return NO_MEMORY;
2882 default:
2883 return UNKNOWN_ERROR;
2884 }
2885 default:
2886 break;
2887 }
2888
2889 // Backup operation-agnostic translation
2890 switch (c2s) {
2891 case C2_BAD_INDEX:
2892 return BAD_INDEX;
2893 case C2_BAD_VALUE:
2894 return BAD_VALUE;
2895 case C2_BLOCKING:
2896 return WOULD_BLOCK;
2897 case C2_DUPLICATE:
2898 return ALREADY_EXISTS;
2899 case C2_NO_INIT:
2900 return NO_INIT;
2901 case C2_NO_MEMORY:
2902 return NO_MEMORY;
2903 case C2_NOT_FOUND:
2904 return NAME_NOT_FOUND;
2905 case C2_TIMED_OUT:
2906 return TIMED_OUT;
2907 case C2_BAD_STATE:
2908 case C2_CANCELED:
2909 case C2_CANNOT_DO:
2910 case C2_CORRUPTED:
2911 case C2_OMITTED:
2912 case C2_REFUSED:
2913 return UNKNOWN_ERROR;
2914 default:
2915 return -static_cast<status_t>(c2s);
2916 }
2917}
2918
Pawin Vongmasa36653902018-11-15 00:10:25 -08002919} // namespace android