blob: 68f1dda628a0992880679b9c18b43c785dd51b37 [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodec"
19#include <utils/Log.h>
20
21#include <sstream>
22#include <thread>
23
Ram Mohan16511072023-12-11 19:41:31 +053024#include <android_media_codec.h>
25
Pawin Vongmasa36653902018-11-15 00:10:25 -080026#include <C2Config.h>
27#include <C2Debug.h>
28#include <C2ParamInternal.h>
29#include <C2PlatformSupport.h>
30
Sungtak Lee92bca442024-03-12 09:10:31 +000031#include <aidl/android/hardware/graphics/common/Dataspace.h>
32#include <aidl/android/media/IAidlGraphicBufferSource.h>
33#include <aidl/android/media/IAidlBufferSource.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080034#include <android/IOMXBufferSource.h>
Pawin Vongmasabf69de92019-10-29 06:21:27 -070035#include <android/hardware/media/c2/1.0/IInputSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080036#include <android/hardware/media/omx/1.0/IGraphicBufferSource.h>
37#include <android/hardware/media/omx/1.0/IOmx.h>
Wonsik Kim50811882022-04-28 15:57:27 -070038#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080039#include <android-base/stringprintf.h>
40#include <cutils/properties.h>
41#include <gui/IGraphicBufferProducer.h>
42#include <gui/Surface.h>
43#include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070044#include <media/omx/1.0/WOmxNode.h>
45#include <media/openmax/OMX_Core.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080046#include <media/openmax/OMX_IndexExt.h>
Wonsik Kim1f5063d2021-05-03 15:41:17 -070047#include <media/stagefright/foundation/avc_utils.h>
Harish Mahendrakarf6b3e5e2024-03-21 21:04:28 +000048#include <media/stagefright/foundation/AUtils.h>
Sungtak Lee92bca442024-03-12 09:10:31 +000049#include <media/stagefright/aidlpersistentsurface/AidlGraphicBufferSource.h>
50#include <media/stagefright/aidlpersistentsurface/C2NodeDef.h>
51#include <media/stagefright/aidlpersistentsurface/wrapper/Conversion.h>
52#include <media/stagefright/aidlpersistentsurface/wrapper/WAidlGraphicBufferSource.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070053#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
54#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070055#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080056#include <media/stagefright/BufferProducerWrapper.h>
57#include <media/stagefright/MediaCodecConstants.h>
Songyue Han1e6769b2023-08-30 18:09:27 +000058#include <media/stagefright/MediaCodecMetricsConstants.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080059#include <media/stagefright/PersistentSurface.h>
Brian Lindahlff74e9d2023-07-20 14:44:04 -060060#include <media/stagefright/RenderedFrameInfo.h>
ted.sun765db4d2020-06-23 14:03:41 +080061#include <utils/NativeHandle.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080062
Sungtak Lee92bca442024-03-12 09:10:31 +000063#include "C2AidlNode.h"
Sungtak Lee64c9d932024-03-26 03:46:53 +000064#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080065#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070066#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080067#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080068#include "InputSurfaceWrapper.h"
69
70extern "C" android::PersistentSurface *CreateInputSurface();
71
72namespace android {
73
74using namespace std::chrono_literals;
75using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
76using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080077using ::android::hardware::media::c2::V1_0::IInputSurface;
Sungtak Lee92bca442024-03-12 09:10:31 +000078using ::aidl::android::media::IAidlBufferSource;
79using ::aidl::android::media::IAidlNode;
80using ::android::media::AidlGraphicBufferSource;
81using ::android::media::WAidlGraphicBufferSource;
82using ::android::media::aidl_conversion::fromAidlStatus;
Pawin Vongmasa36653902018-11-15 00:10:25 -080083
Wonsik Kim9917d4a2019-10-24 12:56:38 -070084typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Sungtak Lee92bca442024-03-12 09:10:31 +000085typedef aidl::android::media::IAidlGraphicBufferSource AGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070086typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070087
Pawin Vongmasa36653902018-11-15 00:10:25 -080088namespace {
89
90class CCodecWatchdog : public AHandler {
91private:
92 enum {
93 kWhatWatch,
94 };
95 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
96
97public:
98 static sp<CCodecWatchdog> getInstance() {
Wonsik Kim2b479b72024-08-22 19:14:48 +000099 static sp<CCodecWatchdog> sInstance = [] {
100 sp<CCodecWatchdog> instance = new CCodecWatchdog;
101 // the instance should never get destructed
102 instance->incStrong((void *)CCodecWatchdog::getInstance);
103 instance->init();
104 return instance;
105 }();
106 return sInstance;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800107 }
108
109 ~CCodecWatchdog() = default;
110
111 void watch(sp<CCodec> codec) {
112 bool shouldPost = false;
113 {
114 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
115 // If a watch message is in flight, piggy-back this instance as well.
116 // Otherwise, post a new watch message.
117 shouldPost = codecs->empty();
118 codecs->emplace(codec);
119 }
120 if (shouldPost) {
121 ALOGV("posting watch message");
122 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
123 }
124 }
125
126protected:
127 void onMessageReceived(const sp<AMessage> &msg) {
128 switch (msg->what()) {
129 case kWhatWatch: {
130 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
131 ALOGV("watch for %zu codecs", codecs->size());
132 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
133 sp<CCodec> codec = it->promote();
134 if (codec == nullptr) {
135 continue;
136 }
137 codec->initiateReleaseIfStuck();
138 }
139 codecs->clear();
140 break;
141 }
142
143 default: {
144 TRESPASS("CCodecWatchdog: unrecognized message");
145 }
146 }
147 }
148
149private:
150 CCodecWatchdog() : mLooper(new ALooper) {}
151
Wonsik Kim2b479b72024-08-22 19:14:48 +0000152 void init() {
153 ALOGV("init");
154 mLooper->setName("CCodecWatchdog");
155 mLooper->registerHandler(this);
156 mLooper->start();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800157 }
158
159 sp<ALooper> mLooper;
160
161 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
162};
163
164class C2InputSurfaceWrapper : public InputSurfaceWrapper {
165public:
166 explicit C2InputSurfaceWrapper(
167 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
168 mSurface(surface) {
169 }
170
171 ~C2InputSurfaceWrapper() override = default;
172
173 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
174 if (mConnection != nullptr) {
175 return ALREADY_EXISTS;
176 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800177 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800178 }
179
180 void disconnect() override {
181 if (mConnection != nullptr) {
182 mConnection->disconnect();
183 mConnection = nullptr;
184 }
185 }
186
187 status_t start() override {
188 // InputSurface does not distinguish started state
189 return OK;
190 }
191
192 status_t signalEndOfInputStream() override {
193 C2InputSurfaceEosTuning eos(true);
194 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800195 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800196 if (err != C2_OK) {
197 return UNKNOWN_ERROR;
198 }
199 return OK;
200 }
201
202 status_t configure(Config &config __unused) {
203 // TODO
204 return OK;
205 }
206
207private:
208 std::shared_ptr<Codec2Client::InputSurface> mSurface;
209 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
210};
211
Sungtak Lee92bca442024-03-12 09:10:31 +0000212class HGraphicBufferSourceWrapper : public InputSurfaceWrapper {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800213public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700214 typedef hardware::media::omx::V1_0::Status OmxStatus;
215
Sungtak Lee92bca442024-03-12 09:10:31 +0000216 HGraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700217 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800218 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700219 uint32_t height,
220 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800221 : mSource(source), mWidth(width), mHeight(height) {
222 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700223 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800224 }
Sungtak Lee92bca442024-03-12 09:10:31 +0000225 ~HGraphicBufferSourceWrapper() override = default;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800226
227 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700228 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
229 *node = new C2OMXNode(comp);
230 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(*node);
231 (*node)->setFrameSize(mWidth, mHeight);
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700232 // Usage is queried during configure(), so setting it beforehand.
Sungtak Lee0cd4fbc2023-02-02 00:59:01 +0000233 // 64 bit set parameter is existing only in C2OMXNode.
234 OMX_U64 usage64 = mConfig.mUsage;
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700235 status_t res = (*node)->setParameter(
Sungtak Lee0cd4fbc2023-02-02 00:59:01 +0000236 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits64,
237 &usage64, sizeof(usage64));
238
239 if (res != OK) {
240 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700241 (void)(*node)->setParameter(
Sungtak Lee0cd4fbc2023-02-02 00:59:01 +0000242 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
243 &usage, sizeof(usage));
244 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700245
Yanqiang Fanc56f3e62021-09-28 16:54:07 +0800246 return GetStatus(mSource->configure(
247 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800248 }
249
250 void disconnect() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700251 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
252 if ((*node) == nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800253 return;
254 }
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700255 sp<IOMXBufferSource> source = (*node)->getSource();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800256 if (source == nullptr) {
257 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
258 return;
259 }
260 source->onOmxIdle();
261 source->onOmxLoaded();
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700262 node->clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700263 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800264 }
265
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700266 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
267 if (status.isOk()) {
268 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
269 } else if (status.isDeadObject()) {
270 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800271 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700272 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800273 }
274
275 status_t start() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700276 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
277 if ((*node) == nullptr) {
278 return NO_INIT;
279 }
280 sp<IOMXBufferSource> source = (*node)->getSource();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800281 if (source == nullptr) {
282 return NO_INIT;
283 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900284
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800285 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800286 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900287
Wonsik Kim34d66012021-03-01 16:40:33 -0800288 OMX_PARAM_PORTDEFINITIONTYPE param;
289 param.nPortIndex = kPortIndexInput;
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700290 status_t err = (*node)->getParameter(OMX_IndexParamPortDefinition,
Wonsik Kim34d66012021-03-01 16:40:33 -0800291 &param, sizeof(param));
292 if (err == OK) {
293 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900294 }
295
296 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800297 source->onInputBufferAdded(i);
298 }
299
300 source->onOmxExecuting();
301 return OK;
302 }
303
304 status_t signalEndOfInputStream() override {
305 return GetStatus(mSource->signalEndOfInputStream());
306 }
307
308 status_t configure(Config &config) {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700309 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800310 std::stringstream status;
311 status_t err = OK;
312
313 // handle each configuration granually, in case we need to handle part of the configuration
314 // elsewhere
315
316 // TRICKY: we do not unset frame delay repeating
317 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
318 int64_t us = 1e6 / config.mMinFps + 0.5;
319 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
320 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
321 if (res != OK) {
322 status << " (=> " << asString(res) << ")";
323 err = res;
324 }
325 mConfig.mMinFps = config.mMinFps;
326 }
327
328 // pts gap
329 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700330 if ((*node) != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800331 OMX_PARAM_U32TYPE ptrGapParam = {};
332 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700333 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800334 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
335 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700336 // float -> uint32_t is undefined if the value is negative.
337 // First convert to int32_t to ensure the expected behavior.
338 ptrGapParam.nU32 = int32_t(gap);
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700339 (void)(*node)->setParameter(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800340 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
341 &ptrGapParam, sizeof(ptrGapParam));
342 }
343 }
344
345 // max fps
346 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700347 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800348 && config.mMaxFps != mConfig.mMaxFps) {
349 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
350 status << " maxFps=" << config.mMaxFps;
351 if (res != OK) {
352 status << " (=> " << asString(res) << ")";
353 err = res;
354 }
355 mConfig.mMaxFps = config.mMaxFps;
356 }
357
358 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
359 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
360 status << " timeOffset " << config.mTimeOffsetUs << "us";
361 if (res != OK) {
362 status << " (=> " << asString(res) << ")";
363 err = res;
364 }
365 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
366 }
367
368 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
369 status_t res =
370 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
371 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
372 if (res != OK) {
373 status << " (=> " << asString(res) << ")";
374 err = res;
375 }
376 mConfig.mCaptureFps = config.mCaptureFps;
377 mConfig.mCodedFps = config.mCodedFps;
378 }
379
380 if (config.mStartAtUs != mConfig.mStartAtUs
381 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
382 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
383 status << " start at " << config.mStartAtUs << "us";
384 if (res != OK) {
385 status << " (=> " << asString(res) << ")";
386 err = res;
387 }
388 mConfig.mStartAtUs = config.mStartAtUs;
389 mConfig.mStopped = config.mStopped;
390 }
391
392 // suspend-resume
393 if (config.mSuspended != mConfig.mSuspended) {
394 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
395 status << " " << (config.mSuspended ? "suspend" : "resume")
396 << " at " << config.mSuspendAtUs << "us";
397 if (res != OK) {
398 status << " (=> " << asString(res) << ")";
399 err = res;
400 }
401 mConfig.mSuspended = config.mSuspended;
402 mConfig.mSuspendAtUs = config.mSuspendAtUs;
403 }
404
405 if (config.mStopped != mConfig.mStopped && config.mStopped) {
406 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
407 status << " stop at " << config.mStopAtUs << "us";
408 if (res != OK) {
409 status << " (=> " << asString(res) << ")";
410 err = res;
411 } else {
412 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700413 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
414 [&res, &delayUs = config.mInputDelayUs](
415 auto status, auto stopTimeOffsetUs) {
416 res = static_cast<status_t>(status);
417 delayUs = stopTimeOffsetUs;
418 });
419 if (!trans.isOk()) {
420 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
421 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800422 if (res != OK) {
423 status << " (=> " << asString(res) << ")";
424 } else {
425 status << "=" << config.mInputDelayUs << "us";
426 }
427 mConfig.mInputDelayUs = config.mInputDelayUs;
428 }
429 mConfig.mStopAtUs = config.mStopAtUs;
430 mConfig.mStopped = config.mStopped;
431 }
432
433 // color aspects (android._color-aspects)
434
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700435 // consumer usage is queried earlier.
436
Wonsik Kima1335e12021-04-22 16:28:29 -0700437 // priority
438 if (mConfig.mPriority != config.mPriority) {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700439 if (config.mPriority != INT_MAX && (*node) != nullptr) {
440 (*node)->setPriority(config.mPriority);
Wonsik Kima1335e12021-04-22 16:28:29 -0700441 }
442 mConfig.mPriority = config.mPriority;
443 }
444
Wonsik Kimbd557932019-07-02 15:51:20 -0700445 if (status.str().empty()) {
446 ALOGD("ISConfig not changed");
447 } else {
448 ALOGD("ISConfig%s", status.str().c_str());
449 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800450 return err;
451 }
452
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700453 void onInputBufferDone(c2_cntr64_t index) override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700454 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
455 if ((*node) == nullptr) {
456 return;
457 }
458 (*node)->onInputBufferDone(index);
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700459 }
460
Wonsik Kim1951d932024-05-23 22:59:00 +0000461 void onInputBufferEmptied() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700462 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
463 if ((*node) == nullptr) {
464 return;
465 }
466 (*node)->onInputBufferEmptied();
Wonsik Kim1951d932024-05-23 22:59:00 +0000467 }
468
Wonsik Kim673dd192021-01-29 14:58:12 -0800469 android_dataspace getDataspace() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700470 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
471 if ((*node) == nullptr) {
472 return HAL_DATASPACE_UNKNOWN;
473 }
474 return (*node)->getDataspace();
Wonsik Kim673dd192021-01-29 14:58:12 -0800475 }
476
Songyue Hanad01f6a2023-08-17 05:45:35 +0000477 uint32_t getPixelFormat() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700478 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
479 if ((*node) == nullptr) {
480 return PIXEL_FORMAT_UNKNOWN;
481 }
482 return (*node)->getPixelFormat();
Songyue Hanad01f6a2023-08-17 05:45:35 +0000483 }
484
Pawin Vongmasa36653902018-11-15 00:10:25 -0800485private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700486 sp<HGraphicBufferSource> mSource;
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700487 Mutexed<sp<C2OMXNode>> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700488 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800489 uint32_t mWidth;
490 uint32_t mHeight;
491 Config mConfig;
492};
493
Sungtak Lee92bca442024-03-12 09:10:31 +0000494class AGraphicBufferSourceWrapper : public InputSurfaceWrapper {
495public:
496 AGraphicBufferSourceWrapper(
497 const std::shared_ptr<AGraphicBufferSource> &source,
498 uint32_t width,
499 uint32_t height,
500 uint64_t usage)
501 : mSource(source), mWidth(width), mHeight(height) {
502 mDataSpace = HAL_DATASPACE_BT709;
503 mConfig.mUsage = usage;
504 }
505 ~AGraphicBufferSourceWrapper() override = default;
506
507 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700508 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
509 *node = ::ndk::SharedRefBase::make<C2AidlNode>(comp);
510 (*node)->setFrameSize(mWidth, mHeight);
Sungtak Lee92bca442024-03-12 09:10:31 +0000511 // Usage is queried during configure(), so setting it beforehand.
512 uint64_t usage = mConfig.mUsage;
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700513 (void)(*node)->setConsumerUsage((int64_t)usage);
Sungtak Lee92bca442024-03-12 09:10:31 +0000514
515 return fromAidlStatus(mSource->configure(
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700516 (*node), static_cast<::aidl::android::hardware::graphics::common::Dataspace>(
Sungtak Lee92bca442024-03-12 09:10:31 +0000517 mDataSpace)));
518 }
519
520 void disconnect() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700521 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
522 if ((*node) == nullptr) {
Sungtak Lee92bca442024-03-12 09:10:31 +0000523 return;
524 }
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700525 std::shared_ptr<IAidlBufferSource> source = (*node)->getSource();
Sungtak Lee92bca442024-03-12 09:10:31 +0000526 if (source == nullptr) {
527 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
528 return;
529 }
530 (void)source->onStop();
531 (void)source->onRelease();
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700532 node->reset();
Sungtak Lee92bca442024-03-12 09:10:31 +0000533 }
534
535 status_t start() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700536 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
537 if ((*node) == nullptr) {
538 return NO_INIT;
539 }
540 std::shared_ptr<IAidlBufferSource> source = (*node)->getSource();
Sungtak Lee92bca442024-03-12 09:10:31 +0000541 if (source == nullptr) {
542 return NO_INIT;
543 }
544
545 size_t numSlots = 16;
546
547 IAidlNode::InputBufferParams param;
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700548 status_t err = fromAidlStatus((*node)->getInputBufferParams(&param));
Sungtak Lee92bca442024-03-12 09:10:31 +0000549 if (err == OK) {
550 numSlots = param.bufferCountActual;
551 }
552
553 for (size_t i = 0; i < numSlots; ++i) {
554 (void)source->onInputBufferAdded(i);
555 }
556
557 (void)source->onStart();
558 return OK;
559 }
560
561 status_t signalEndOfInputStream() override {
562 return fromAidlStatus(mSource->signalEndOfInputStream());
563 }
564
565 status_t configure(Config &config) {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700566 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
Sungtak Lee92bca442024-03-12 09:10:31 +0000567 std::stringstream status;
568 status_t err = OK;
569
570 // handle each configuration granually, in case we need to handle part of the configuration
571 // elsewhere
572
573 // TRICKY: we do not unset frame delay repeating
574 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
575 int64_t us = 1e6 / config.mMinFps + 0.5;
576 status_t res = fromAidlStatus(mSource->setRepeatPreviousFrameDelayUs(us));
577 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
578 if (res != OK) {
579 status << " (=> " << asString(res) << ")";
580 err = res;
581 }
582 mConfig.mMinFps = config.mMinFps;
583 }
584
585 // pts gap
586 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700587 if ((*node) != nullptr) {
Sungtak Lee92bca442024-03-12 09:10:31 +0000588 float gap = (config.mMinAdjustedFps > 0)
589 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
590 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
591 // float -> uint32_t is undefined if the value is negative.
592 // First convert to int32_t to ensure the expected behavior.
593 int32_t gapUs = int32_t(gap);
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700594 (void)(*node)->setAdjustTimestampGapUs(gapUs);
Sungtak Lee92bca442024-03-12 09:10:31 +0000595 }
596 }
597
598 // max fps
599 // TRICKY: we do not unset max fps to 0 unless using fixed fps
600 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
601 && config.mMaxFps != mConfig.mMaxFps) {
602 status_t res = fromAidlStatus(mSource->setMaxFps(config.mMaxFps));
603 status << " maxFps=" << config.mMaxFps;
604 if (res != OK) {
605 status << " (=> " << asString(res) << ")";
606 err = res;
607 }
608 mConfig.mMaxFps = config.mMaxFps;
609 }
610
611 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
612 status_t res = fromAidlStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
613 status << " timeOffset " << config.mTimeOffsetUs << "us";
614 if (res != OK) {
615 status << " (=> " << asString(res) << ")";
616 err = res;
617 }
618 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
619 }
620
621 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
622 status_t res =
623 fromAidlStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
624 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
625 if (res != OK) {
626 status << " (=> " << asString(res) << ")";
627 err = res;
628 }
629 mConfig.mCaptureFps = config.mCaptureFps;
630 mConfig.mCodedFps = config.mCodedFps;
631 }
632
633 if (config.mStartAtUs != mConfig.mStartAtUs
634 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
635 status_t res = fromAidlStatus(mSource->setStartTimeUs(config.mStartAtUs));
636 status << " start at " << config.mStartAtUs << "us";
637 if (res != OK) {
638 status << " (=> " << asString(res) << ")";
639 err = res;
640 }
641 mConfig.mStartAtUs = config.mStartAtUs;
642 mConfig.mStopped = config.mStopped;
643 }
644
645 // suspend-resume
646 if (config.mSuspended != mConfig.mSuspended) {
647 status_t res = fromAidlStatus(mSource->setSuspend(
648 config.mSuspended, config.mSuspendAtUs));
649 status << " " << (config.mSuspended ? "suspend" : "resume")
650 << " at " << config.mSuspendAtUs << "us";
651 if (res != OK) {
652 status << " (=> " << asString(res) << ")";
653 err = res;
654 }
655 mConfig.mSuspended = config.mSuspended;
656 mConfig.mSuspendAtUs = config.mSuspendAtUs;
657 }
658
659 if (config.mStopped != mConfig.mStopped && config.mStopped) {
660 status_t res = fromAidlStatus(mSource->setStopTimeUs(config.mStopAtUs));
661 status << " stop at " << config.mStopAtUs << "us";
662 if (res != OK) {
663 status << " (=> " << asString(res) << ")";
664 err = res;
665 } else {
666 status << " delayUs";
667 res = fromAidlStatus(mSource->getStopTimeOffsetUs(&config.mInputDelayUs));
668 if (res != OK) {
669 status << " (=> " << asString(res) << ")";
670 } else {
671 status << "=" << config.mInputDelayUs << "us";
672 }
673 mConfig.mInputDelayUs = config.mInputDelayUs;
674 }
675 mConfig.mStopAtUs = config.mStopAtUs;
676 mConfig.mStopped = config.mStopped;
677 }
678
679 // color aspects (android._color-aspects)
680
681 // consumer usage is queried earlier.
682
683 // priority
684 if (mConfig.mPriority != config.mPriority) {
685 if (config.mPriority != INT_MAX) {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700686 (*node)->setPriority(config.mPriority);
Sungtak Lee92bca442024-03-12 09:10:31 +0000687 }
688 mConfig.mPriority = config.mPriority;
689 }
690
691 if (status.str().empty()) {
692 ALOGD("ISConfig not changed");
693 } else {
694 ALOGD("ISConfig%s", status.str().c_str());
695 }
696 return err;
697 }
698
699 void onInputBufferDone(c2_cntr64_t index) override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700700 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
701 if ((*node) == nullptr) {
702 return;
703 }
704 (*node)->onInputBufferDone(index);
Sungtak Lee92bca442024-03-12 09:10:31 +0000705 }
706
Wonsik Kim1951d932024-05-23 22:59:00 +0000707 void onInputBufferEmptied() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700708 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
709 if ((*node) == nullptr) {
710 return;
711 }
712 (*node)->onInputBufferEmptied();
Wonsik Kim1951d932024-05-23 22:59:00 +0000713 }
714
Sungtak Lee92bca442024-03-12 09:10:31 +0000715 android_dataspace getDataspace() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700716 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
717 if ((*node) == nullptr) {
718 return HAL_DATASPACE_UNKNOWN;
719 }
720 return (*node)->getDataspace();
Sungtak Lee92bca442024-03-12 09:10:31 +0000721 }
722
723 uint32_t getPixelFormat() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700724 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
725 if ((*node) == nullptr) {
726 return PIXEL_FORMAT_UNKNOWN;
727 }
728 return (*node)->getPixelFormat();
Sungtak Lee92bca442024-03-12 09:10:31 +0000729 }
730
731private:
732 std::shared_ptr<AGraphicBufferSource> mSource;
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700733 Mutexed<std::shared_ptr<C2AidlNode>> mNode;
Sungtak Lee92bca442024-03-12 09:10:31 +0000734 uint32_t mWidth;
735 uint32_t mHeight;
736 Config mConfig;
737};
738
Pawin Vongmasa36653902018-11-15 00:10:25 -0800739class Codec2ClientInterfaceWrapper : public C2ComponentStore {
740 std::shared_ptr<Codec2Client> mClient;
741
742public:
743 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
744 : mClient(client) { }
745
746 virtual ~Codec2ClientInterfaceWrapper() = default;
747
748 virtual c2_status_t config_sm(
749 const std::vector<C2Param *> &params,
750 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
751 return mClient->config(params, C2_MAY_BLOCK, failures);
752 };
753
754 virtual c2_status_t copyBuffer(
755 std::shared_ptr<C2GraphicBuffer>,
756 std::shared_ptr<C2GraphicBuffer>) {
757 return C2_OMITTED;
758 }
759
760 virtual c2_status_t createComponent(
761 C2String, std::shared_ptr<C2Component> *const component) {
762 component->reset();
763 return C2_OMITTED;
764 }
765
766 virtual c2_status_t createInterface(
767 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
768 interface->reset();
769 return C2_OMITTED;
770 }
771
772 virtual c2_status_t query_sm(
773 const std::vector<C2Param *> &stackParams,
774 const std::vector<C2Param::Index> &heapParamIndices,
775 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
776 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
777 }
778
779 virtual c2_status_t querySupportedParams_nb(
780 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
781 return mClient->querySupportedParams(params);
782 }
783
784 virtual c2_status_t querySupportedValues_sm(
785 std::vector<C2FieldSupportedValuesQuery> &fields) const {
786 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
787 }
788
789 virtual C2String getName() const {
790 return mClient->getName();
791 }
792
793 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
794 return mClient->getParamReflector();
795 }
796
797 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
798 return std::vector<std::shared_ptr<const C2Component::Traits>>();
799 }
800};
801
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800802void RevertOutputFormatIfNeeded(
803 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
804 // We used to not report changes to these keys to the client.
805 const static std::set<std::string> sIgnoredKeys({
806 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800807 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800808 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800809 KEY_MAX_WIDTH,
810 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800811 "csd-0",
812 "csd-1",
813 "csd-2",
814 });
815 if (currentFormat == oldFormat) {
816 return;
817 }
818 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
819 AMessage::Type type;
820 for (size_t i = diff->countEntries(); i > 0; --i) {
821 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
822 diff->removeEntryAt(i - 1);
823 }
824 }
825 if (diff->countEntries() == 0) {
826 currentFormat = oldFormat;
827 }
828}
829
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700830void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700831 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700832 const sp<AMessage> &outputFormat) {
833 if (mediaType == MIMETYPE_VIDEO_AVC) {
834 // Codec specific data should be SPS and PPS in a single buffer,
835 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
836 // We separate the two and put them into the output format
837 // under the keys "csd-0" and "csd-1".
838
839 unsigned csdIndex = 0;
840
841 const uint8_t *nalStart;
842 size_t nalSize;
843 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
844 sp<ABuffer> csd = new ABuffer(nalSize + 4);
845 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
846 memcpy(csd->data() + 4, nalStart, nalSize);
847
848 outputFormat->setBuffer(
849 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
850
851 ++csdIndex;
852 }
853
854 if (csdIndex != 2) {
855 ALOGW("Expected two NAL units from AVC codec config, but %u found",
856 csdIndex);
857 }
858 } else {
859 // For everything else we just stash the codec specific data into
860 // the output format as a single piece of csd under "csd-0".
861 sp<ABuffer> csd = new ABuffer(size);
862 memcpy(csd->data(), data, size);
863 csd->setRange(0, size);
864 outputFormat->setBuffer("csd-0", csd);
865 }
866}
867
Pawin Vongmasa36653902018-11-15 00:10:25 -0800868} // namespace
869
870// CCodec::ClientListener
871
872struct CCodec::ClientListener : public Codec2Client::Listener {
873
874 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
875
876 virtual void onWorkDone(
877 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800878 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800879 (void)component;
880 sp<CCodec> codec(mCodec.promote());
881 if (!codec) {
882 return;
883 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800884 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800885 }
886
887 virtual void onTripped(
888 const std::weak_ptr<Codec2Client::Component>& component,
889 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
890 ) override {
891 // TODO
892 (void)component;
893 (void)settingResult;
894 }
895
896 virtual void onError(
897 const std::weak_ptr<Codec2Client::Component>& component,
898 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800899 {
900 // Component is only used for reporting as we use a separate listener for each instance
901 std::shared_ptr<Codec2Client::Component> comp = component.lock();
902 if (!comp) {
903 ALOGD("Component died with error: 0x%x", errorCode);
904 } else {
905 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
906 }
907 }
908
909 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800910 // Note: for now we do not propagate the error code to MediaCodec
911 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800912 sp<CCodec> codec(mCodec.promote());
913 if (!codec || !codec->mCallback) {
914 return;
915 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800916 codec->mCallback->onError(
917 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
918 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800919 }
920
921 virtual void onDeath(
922 const std::weak_ptr<Codec2Client::Component>& component) override {
923 { // Log the death of the component.
924 std::shared_ptr<Codec2Client::Component> comp = component.lock();
925 if (!comp) {
926 ALOGE("Codec2 component died.");
927 } else {
928 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
929 }
930 }
931
932 // Report to MediaCodec.
933 sp<CCodec> codec(mCodec.promote());
934 if (!codec || !codec->mCallback) {
935 return;
936 }
937 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
938 }
939
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800940 virtual void onFrameRendered(uint64_t bufferQueueId,
941 int32_t slotId,
942 int64_t timestampNs) override {
943 // TODO: implement
944 (void)bufferQueueId;
945 (void)slotId;
946 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800947 }
948
949 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800950 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800951 sp<CCodec> codec(mCodec.promote());
952 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800953 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800954 }
955 }
956
957private:
958 wp<CCodec> mCodec;
959};
960
961// CCodecCallbackImpl
962
963class CCodecCallbackImpl : public CCodecCallback {
964public:
965 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
966 ~CCodecCallbackImpl() override = default;
967
968 void onError(status_t err, enum ActionCode actionCode) override {
969 mCodec->mCallback->onError(err, actionCode);
970 }
971
972 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
Brian Lindahlff74e9d2023-07-20 14:44:04 -0600973 mCodec->mCallback->onOutputFramesRendered({RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
Pawin Vongmasa36653902018-11-15 00:10:25 -0800974 }
975
Pawin Vongmasa36653902018-11-15 00:10:25 -0800976 void onOutputBuffersChanged() override {
977 mCodec->mCallback->onOutputBuffersChanged();
978 }
979
Guillaume Chelfi5ffbcb32021-04-12 14:23:43 +0200980 void onFirstTunnelFrameReady() override {
981 mCodec->mCallback->onFirstTunnelFrameReady();
982 }
983
Pawin Vongmasa36653902018-11-15 00:10:25 -0800984private:
985 CCodec *mCodec;
986};
987
988// CCodec
989
990CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700991 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
992 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800993}
994
995CCodec::~CCodec() {
996}
997
998std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
999 return mChannel;
1000}
1001
1002status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
1003 status_t err = job();
1004 if (err != C2_OK) {
1005 mCallback->onError(err, ACTION_CODE_FATAL);
1006 }
1007 return err;
1008}
1009
1010void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
1011 auto setAllocating = [this] {
1012 Mutexed<State>::Locked state(mState);
1013 if (state->get() != RELEASED) {
1014 return INVALID_OPERATION;
1015 }
1016 state->set(ALLOCATING);
1017 return OK;
1018 };
1019 if (tryAndReportOnError(setAllocating) != OK) {
1020 return;
1021 }
1022
1023 sp<RefBase> codecInfo;
1024 CHECK(msg->findObject("codecInfo", &codecInfo));
1025 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
1026
1027 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
1028 allocMsg->setObject("codecInfo", codecInfo);
1029 allocMsg->post();
1030}
1031
1032void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
1033 if (codecInfo == nullptr) {
1034 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1035 return;
1036 }
1037 ALOGD("allocate(%s)", codecInfo->getCodecName());
1038 mClientListener.reset(new ClientListener(this));
1039
1040 AString componentName = codecInfo->getCodecName();
1041 std::shared_ptr<Codec2Client> client;
1042
1043 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -07001044 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001045 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001046 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001047 SetPreferredCodec2ComponentStore(
1048 std::make_shared<Codec2ClientInterfaceWrapper>(client));
1049 }
1050
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +09001051 std::shared_ptr<Codec2Client::Component> comp;
1052 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001053 componentName.c_str(),
1054 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +09001055 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001056 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +09001057 if (status != C2_OK) {
1058 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001059 Mutexed<State>::Locked state(mState);
1060 state->set(RELEASED);
1061 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +09001062 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001063 state.lock();
1064 return;
1065 }
1066 ALOGI("Created component [%s]", componentName.c_str());
1067 mChannel->setComponent(comp);
1068 auto setAllocated = [this, comp, client] {
1069 Mutexed<State>::Locked state(mState);
1070 if (state->get() != ALLOCATING) {
1071 state->set(RELEASED);
1072 return UNKNOWN_ERROR;
1073 }
1074 state->set(ALLOCATED);
1075 state->comp = comp;
1076 mClient = client;
1077 return OK;
1078 };
1079 if (tryAndReportOnError(setAllocated) != OK) {
1080 return;
1081 }
1082
1083 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001084 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1085 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001086 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001087 if (err != OK) {
1088 ALOGW("Failed to initialize configuration support");
1089 // TODO: report error once we complete implementation.
1090 }
1091 config->queryConfiguration(comp);
1092
1093 mCallback->onComponentAllocated(componentName.c_str());
1094}
1095
1096void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
1097 auto checkAllocated = [this] {
1098 Mutexed<State>::Locked state(mState);
1099 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
1100 };
1101 if (tryAndReportOnError(checkAllocated) != OK) {
1102 return;
1103 }
1104
1105 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
1106 msg->setMessage("format", format);
1107 msg->post();
1108}
1109
1110void CCodec::configure(const sp<AMessage> &msg) {
1111 std::shared_ptr<Codec2Client::Component> comp;
1112 auto checkAllocated = [this, &comp] {
1113 Mutexed<State>::Locked state(mState);
1114 if (state->get() != ALLOCATED) {
1115 state->set(RELEASED);
1116 return UNKNOWN_ERROR;
1117 }
1118 comp = state->comp;
1119 return OK;
1120 };
1121 if (tryAndReportOnError(checkAllocated) != OK) {
1122 return;
1123 }
1124
1125 auto doConfig = [msg, comp, this]() -> status_t {
1126 AString mime;
1127 if (!msg->findString("mime", &mime)) {
1128 return BAD_VALUE;
1129 }
1130
1131 int32_t encoder;
1132 if (!msg->findInt32("encoder", &encoder)) {
1133 encoder = false;
1134 }
1135
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001136 int32_t flags;
1137 if (!msg->findInt32("flags", &flags)) {
1138 return BAD_VALUE;
1139 }
1140
Pawin Vongmasa36653902018-11-15 00:10:25 -08001141 // TODO: read from intf()
1142 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
1143 return UNKNOWN_ERROR;
1144 }
1145
1146 int32_t storeMeta;
1147 if (encoder
1148 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
1149 && storeMeta != kMetadataBufferTypeInvalid) {
1150 if (storeMeta != kMetadataBufferTypeANWBuffer) {
1151 ALOGD("Only ANW buffers are supported for legacy metadata mode");
1152 return BAD_VALUE;
1153 }
1154 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
1155 }
1156
ted.sun765db4d2020-06-23 14:03:41 +08001157 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001158 sp<RefBase> obj;
1159 sp<Surface> surface;
1160 if (msg->findObject("native-window", &obj)) {
1161 surface = static_cast<Surface *>(obj.get());
Sungtak Lee214ce612023-11-01 10:01:13 +00001162 int32_t generation;
1163 (void)msg->findInt32("native-window-generation", &generation);
ted.sun765db4d2020-06-23 14:03:41 +08001164 // setup tunneled playback
1165 if (surface != nullptr) {
1166 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1167 const std::unique_ptr<Config> &config = *configLocked;
1168 if ((config->mDomain & Config::IS_DECODER)
1169 && (config->mDomain & Config::IS_VIDEO)) {
1170 int32_t tunneled;
1171 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
1172 ALOGI("Configuring TUNNELED video playback.");
1173
1174 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
1175 if (err != OK) {
1176 ALOGE("configureTunneledVideoPlayback failed!");
1177 return err;
1178 }
1179 config->mTunneled = true;
1180 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +01001181
1182 int32_t pushBlankBuffersOnStop = 0;
1183 if (msg->findInt32(KEY_PUSH_BLANK_BUFFERS_ON_STOP, &pushBlankBuffersOnStop)) {
1184 config->mPushBlankBuffersOnStop = pushBlankBuffersOnStop == 1;
1185 }
shuanglong.wang480a8362023-02-17 20:55:51 +08001186 // secure compoment or protected content default with
1187 // "push-blank-buffers-on-shutdown" flag
1188 if (!config->mPushBlankBuffersOnStop) {
1189 int32_t usageProtected;
1190 if (comp->getName().find(".secure") != std::string::npos) {
1191 config->mPushBlankBuffersOnStop = true;
1192 } else if (msg->findInt32("protected", &usageProtected) && usageProtected) {
1193 config->mPushBlankBuffersOnStop = true;
1194 }
1195 }
ted.sun765db4d2020-06-23 14:03:41 +08001196 }
1197 }
Sungtak Lee214ce612023-11-01 10:01:13 +00001198 setSurface(surface, (uint32_t)generation);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001199 }
1200
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001201 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1202 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001203 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001204 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
1205 ALOGD("[%s] buffers are %sbound to CCodec for this session",
1206 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001207
Wonsik Kim1114eea2019-02-25 14:35:24 -08001208 // Enforce required parameters
1209 int32_t i32;
1210 float flt;
1211 if (config->mDomain & Config::IS_AUDIO) {
1212 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
1213 ALOGD("sample rate is missing, which is required for audio components.");
1214 return BAD_VALUE;
1215 }
1216 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
1217 ALOGD("channel count is missing, which is required for audio components.");
1218 return BAD_VALUE;
1219 }
1220 if ((config->mDomain & Config::IS_ENCODER)
1221 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
1222 && !msg->findInt32(KEY_BIT_RATE, &i32)
1223 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
1224 ALOGD("bitrate is missing, which is required for audio encoders.");
1225 return BAD_VALUE;
1226 }
1227 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001228 int32_t width = 0;
1229 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -08001230 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001231 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -08001232 ALOGD("width is missing, which is required for image/video components.");
1233 return BAD_VALUE;
1234 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001235 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -08001236 ALOGD("height is missing, which is required for image/video components.");
1237 return BAD_VALUE;
1238 }
1239 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -07001240 int32_t mode = BITRATE_MODE_VBR;
1241 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -07001242 if (!msg->findInt32(KEY_QUALITY, &i32)) {
1243 ALOGD("quality is missing, which is required for video encoders in CQ.");
1244 return BAD_VALUE;
1245 }
1246 } else {
1247 if (!msg->findInt32(KEY_BIT_RATE, &i32)
1248 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
1249 ALOGD("bitrate is missing, which is required for video encoders.");
1250 return BAD_VALUE;
1251 }
Wonsik Kim1114eea2019-02-25 14:35:24 -08001252 }
1253 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
1254 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
1255 ALOGD("I frame interval is missing, which is required for video encoders.");
1256 return BAD_VALUE;
1257 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001258 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
1259 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
1260 ALOGD("frame rate is missing, which is required for video encoders.");
1261 return BAD_VALUE;
1262 }
Wonsik Kim1114eea2019-02-25 14:35:24 -08001263 }
1264 }
1265
Pawin Vongmasa36653902018-11-15 00:10:25 -08001266 /*
1267 * Handle input surface configuration
1268 */
1269 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1270 && (config->mDomain & Config::IS_ENCODER)) {
1271 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
1272 {
1273 config->mISConfig->mMinFps = 0;
1274 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001275 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001276 config->mISConfig->mMinFps = 1e6 / value;
1277 }
Wonsik Kim95ba0162019-03-19 15:51:54 -07001278 if (!msg->findFloat(
1279 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
1280 config->mISConfig->mMaxFps = -1;
1281 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001282 config->mISConfig->mMinAdjustedFps = 0;
1283 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -08001284 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001285 if (value < 0 && value >= INT32_MIN) {
1286 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001287 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001288 } else if (value > 0 && value <= INT32_MAX) {
1289 config->mISConfig->mMinAdjustedFps = 1e6 / value;
1290 }
1291 }
1292 }
1293
1294 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -07001295 bool captureFpsFound = false;
1296 double timeLapseFps;
1297 float captureRate;
1298 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
1299 config->mISConfig->mCaptureFps = timeLapseFps;
1300 captureFpsFound = true;
1301 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
1302 config->mISConfig->mCaptureFps = captureRate;
1303 captureFpsFound = true;
1304 }
1305 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001306 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
1307 }
1308 }
1309
1310 {
1311 config->mISConfig->mSuspended = false;
1312 config->mISConfig->mSuspendAtUs = -1;
1313 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001314 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001315 config->mISConfig->mSuspended = true;
1316 }
1317 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001318 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -07001319 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001320 }
1321
1322 /*
1323 * Handle desired color format.
1324 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001325 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001326 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001327 int32_t format = 0;
1328 // Query vendor format for Flexible YUV
1329 std::vector<std::unique_ptr<C2Param>> heapParams;
1330 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
Wonsik Kim50811882022-04-28 15:57:27 -07001331 int vendorSdkVersion = base::GetIntProperty(
1332 "ro.vendor.build.version.sdk", android_get_device_api_level());
guochuang709b48b2022-10-25 20:40:42 +08001333 if (mClient->query(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001334 {},
1335 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1336 C2_MAY_BLOCK,
1337 &heapParams) == C2_OK
1338 && heapParams.size() == 1u) {
1339 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1340 heapParams[0].get());
1341 } else {
1342 pixelFormatInfo = nullptr;
1343 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001344 // bit depth -> format
1345 std::map<uint32_t, uint32_t> flexPixelFormat;
1346 std::map<uint32_t, uint32_t> flexPlanarPixelFormat;
1347 std::map<uint32_t, uint32_t> flexSemiPlanarPixelFormat;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001348 if (pixelFormatInfo && *pixelFormatInfo) {
1349 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1350 const C2FlexiblePixelFormatDescriptorStruct &desc =
1351 pixelFormatInfo->m.values[i];
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001352 if (desc.subsampling != C2Color::YUV_420
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001353 // TODO(b/180076105): some device report wrong layout
1354 // || desc.layout == C2Color::INTERLEAVED_PACKED
1355 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1356 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1357 continue;
1358 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001359 if (flexPixelFormat.count(desc.bitDepth) == 0) {
1360 flexPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001361 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001362 if (desc.layout == C2Color::PLANAR_PACKED
1363 && flexPlanarPixelFormat.count(desc.bitDepth) == 0) {
1364 flexPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001365 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001366 if (desc.layout == C2Color::SEMIPLANAR_PACKED
1367 && flexSemiPlanarPixelFormat.count(desc.bitDepth) == 0) {
1368 flexSemiPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001369 }
1370 }
1371 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001372 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001373 // Also handle default color format (encoders require color format, so this is only
1374 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001375 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001376 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001377 const char *prefix = "";
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001378 if (flexSemiPlanarPixelFormat.count(8) != 0) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001379 format = COLOR_FormatYUV420SemiPlanar;
1380 prefix = "semi-";
1381 } else {
1382 format = COLOR_FormatYUV420Planar;
1383 }
1384 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1385 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001386 } else {
1387 format = COLOR_FormatSurface;
1388 }
1389 defaultColorFormat = format;
1390 }
1391 } else {
1392 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001393 if (vendorSdkVersion < __ANDROID_API_S__ &&
Taehwan Kim43e715d2022-09-22 12:04:59 +09001394 (format == COLOR_FormatYUV420Planar ||
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001395 format == COLOR_FormatYUV420PackedPlanar ||
1396 format == COLOR_FormatYUV420SemiPlanar ||
1397 format == COLOR_FormatYUV420PackedSemiPlanar)) {
1398 // pre-S framework used to map these color formats into YV12.
1399 // Codecs from older vendor partition may be relying on
1400 // this assumption.
1401 format = HAL_PIXEL_FORMAT_YV12;
1402 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001403 switch (format) {
1404 case COLOR_FormatYUV420Flexible:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001405 format = COLOR_FormatYUV420Planar;
1406 if (flexPixelFormat.count(8) != 0) {
1407 format = flexPixelFormat[8];
1408 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001409 break;
1410 case COLOR_FormatYUV420Planar:
1411 case COLOR_FormatYUV420PackedPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001412 if (flexPlanarPixelFormat.count(8) != 0) {
1413 format = flexPlanarPixelFormat[8];
1414 } else if (flexPixelFormat.count(8) != 0) {
1415 format = flexPixelFormat[8];
1416 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001417 break;
1418 case COLOR_FormatYUV420SemiPlanar:
1419 case COLOR_FormatYUV420PackedSemiPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001420 if (flexSemiPlanarPixelFormat.count(8) != 0) {
1421 format = flexSemiPlanarPixelFormat[8];
1422 } else if (flexPixelFormat.count(8) != 0) {
1423 format = flexPixelFormat[8];
1424 }
1425 break;
1426 case COLOR_FormatYUVP010:
1427 format = COLOR_FormatYUVP010;
1428 if (flexSemiPlanarPixelFormat.count(10) != 0) {
1429 format = flexSemiPlanarPixelFormat[10];
1430 } else if (flexPixelFormat.count(10) != 0) {
1431 format = flexPixelFormat[10];
1432 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001433 break;
1434 default:
1435 // No-op
1436 break;
1437 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001438 }
1439 }
1440
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001441 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001442 msg->setInt32("android._color-format", format);
1443 }
1444 }
1445
Wonsik Kim77e97c72021-01-20 10:33:22 -08001446 /*
1447 * Handle dataspace
1448 */
1449 int32_t usingRecorder;
1450 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1451 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1452 int32_t width, height;
1453 if (msg->findInt32("width", &width)
1454 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001455 ColorAspects aspects;
1456 getColorAspectsFromFormat(msg, aspects);
1457 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001458 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001459 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1460 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001461 }
1462 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1463 ALOGD("setting dataspace to %x", dataSpace);
1464 }
1465
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001466 int32_t subscribeToAllVendorParams;
1467 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1468 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1469 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1470 }
1471 }
1472
Ram Mohan16511072023-12-11 19:41:31 +05301473 /*
1474 * configure mock region of interest if Feature_Roi is enabled
1475 */
1476 if (android::media::codec::provider_->region_of_interest()
1477 && android::media::codec::provider_->region_of_interest_support()) {
1478 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
1479 int32_t enableRoi;
1480 if (msg->findInt32("feature-region-of-interest", &enableRoi) && enableRoi != 0) {
1481 if (!msg->contains(PARAMETER_KEY_QP_OFFSET_MAP) &&
1482 !msg->contains(PARAMETER_KEY_QP_OFFSET_RECTS)) {
1483 msg->setString(PARAMETER_KEY_QP_OFFSET_RECTS,
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05301484 AStringPrintf("%d,%d-%d,%d=%d;", 0, 0, height, width, 0));
Ram Mohan16511072023-12-11 19:41:31 +05301485 }
1486 }
1487 }
1488 }
1489
Pawin Vongmasa36653902018-11-15 00:10:25 -08001490 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001491 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1492 // the behavior here.
1493 sp<AMessage> sdkParams = msg;
1494 int32_t videoBitrate;
1495 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1496 sdkParams = msg->dup();
1497 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1498 }
ted.sun765db4d2020-06-23 14:03:41 +08001499 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001500 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001501 if (err != OK) {
1502 ALOGW("failed to convert configuration to c2 params");
1503 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001504
1505 int32_t maxBframes = 0;
1506 if ((config->mDomain & Config::IS_ENCODER)
1507 && (config->mDomain & Config::IS_VIDEO)
1508 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1509 && maxBframes > 0) {
1510 std::unique_ptr<C2StreamGopTuning::output> gop =
1511 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1512 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1513 gop->m.values[1] = {
1514 C2Config::picture_type_t(P_FRAME | B_FRAME),
1515 uint32_t(maxBframes)
1516 };
1517 configUpdate.push_back(std::move(gop));
1518 }
1519
Ray Essicka0ae6972021-03-10 19:40:01 -08001520 if ((config->mDomain & Config::IS_ENCODER)
1521 && (config->mDomain & Config::IS_VIDEO)) {
1522 // we may not use all 3 of these entries
1523 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1524 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1525 0u /* stream */);
1526
1527 int ix = 0;
1528
1529 int32_t iMax = INT32_MAX;
1530 int32_t iMin = INT32_MIN;
1531 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1532 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1533 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1534 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1535 }
1536
1537 int32_t pMax = INT32_MAX;
1538 int32_t pMin = INT32_MIN;
1539 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1540 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1541 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1542 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1543 }
1544
1545 int32_t bMax = INT32_MAX;
1546 int32_t bMin = INT32_MIN;
1547 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1548 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1549 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1550 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1551 }
1552
1553 // adjust to reflect actual use.
1554 qp->setFlexCount(ix);
1555
1556 configUpdate.push_back(std::move(qp));
1557 }
1558
Wonsik Kima1335e12021-04-22 16:28:29 -07001559 int32_t background = 0;
1560 if ((config->mDomain & Config::IS_VIDEO)
1561 && msg->findInt32("android._background-mode", &background)
1562 && background) {
1563 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1564 if (config->mISConfig) {
1565 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1566 }
1567 }
1568
Pawin Vongmasa36653902018-11-15 00:10:25 -08001569 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1570 if (err != OK) {
1571 ALOGW("failed to configure c2 params");
1572 return err;
1573 }
1574
1575 std::vector<std::unique_ptr<C2Param>> params;
1576 C2StreamUsageTuning::input usage(0u, 0u);
1577 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001578 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001579
Wonsik Kim3baecda2021-02-07 22:19:56 -08001580 C2Param::Index colorAspectsRequestIndex =
1581 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001582 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001583 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001584 };
Chaejung Lim86c22dc2021-12-23 00:41:05 -08001585 int32_t colorTransferRequest = 0;
1586 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1587 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1588 colorTransferRequest = 0;
1589 }
1590 c2_status_t c2err = C2_OK;
1591 if (colorTransferRequest != 0) {
1592 c2err = comp->query(
1593 { &usage, &maxInputSize, &prepend },
1594 indices,
1595 C2_DONT_BLOCK,
1596 &params);
1597 } else {
1598 c2err = comp->query(
1599 { &usage, &maxInputSize, &prepend },
1600 {},
1601 C2_DONT_BLOCK,
1602 &params);
1603 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001604 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1605 ALOGE("Failed to query component interface: %d", c2err);
1606 return UNKNOWN_ERROR;
1607 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001608 if (usage) {
1609 if (usage.value & C2MemoryUsage::CPU_READ) {
1610 config->mInputFormat->setInt32("using-sw-read-often", true);
1611 }
1612 if (config->mISConfig) {
1613 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1614 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1615 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001616 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001617 }
1618
1619 // NOTE: we don't blindly use client specified input size if specified as clients
1620 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1621 // client specified size is only used to ask for bigger buffers than component suggested
1622 // size.
1623 int32_t clientInputSize = 0;
1624 bool clientSpecifiedInputSize =
1625 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1626 // TEMP: enforce minimum buffer size of 1MB for video decoders
1627 // and 16K / 4K for audio encoders/decoders
1628 if (maxInputSize.value == 0) {
1629 if (config->mDomain & Config::IS_AUDIO) {
1630 maxInputSize.value = encoder ? 16384 : 4096;
1631 } else if (!encoder) {
1632 maxInputSize.value = 1048576u;
1633 }
1634 }
1635
1636 // verify that CSD fits into this size (if defined)
1637 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1638 sp<ABuffer> csd;
1639 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1640 if (csd && csd->size() > maxInputSize.value) {
1641 maxInputSize.value = csd->size();
1642 }
1643 }
1644 }
1645
1646 // TODO: do this based on component requiring linear allocator for input
1647 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1648 if (clientSpecifiedInputSize) {
1649 // Warn that we're overriding client's max input size if necessary.
1650 if ((uint32_t)clientInputSize < maxInputSize.value) {
1651 ALOGD("client requested max input size %d, which is smaller than "
1652 "what component recommended (%u); overriding with component "
1653 "recommendation.", clientInputSize, maxInputSize.value);
1654 ALOGW("This behavior is subject to change. It is recommended that "
1655 "app developers double check whether the requested "
1656 "max input size is in reasonable range.");
1657 } else {
1658 maxInputSize.value = clientInputSize;
1659 }
1660 }
1661 // Pass max input size on input format to the buffer channel (if supplied by the
1662 // component or by a default)
1663 if (maxInputSize.value) {
1664 config->mInputFormat->setInt32(
1665 KEY_MAX_INPUT_SIZE,
1666 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1667 }
1668 }
1669
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001670 int32_t clientPrepend;
1671 if ((config->mDomain & Config::IS_VIDEO)
1672 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001673 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001674 && clientPrepend
1675 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001676 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001677 return BAD_VALUE;
1678 }
1679
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001680 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001681 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1682 // propagate HDR static info to output format for both encoders and decoders
1683 // if component supports this info, we will update from component, but only the raw port,
1684 // so don't propagate if component already filled it in.
1685 sp<ABuffer> hdrInfo;
1686 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1687 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1688 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1689 }
1690
1691 // Set desired color format from configuration parameter
1692 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001693 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1694 format = defaultColorFormat;
1695 }
1696 if (config->mDomain & Config::IS_ENCODER) {
1697 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001698 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1699 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001700 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001701 } else {
1702 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001703 }
1704 }
1705
1706 // propagate encoder delay and padding to output format
1707 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1708 int delay = 0;
1709 if (msg->findInt32("encoder-delay", &delay)) {
1710 config->mOutputFormat->setInt32("encoder-delay", delay);
1711 }
1712 int padding = 0;
1713 if (msg->findInt32("encoder-padding", &padding)) {
1714 config->mOutputFormat->setInt32("encoder-padding", padding);
1715 }
1716 }
1717
Pawin Vongmasa36653902018-11-15 00:10:25 -08001718 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001719 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001720 int32_t mask;
1721 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1722 if (config->mDomain & Config::IS_ENCODER) {
1723 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1724 } else {
1725 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1726 }
1727 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001728
1729 // set PCM encoding
1730 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1731 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1732 if (encoder) {
1733 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1734 } else {
1735 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1736 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001737 }
1738
Wonsik Kim3baecda2021-02-07 22:19:56 -08001739 std::unique_ptr<C2Param> colorTransferRequestParam;
1740 for (std::unique_ptr<C2Param> &param : params) {
1741 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1742 ALOGI("found color transfer request param");
1743 colorTransferRequestParam = std::move(param);
1744 }
1745 }
Wonsik Kim3baecda2021-02-07 22:19:56 -08001746
1747 if (colorTransferRequest != 0) {
1748 if (colorTransferRequestParam && *colorTransferRequestParam) {
1749 C2StreamColorAspectsInfo::output *info =
1750 static_cast<C2StreamColorAspectsInfo::output *>(
1751 colorTransferRequestParam.get());
1752 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1753 colorTransferRequest = 0;
1754 }
1755 } else {
1756 colorTransferRequest = 0;
1757 }
1758 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1759 }
1760
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001761 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1762 // Need to get stride/vstride
1763 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1764 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1765 // TODO: retrieve these values without allocating a buffer.
1766 // Currently allocating a buffer is necessary to retrieve the layout.
1767 int64_t blockUsage =
1768 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1769 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
Harish Mahendrakarf6b3e5e2024-03-21 21:04:28 +00001770 align(width, 2), align(height, 2), componentColorFormat, blockUsage,
1771 {comp->getName()});
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001772 sp<GraphicBlockBuffer> buffer;
1773 if (block) {
1774 buffer = GraphicBlockBuffer::Allocate(
1775 config->mInputFormat,
1776 block,
1777 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1778 } else {
1779 ALOGD("Failed to allocate a graphic block "
1780 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1781 width, height, pixelFormat, (long long)blockUsage);
1782 // This means that byte buffer mode is not supported in this configuration
1783 // anyway. Skip setting stride/vstride to input format.
1784 }
1785 if (buffer) {
1786 sp<ABuffer> imageData = buffer->getImageData();
1787 MediaImage2 *img = nullptr;
1788 if (imageData && imageData->data()
1789 && imageData->size() >= sizeof(MediaImage2)) {
1790 img = (MediaImage2*)imageData->data();
1791 }
1792 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1793 int32_t stride = img->mPlane[0].mRowInc;
1794 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1795 if (img->mNumPlanes > 1 && stride > 0) {
1796 int64_t offsetDelta =
1797 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1798 if (offsetDelta % stride == 0) {
1799 int32_t vstride = int32_t(offsetDelta / stride);
1800 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1801 } else {
1802 ALOGD("Cannot report accurate slice height: "
1803 "offsetDelta = %lld stride = %d",
1804 (long long)offsetDelta, stride);
1805 }
1806 }
1807 }
1808 }
1809 }
1810 }
1811
Wonsik Kimec585c32021-10-01 01:11:00 -07001812 if (config->mTunneled) {
1813 config->mOutputFormat->setInt32("android._tunneled", 1);
1814 }
1815
Yushin Cho91873b52021-12-21 04:08:35 -08001816 // Convert an encoding statistics level to corresponding encoding statistics
1817 // kinds
1818 int32_t encodingStatisticsLevel = VIDEO_ENCODING_STATISTICS_LEVEL_NONE;
1819 if ((config->mDomain & Config::IS_ENCODER)
1820 && (config->mDomain & Config::IS_VIDEO)
1821 && msg->findInt32(KEY_VIDEO_ENCODING_STATISTICS_LEVEL, &encodingStatisticsLevel)) {
1822 // Higher level include all the enc stats belong to lower level.
1823 switch (encodingStatisticsLevel) {
1824 // case VIDEO_ENCODING_STATISTICS_LEVEL_2: // reserved for the future level 2
1825 // with more enc stat kinds
1826 // Future extended encoding statistics for the level 2 should be added here
1827 case VIDEO_ENCODING_STATISTICS_LEVEL_1:
Wonsik Kimeebab652022-06-02 13:01:55 -07001828 config->subscribeToConfigUpdate(
1829 comp,
1830 {
1831 C2AndroidStreamAverageBlockQuantizationInfo::output::PARAM_TYPE,
1832 C2StreamPictureTypeInfo::output::PARAM_TYPE,
1833 });
Yushin Cho91873b52021-12-21 04:08:35 -08001834 break;
1835 case VIDEO_ENCODING_STATISTICS_LEVEL_NONE:
1836 break;
1837 }
1838 }
1839 ALOGD("encoding statistics level = %d", encodingStatisticsLevel);
1840
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001841 ALOGD("setup formats input: %s",
1842 config->mInputFormat->debugString().c_str());
1843 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001844 config->mOutputFormat->debugString().c_str());
1845 return OK;
1846 };
1847 if (tryAndReportOnError(doConfig) != OK) {
1848 return;
1849 }
1850
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001851 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1852 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001853
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001854 config->queryConfiguration(comp);
1855
Songyue Han1e6769b2023-08-30 18:09:27 +00001856 mMetrics = new AMessage;
1857 mChannel->resetBuffersPixelFormat((config->mDomain & Config::IS_ENCODER) ? true : false);
1858
Pawin Vongmasa36653902018-11-15 00:10:25 -08001859 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1860}
1861
1862void CCodec::initiateCreateInputSurface() {
1863 status_t err = [this] {
1864 Mutexed<State>::Locked state(mState);
1865 if (state->get() != ALLOCATED) {
1866 return UNKNOWN_ERROR;
1867 }
1868 // TODO: read it from intf() properly.
1869 if (state->comp->getName().find("encoder") == std::string::npos) {
1870 return INVALID_OPERATION;
1871 }
1872 return OK;
1873 }();
1874 if (err != OK) {
1875 mCallback->onInputSurfaceCreationFailed(err);
1876 return;
1877 }
1878
1879 (new AMessage(kWhatCreateInputSurface, this))->post();
1880}
1881
Lajos Molnar47118272019-01-31 16:28:04 -08001882sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1883 using namespace android::hardware::media::omx::V1_0;
1884 using namespace android::hardware::media::omx::V1_0::utils;
1885 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1886 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1887 android::sp<IOmx> omx = IOmx::getService();
Sungtak Lee47dcb482022-04-15 10:47:08 -07001888 if (omx == nullptr) {
1889 return nullptr;
1890 }
Lajos Molnar47118272019-01-31 16:28:04 -08001891 typedef android::hardware::graphics::bufferqueue::V1_0::
1892 IGraphicBufferProducer HGraphicBufferProducer;
1893 typedef android::hardware::media::omx::V1_0::
1894 IGraphicBufferSource HGraphicBufferSource;
1895 OmxStatus s;
1896 android::sp<HGraphicBufferProducer> gbp;
1897 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001898
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001899 using ::android::hardware::Return;
1900 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001901 [&s, &gbp, &gbs](
1902 OmxStatus status,
1903 const android::sp<HGraphicBufferProducer>& producer,
1904 const android::sp<HGraphicBufferSource>& source) {
1905 s = status;
1906 gbp = producer;
1907 gbs = source;
1908 });
1909 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001910 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001911 }
1912
1913 return nullptr;
1914}
1915
1916sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1917 sp<PersistentSurface> surface(CreateInputSurface());
1918
1919 if (surface == nullptr) {
1920 surface = CreateOmxInputSurface();
1921 }
1922
1923 return surface;
1924}
1925
Pawin Vongmasa36653902018-11-15 00:10:25 -08001926void CCodec::createInputSurface() {
1927 status_t err;
1928 sp<IGraphicBufferProducer> bufferProducer;
1929
Pawin Vongmasa36653902018-11-15 00:10:25 -08001930 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001931 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001932 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001933 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1934 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001935 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001936 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001937 }
1938
Lajos Molnar47118272019-01-31 16:28:04 -08001939 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Sungtak Lee92bca442024-03-12 09:10:31 +00001940 if (persistentSurface->isTargetAidl()) {
1941 ::ndk::SpAIBinder aidlTarget = persistentSurface->getAidlTarget();
1942 std::shared_ptr<AGraphicBufferSource> gbs = AGraphicBufferSource::fromBinder(aidlTarget);
1943 if (gbs) {
1944 int32_t width = 0;
1945 (void)outputFormat->findInt32("width", &width);
1946 int32_t height = 0;
1947 (void)outputFormat->findInt32("height", &height);
1948 err = setupInputSurface(std::make_shared<AGraphicBufferSourceWrapper>(
1949 gbs, width, height, usage));
1950 bufferProducer = persistentSurface->getBufferProducer();
1951 } else {
1952 ALOGE("Corrupted input surface(aidl)");
1953 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1954 return;
1955 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001956 } else {
Sungtak Lee92bca442024-03-12 09:10:31 +00001957 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1958 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1959 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1960
1961 if (hidlInputSurface) {
1962 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1963 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
1964 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1965 inputSurface));
1966 bufferProducer = inputSurface->getGraphicBufferProducer();
1967 } else if (gbs) {
1968 int32_t width = 0;
1969 (void)outputFormat->findInt32("width", &width);
1970 int32_t height = 0;
1971 (void)outputFormat->findInt32("height", &height);
1972 err = setupInputSurface(std::make_shared<HGraphicBufferSourceWrapper>(
1973 gbs, width, height, usage));
1974 bufferProducer = persistentSurface->getBufferProducer();
1975 } else {
1976 ALOGE("Corrupted input surface");
1977 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1978 return;
1979 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001980 }
1981
1982 if (err != OK) {
1983 ALOGE("Failed to set up input surface: %d", err);
1984 mCallback->onInputSurfaceCreationFailed(err);
1985 return;
1986 }
1987
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001988 // Formats can change after setupInputSurface
1989 sp<AMessage> inputFormat;
1990 {
1991 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1992 const std::unique_ptr<Config> &config = *configLocked;
1993 inputFormat = config->mInputFormat;
1994 outputFormat = config->mOutputFormat;
1995 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001996 mCallback->onInputSurfaceCreated(
1997 inputFormat,
1998 outputFormat,
1999 new BufferProducerWrapper(bufferProducer));
2000}
2001
2002status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002003 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2004 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002005 config->mUsingSurface = true;
2006
2007 // we are now using surface - apply default color aspects to input format - as well as
2008 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002009 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002010
2011 // configure dataspace
2012 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
Wonsik Kim66b19552021-08-02 16:07:49 -07002013
2014 // The output format contains app-configured color aspects, and the input format
2015 // has the default color aspects. Use the default for the unspecified params.
2016 ColorAspects inputColorAspects, colorAspects;
2017 getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
2018 getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
2019 if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
2020 colorAspects.mRange = inputColorAspects.mRange;
2021 }
2022 if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
2023 colorAspects.mPrimaries = inputColorAspects.mPrimaries;
2024 }
2025 if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
2026 colorAspects.mTransfer = inputColorAspects.mTransfer;
2027 }
2028 if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
2029 colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
2030 }
2031 android_dataspace dataSpace = getDataSpaceForColorAspects(
2032 colorAspects, /* mayExtend = */ false);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002033 surface->setDataSpace(dataSpace);
Wonsik Kim66b19552021-08-02 16:07:49 -07002034 setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
2035 config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
2036
2037 ALOGD("input format %s to %s",
2038 inputFormatChanged ? "changed" : "unchanged",
2039 config->mInputFormat->debugString().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002040
2041 status_t err = mChannel->setInputSurface(surface);
2042 if (err != OK) {
2043 // undo input format update
2044 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002045 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002046 return err;
2047 }
2048 config->mInputSurface = surface;
2049
2050 if (config->mISConfig) {
2051 surface->configure(*config->mISConfig);
2052 } else {
2053 ALOGD("ISConfig: no configuration");
2054 }
2055
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002056 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002057}
2058
2059void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
2060 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
2061 msg->setObject("surface", surface);
2062 msg->post();
2063}
2064
2065void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002066 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07002067 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002068 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002069 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2070 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002071 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07002072 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002073 }
Sungtak Lee92bca442024-03-12 09:10:31 +00002074 if (surface->isTargetAidl()) {
2075 ::ndk::SpAIBinder aidlTarget = surface->getAidlTarget();
2076 std::shared_ptr<AGraphicBufferSource> gbs = AGraphicBufferSource::fromBinder(aidlTarget);
2077 if (gbs) {
2078 int32_t width = 0;
2079 (void)outputFormat->findInt32("width", &width);
2080 int32_t height = 0;
2081 (void)outputFormat->findInt32("height", &height);
2082
2083 status_t err = setupInputSurface(std::make_shared<AGraphicBufferSourceWrapper>(
2084 gbs, width, height, usage));
2085 if (err != OK) {
2086 ALOGE("Failed to set up input surface(aidl): %d", err);
2087 mCallback->onInputSurfaceDeclined(err);
2088 return;
2089 }
2090 } else {
2091 ALOGE("Failed to set input surface(aidl): Corrupted surface.");
2092 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002093 return;
2094 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002095 } else {
Sungtak Lee92bca442024-03-12 09:10:31 +00002096 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
2097 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
2098 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
2099 if (inputSurface) {
2100 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
2101 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
2102 if (err != OK) {
2103 ALOGE("Failed to set up input surface: %d", err);
2104 mCallback->onInputSurfaceDeclined(err);
2105 return;
2106 }
2107 } else if (gbs) {
2108 int32_t width = 0;
2109 (void)outputFormat->findInt32("width", &width);
2110 int32_t height = 0;
2111 (void)outputFormat->findInt32("height", &height);
2112 status_t err = setupInputSurface(std::make_shared<HGraphicBufferSourceWrapper>(
2113 gbs, width, height, usage));
2114 if (err != OK) {
2115 ALOGE("Failed to set up input surface: %d", err);
2116 mCallback->onInputSurfaceDeclined(err);
2117 return;
2118 }
2119 } else {
2120 ALOGE("Failed to set input surface: Corrupted surface.");
2121 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
2122 return;
2123 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002124 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07002125 // Formats can change after setupInputSurface
2126 sp<AMessage> inputFormat;
2127 {
2128 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2129 const std::unique_ptr<Config> &config = *configLocked;
2130 inputFormat = config->mInputFormat;
2131 outputFormat = config->mOutputFormat;
2132 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002133 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
2134}
2135
2136void CCodec::initiateStart() {
2137 auto setStarting = [this] {
2138 Mutexed<State>::Locked state(mState);
2139 if (state->get() != ALLOCATED) {
2140 return UNKNOWN_ERROR;
2141 }
2142 state->set(STARTING);
2143 return OK;
2144 };
2145 if (tryAndReportOnError(setStarting) != OK) {
2146 return;
2147 }
2148
2149 (new AMessage(kWhatStart, this))->post();
2150}
2151
2152void CCodec::start() {
2153 std::shared_ptr<Codec2Client::Component> comp;
2154 auto checkStarting = [this, &comp] {
2155 Mutexed<State>::Locked state(mState);
2156 if (state->get() != STARTING) {
2157 return UNKNOWN_ERROR;
2158 }
2159 comp = state->comp;
2160 return OK;
2161 };
2162 if (tryAndReportOnError(checkStarting) != OK) {
2163 return;
2164 }
2165
2166 c2_status_t err = comp->start();
2167 if (err != C2_OK) {
2168 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
2169 ACTION_CODE_FATAL);
2170 return;
2171 }
Wonsik Kimd55ed3b2023-06-22 14:42:17 -07002172
2173 // clear the deadline after the component starts
2174 setDeadline(TimePoint::max(), 0ms, "none");
2175
Pawin Vongmasa36653902018-11-15 00:10:25 -08002176 sp<AMessage> inputFormat;
2177 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002178 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002179 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002180 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002181 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2182 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002183 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08002184 // start triggers format dup
2185 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002186 if (config->mInputSurface) {
2187 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08002188 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002189 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002190 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002191 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002192 if (err2 != OK) {
2193 mCallback->onError(err2, ACTION_CODE_FATAL);
2194 return;
2195 }
Arun Johnson106fe7a2023-04-26 17:49:43 +00002196
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002197 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002198 if (err2 != OK) {
2199 mCallback->onError(err2, ACTION_CODE_FATAL);
2200 return;
2201 }
2202
2203 auto setRunning = [this] {
2204 Mutexed<State>::Locked state(mState);
2205 if (state->get() != STARTING) {
2206 return UNKNOWN_ERROR;
2207 }
2208 state->set(RUNNING);
2209 return OK;
2210 };
2211 if (tryAndReportOnError(setRunning) != OK) {
2212 return;
2213 }
Arun Johnson5997bb02022-04-01 19:35:44 +00002214
Wonsik Kim34b28b42022-05-20 15:49:32 -07002215 // preparation of input buffers may not succeed due to the lack of
2216 // memory; returning correct error code (NO_MEMORY) as an error allows
2217 // MediaCodec to try reclaim and restart codec gracefully.
2218 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
2219 err2 = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
2220 if (err2 != OK) {
2221 ALOGE("Initial preparation for Input Buffers failed");
2222 mCallback->onError(err2, ACTION_CODE_FATAL);
2223 return;
2224 }
2225
Pawin Vongmasa36653902018-11-15 00:10:25 -08002226 mCallback->onStartCompleted();
2227
Wonsik Kim34b28b42022-05-20 15:49:32 -07002228 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002229}
2230
2231void CCodec::initiateShutdown(bool keepComponentAllocated) {
2232 if (keepComponentAllocated) {
2233 initiateStop();
2234 } else {
2235 initiateRelease();
2236 }
2237}
2238
2239void CCodec::initiateStop() {
2240 {
2241 Mutexed<State>::Locked state(mState);
2242 if (state->get() == ALLOCATED
2243 || state->get() == RELEASED
2244 || state->get() == STOPPING
2245 || state->get() == RELEASING) {
2246 // We're already stopped, released, or doing it right now.
2247 state.unlock();
2248 mCallback->onStopCompleted();
2249 state.lock();
2250 return;
2251 }
2252 state->set(STOPPING);
2253 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002254 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00002255 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
2256 sp<AMessage> stopMessage(new AMessage(kWhatStop, this));
2257 stopMessage->setInt32("pushBlankBuffer", pushBlankBuffer);
2258 stopMessage->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002259}
2260
Sungtak Lee99144332023-01-26 11:03:14 +00002261void CCodec::stop(bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002262 std::shared_ptr<Codec2Client::Component> comp;
2263 {
2264 Mutexed<State>::Locked state(mState);
2265 if (state->get() == RELEASING) {
2266 state.unlock();
2267 // We're already stopped or release is in progress.
2268 mCallback->onStopCompleted();
2269 state.lock();
2270 return;
2271 } else if (state->get() != STOPPING) {
2272 state.unlock();
2273 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2274 state.lock();
2275 return;
2276 }
2277 comp = state->comp;
2278 }
Sungtak Leec0c05962023-10-25 08:14:13 +00002279
2280 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->stop().
2281 // But in the case some HAL implementations hang forever on comp->stop().
2282 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
2283 // completing stop()).
2284 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
2285 // prior to comp->stop().
2286 // See also b/300350761.
Sungtak Lee34402ae2024-05-07 19:51:28 +00002287 //
2288 // The workaround is no longer needed with fetchGraphicBlock & C2Fence changes.
Sungtak Leeb7b1cf42024-05-14 22:45:35 +00002289 // so we are reverting back to the logical sequence of the operations when
2290 // AIDL HALs are selected.
2291 // When the HIDL HALs are selected, we retained workaround(the reversed
2292 // order) as default in order to keep legacy behavior.
2293 bool stopHalBeforeSurface =
2294 Codec2Client::IsAidlSelected() ||
2295 property_get_bool("debug.codec2.stop_hal_before_surface", false);
Sungtak Lee34402ae2024-05-07 19:51:28 +00002296 status_t err = C2_OK;
Sungtak Leeb7b1cf42024-05-14 22:45:35 +00002297 if (stopHalBeforeSurface && android::media::codec::provider_->stop_hal_before_surface()) {
Sungtak Lee34402ae2024-05-07 19:51:28 +00002298 err = comp->stop();
2299 mChannel->stopUseOutputSurface(pushBlankBuffer);
2300 } else {
2301 mChannel->stopUseOutputSurface(pushBlankBuffer);
2302 err = comp->stop();
2303 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002304 if (err != C2_OK) {
2305 // TODO: convert err into status_t
2306 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2307 }
2308
2309 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002310 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2311 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002312 if (config->mInputSurface) {
2313 config->mInputSurface->disconnect();
2314 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08002315 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002316 }
2317 }
2318 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002319 Mutexed<State>::Locked state(mState);
2320 if (state->get() == STOPPING) {
2321 state->set(ALLOCATED);
2322 }
2323 }
2324 mCallback->onStopCompleted();
2325}
2326
2327void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002328 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002329 {
2330 Mutexed<State>::Locked state(mState);
2331 if (state->get() == RELEASED || state->get() == RELEASING) {
2332 // We're already released or doing it right now.
2333 if (sendCallback) {
2334 state.unlock();
2335 mCallback->onReleaseCompleted();
2336 state.lock();
2337 }
2338 return;
2339 }
2340 if (state->get() == ALLOCATING) {
2341 state->set(RELEASING);
2342 // With the altered state allocate() would fail and clean up.
2343 if (sendCallback) {
2344 state.unlock();
2345 mCallback->onReleaseCompleted();
2346 state.lock();
2347 }
2348 return;
2349 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002350 if (state->get() == STARTING
2351 || state->get() == RUNNING
2352 || state->get() == STOPPING) {
2353 // Input surface may have been started, so clean up is needed.
2354 clearInputSurfaceIfNeeded = true;
2355 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002356 state->set(RELEASING);
2357 }
2358
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002359 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002360 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2361 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002362 if (config->mInputSurface) {
2363 config->mInputSurface->disconnect();
2364 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08002365 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002366 }
2367 }
2368
Wonsik Kim936a89c2020-05-08 16:07:50 -07002369 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00002370 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002371 // thiz holds strong ref to this while the thread is running.
2372 sp<CCodec> thiz(this);
Sungtak Lee99144332023-01-26 11:03:14 +00002373 std::thread([thiz, sendCallback, pushBlankBuffer]
2374 { thiz->release(sendCallback, pushBlankBuffer); }).detach();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002375}
2376
Sungtak Lee99144332023-01-26 11:03:14 +00002377void CCodec::release(bool sendCallback, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002378 std::shared_ptr<Codec2Client::Component> comp;
2379 {
2380 Mutexed<State>::Locked state(mState);
2381 if (state->get() == RELEASED) {
2382 if (sendCallback) {
2383 state.unlock();
2384 mCallback->onReleaseCompleted();
2385 state.lock();
2386 }
2387 return;
2388 }
2389 comp = state->comp;
2390 }
Sungtak Leec0c05962023-10-25 08:14:13 +00002391 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->release().
2392 // But in the case some HAL implementations hang forever on comp->release().
2393 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
2394 // completing release()).
2395 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
2396 // prior to comp->release().
2397 // See also b/300350761.
Sungtak Lee34402ae2024-05-07 19:51:28 +00002398 //
2399 // The workaround is no longer needed with fetchGraphicBlock & C2Fence changes.
Sungtak Leeb7b1cf42024-05-14 22:45:35 +00002400 // so we are reverting back to the logical sequence of the operations when
2401 // AIDL HALs are selected.
2402 // When the HIDL HALs are selected, we retained workaround(the reversed
2403 // order) as default in order to keep legacy behavior.
2404 bool stopHalBeforeSurface =
2405 Codec2Client::IsAidlSelected() ||
2406 property_get_bool("debug.codec2.stop_hal_before_surface", false);
2407 if (stopHalBeforeSurface && android::media::codec::provider_->stop_hal_before_surface()) {
Sungtak Lee34402ae2024-05-07 19:51:28 +00002408 comp->release();
2409 mChannel->stopUseOutputSurface(pushBlankBuffer);
2410 } else {
2411 mChannel->stopUseOutputSurface(pushBlankBuffer);
2412 comp->release();
2413 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002414
2415 {
2416 Mutexed<State>::Locked state(mState);
2417 state->set(RELEASED);
2418 state->comp.reset();
2419 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002420 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002421 if (sendCallback) {
2422 mCallback->onReleaseCompleted();
2423 }
2424}
2425
Sungtak Lee214ce612023-11-01 10:01:13 +00002426status_t CCodec::setSurface(const sp<Surface> &surface, uint32_t generation) {
Sungtak Lee99144332023-01-26 11:03:14 +00002427 bool pushBlankBuffer = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002428 {
2429 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2430 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002431 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
2432 status_t err = OK;
2433
Wonsik Kim75e22f42021-04-14 23:34:51 -07002434 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002435 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07002436 nativeWindow.get(),
2437 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
2438 if (err != OK) {
2439 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
2440 nativeWindow.get(), config->mSidebandHandle->handle(), err);
2441 return err;
2442 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002443 } else {
2444 // Explicitly reset the sideband handle of the window for
2445 // non-tunneled video in case the window was previously used
2446 // for a tunneled video playback.
2447 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
2448 if (err != OK) {
2449 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
2450 return err;
2451 }
ted.sun765db4d2020-06-23 14:03:41 +08002452 }
Sungtak Lee99144332023-01-26 11:03:14 +00002453 pushBlankBuffer = config->mPushBlankBuffersOnStop;
ted.sun765db4d2020-06-23 14:03:41 +08002454 }
Sungtak Lee214ce612023-11-01 10:01:13 +00002455 return mChannel->setSurface(surface, generation, pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002456}
2457
2458void CCodec::signalFlush() {
2459 status_t err = [this] {
2460 Mutexed<State>::Locked state(mState);
2461 if (state->get() == FLUSHED) {
2462 return ALREADY_EXISTS;
2463 }
2464 if (state->get() != RUNNING) {
2465 return UNKNOWN_ERROR;
2466 }
2467 state->set(FLUSHING);
2468 return OK;
2469 }();
2470 switch (err) {
2471 case ALREADY_EXISTS:
2472 mCallback->onFlushCompleted();
2473 return;
2474 case OK:
2475 break;
2476 default:
2477 mCallback->onError(err, ACTION_CODE_FATAL);
2478 return;
2479 }
2480
2481 mChannel->stop();
2482 (new AMessage(kWhatFlush, this))->post();
2483}
2484
2485void CCodec::flush() {
2486 std::shared_ptr<Codec2Client::Component> comp;
2487 auto checkFlushing = [this, &comp] {
2488 Mutexed<State>::Locked state(mState);
2489 if (state->get() != FLUSHING) {
2490 return UNKNOWN_ERROR;
2491 }
2492 comp = state->comp;
2493 return OK;
2494 };
2495 if (tryAndReportOnError(checkFlushing) != OK) {
2496 return;
2497 }
2498
2499 std::list<std::unique_ptr<C2Work>> flushedWork;
2500 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2501 {
2502 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2503 flushedWork.splice(flushedWork.end(), *queue);
2504 }
2505 if (err != C2_OK) {
2506 // TODO: convert err into status_t
2507 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2508 }
2509
2510 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002511
2512 {
2513 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002514 if (state->get() == FLUSHING) {
2515 state->set(FLUSHED);
2516 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002517 }
2518 mCallback->onFlushCompleted();
2519}
2520
2521void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002522 std::shared_ptr<Codec2Client::Component> comp;
2523 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002524 Mutexed<State>::Locked state(mState);
2525 if (state->get() != FLUSHED) {
2526 return UNKNOWN_ERROR;
2527 }
2528 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002529 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002530 return OK;
2531 };
2532 if (tryAndReportOnError(setResuming) != OK) {
2533 return;
2534 }
2535
Wonsik Kime75a5da2020-02-14 17:29:03 -08002536 {
2537 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2538 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002539 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002540 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002541 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002542 }
2543
Arun Johnson106fe7a2023-04-26 17:49:43 +00002544 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
Arun Johnson326166e2023-07-28 19:11:52 +00002545 status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers, true);
Arun Johnson106fe7a2023-04-26 17:49:43 +00002546 if (err != OK) {
2547 if (err == NO_MEMORY) {
2548 // NO_MEMORY happens here when all the buffers are still
2549 // with the codec. That is not an error as it is momentarily
2550 // and the buffers are send to the client as soon as the codec
2551 // releases them
2552 ALOGI("Resuming with all input buffers still with codec");
2553 } else {
2554 ALOGE("Resume request for Input Buffers failed");
2555 mCallback->onError(err, ACTION_CODE_FATAL);
2556 return;
2557 }
2558 }
2559
2560 // channel start should be called after prepareInitialBuffers
2561 // Calling before can cause a failure during prepare when
2562 // buffers are sent to the client before preparation from onWorkDone
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002563 (void)mChannel->start(nullptr, nullptr, [&]{
2564 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2565 const std::unique_ptr<Config> &config = *configLocked;
2566 return config->mBuffersBoundToCodec;
2567 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002568 {
2569 Mutexed<State>::Locked state(mState);
2570 if (state->get() != RESUMING) {
2571 state.unlock();
2572 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2573 state.lock();
2574 return;
2575 }
2576 state->set(RUNNING);
2577 }
2578
Wonsik Kim34b28b42022-05-20 15:49:32 -07002579 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002580}
2581
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002582void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002583 std::shared_ptr<Codec2Client::Component> comp;
2584 auto checkState = [this, &comp] {
2585 Mutexed<State>::Locked state(mState);
2586 if (state->get() == RELEASED) {
2587 return INVALID_OPERATION;
2588 }
2589 comp = state->comp;
2590 return OK;
2591 };
2592 if (tryAndReportOnError(checkState) != OK) {
2593 return;
2594 }
2595
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002596 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2597 // the behavior here.
2598 sp<AMessage> params = msg;
2599 int32_t bitrate;
2600 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2601 params = msg->dup();
2602 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2603 }
2604
Houxiang Dai5a97b472021-03-22 17:56:04 +08002605 int32_t syncId = 0;
2606 if (params->findInt32("audio-hw-sync", &syncId)
2607 || params->findInt32("hw-av-sync-id", &syncId)) {
2608 configureTunneledVideoPlayback(comp, nullptr, params);
2609 }
2610
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002611 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2612 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002613
2614 /**
2615 * Handle input surface parameters
2616 */
2617 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002618 && (config->mDomain & Config::IS_ENCODER)
2619 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002620 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002621
2622 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2623 config->mISConfig->mStopped = false;
2624 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2625 config->mISConfig->mStopped = true;
2626 }
2627
2628 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002629 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002630 config->mISConfig->mSuspended = value;
2631 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002632 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002633 }
2634
2635 (void)config->mInputSurface->configure(*config->mISConfig);
2636 if (config->mISConfig->mStopped) {
2637 config->mInputFormat->setInt64(
2638 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2639 }
2640 }
2641
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302642 /**
2643 * Handle ROI QP map configuration. Recover the QP map configuration from AMessage as an
2644 * ABuffer and configure to CCodecBufferChannel as a C2InfoBuffer
2645 */
2646 if (android::media::codec::provider_->region_of_interest()
2647 && android::media::codec::provider_->region_of_interest_support()) {
2648 sp<ABuffer> qpOffsetMap;
2649 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
2650 && (config->mDomain & Config::IS_ENCODER)
2651 && params->findBuffer(PARAMETER_KEY_QP_OFFSET_MAP, &qpOffsetMap)) {
2652 std::shared_ptr<C2BlockPool> pool;
2653 // TODO(b/331443865) Use pooled block pool to improve efficiency
2654 c2_status_t status = GetCodec2BlockPool(C2BlockPool::BASIC_LINEAR, nullptr, &pool);
2655
2656 if (status == C2_OK) {
Suyog Paware23970e2024-06-03 15:57:49 +05302657 int width, height;
2658 config->mInputFormat->findInt32("width", &width);
2659 config->mInputFormat->findInt32("height", &height);
2660 // The length of the qp-map corresponds to the number of 16x16 blocks in one frame
2661 int expectedMapSize = ((width + 15) / 16) * ((height + 15) / 16);
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302662 size_t mapSize = qpOffsetMap->size();
Suyog Paware23970e2024-06-03 15:57:49 +05302663 if (mapSize >= expectedMapSize) {
2664 std::shared_ptr<C2LinearBlock> block;
2665 status = pool->fetchLinearBlock(
2666 expectedMapSize,
2667 C2MemoryUsage{C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
2668 &block);
2669 if (status == C2_OK && !block->map().get().error()) {
2670 C2WriteView wView = block->map().get();
2671 uint8_t* outData = wView.data();
2672 memcpy(outData, qpOffsetMap->data(), expectedMapSize);
2673 C2InfoBuffer info = C2InfoBuffer::CreateLinearBuffer(
2674 kParamIndexQpOffsetMapBuffer,
2675 block->share(0, expectedMapSize, C2Fence()));
2676 mChannel->setInfoBuffer(std::make_shared<C2InfoBuffer>(info));
2677 }
2678 } else {
Yi Kong8d0feae2024-07-23 16:36:11 +09002679 ALOGE("Ignoring param key %s as buffer size %zu is less than expected "
Suyog Paware23970e2024-06-03 15:57:49 +05302680 "buffer size %d",
2681 PARAMETER_KEY_QP_OFFSET_MAP, mapSize, expectedMapSize);
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302682 }
2683 }
2684 params->removeEntryByName(PARAMETER_KEY_QP_OFFSET_MAP);
2685 }
2686 }
2687
2688
Pawin Vongmasa36653902018-11-15 00:10:25 -08002689 std::vector<std::unique_ptr<C2Param>> configUpdate;
2690 (void)config->getConfigUpdateFromSdkParams(
2691 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2692 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2693 // Parameter synchronization is not defined when using input surface. For now, route
2694 // these directly to the component.
2695 if (config->mInputSurface == nullptr
2696 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2697 || comp->getName().find("c2.android.") == 0)) {
Wonsik Kim051238c2024-06-13 21:16:23 +00002698 std::vector<std::unique_ptr<C2Param>> localConfigUpdate;
2699 for (const std::unique_ptr<C2Param> &param : configUpdate) {
2700 if (param && param->coreIndex().coreIndex() == C2StreamSurfaceScalingInfo::CORE_INDEX) {
2701 localConfigUpdate.push_back(C2Param::Copy(*param));
2702 }
2703 }
2704 if (!localConfigUpdate.empty()) {
2705 (void)config->setParameters(comp, localConfigUpdate, C2_MAY_BLOCK);
2706 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002707 mChannel->setParameters(configUpdate);
2708 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002709 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002710 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002711 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002712 }
2713}
2714
2715void CCodec::signalEndOfInputStream() {
2716 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2717}
2718
2719void CCodec::signalRequestIDRFrame() {
2720 std::shared_ptr<Codec2Client::Component> comp;
2721 {
2722 Mutexed<State>::Locked state(mState);
2723 if (state->get() == RELEASED) {
2724 ALOGD("no IDR request sent since component is released");
2725 return;
2726 }
2727 comp = state->comp;
2728 }
2729 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002730 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2731 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002732 std::vector<std::unique_ptr<C2Param>> params;
2733 params.push_back(
2734 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2735 config->setParameters(comp, params, C2_MAY_BLOCK);
2736}
2737
Wonsik Kim874ad382021-03-12 09:59:36 -08002738status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2739 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2740 const std::unique_ptr<Config> &config = *configLocked;
2741 return config->querySupportedParameters(names);
2742}
2743
2744status_t CCodec::describeParameter(
2745 const std::string &name, CodecParameterDescriptor *desc) {
2746 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2747 const std::unique_ptr<Config> &config = *configLocked;
2748 return config->describe(name, desc);
2749}
2750
2751status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2752 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2753 if (!comp) {
2754 return INVALID_OPERATION;
2755 }
2756 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2757 const std::unique_ptr<Config> &config = *configLocked;
2758 return config->subscribeToVendorConfigUpdate(comp, names);
2759}
2760
2761status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2762 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2763 if (!comp) {
2764 return INVALID_OPERATION;
2765 }
2766 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2767 const std::unique_ptr<Config> &config = *configLocked;
2768 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2769}
2770
Wonsik Kimab34ed62019-01-31 15:28:46 -08002771void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002772 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002773 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002774 bool shouldPost = queue->empty();
Wonsik Kimab34ed62019-01-31 15:28:46 -08002775 queue->splice(queue->end(), workItems);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002776 if (shouldPost) {
2777 (new AMessage(kWhatWorkDone, this))->post();
2778 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002779 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002780}
2781
Wonsik Kimab34ed62019-01-31 15:28:46 -08002782void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2783 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002784 if (arrayIndex == 0) {
2785 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002786 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2787 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002788 if (config->mInputSurface) {
2789 config->mInputSurface->onInputBufferDone(frameIndex);
2790 }
2791 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002792}
2793
2794void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2795 TimePoint now = std::chrono::steady_clock::now();
2796 CCodecWatchdog::getInstance()->watch(this);
2797 switch (msg->what()) {
2798 case kWhatAllocate: {
2799 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002800 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002801 sp<RefBase> obj;
2802 CHECK(msg->findObject("codecInfo", &obj));
2803 allocate((MediaCodecInfo *)obj.get());
2804 break;
2805 }
2806 case kWhatConfigure: {
2807 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002808 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002809 sp<AMessage> format;
2810 CHECK(msg->findMessage("format", &format));
2811 configure(format);
2812 break;
2813 }
2814 case kWhatStart: {
2815 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002816 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002817 start();
2818 break;
2819 }
2820 case kWhatStop: {
2821 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002822 setDeadline(now, 1500ms, "stop");
Sungtak Lee99144332023-01-26 11:03:14 +00002823 int32_t pushBlankBuffer;
2824 if (!msg->findInt32("pushBlankBuffer", &pushBlankBuffer)) {
2825 pushBlankBuffer = 0;
2826 }
2827 stop(static_cast<bool>(pushBlankBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002828 break;
2829 }
2830 case kWhatFlush: {
2831 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002832 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002833 flush();
2834 break;
2835 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002836 case kWhatRelease: {
2837 mChannel->release();
2838 mClient.reset();
2839 mClientListener.reset();
2840 break;
2841 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002842 case kWhatCreateInputSurface: {
2843 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002844 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002845 createInputSurface();
2846 break;
2847 }
2848 case kWhatSetInputSurface: {
2849 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002850 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002851 sp<RefBase> obj;
2852 CHECK(msg->findObject("surface", &obj));
2853 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2854 setInputSurface(surface);
2855 break;
2856 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002857 case kWhatWorkDone: {
2858 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002859 bool shouldPost = false;
2860 {
2861 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2862 if (queue->empty()) {
2863 break;
2864 }
2865 work.swap(queue->front());
2866 queue->pop_front();
2867 shouldPost = !queue->empty();
2868 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002869 if (shouldPost) {
2870 (new AMessage(kWhatWorkDone, this))->post();
2871 }
2872
Pawin Vongmasa36653902018-11-15 00:10:25 -08002873 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002874 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002875 sp<AMessage> outputFormat = nullptr;
2876 {
2877 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2878 const std::unique_ptr<Config> &config = *configLocked;
2879 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2880 config->watch<C2StreamInitDataInfo::output>();
2881 if (!work->worklets.empty()
2882 && (work->worklets.front()->output.flags
2883 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002884
Wonsik Kim75e22f42021-04-14 23:34:51 -07002885 // copy buffer info to config
2886 std::vector<std::unique_ptr<C2Param>> updates;
2887 for (const std::unique_ptr<C2Param> &param
2888 : work->worklets.front()->output.configUpdate) {
2889 updates.push_back(C2Param::Copy(*param));
2890 }
2891 unsigned stream = 0;
2892 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2893 work->worklets.front()->output.buffers;
2894 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2895 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2896 // move all info into output-stream #0 domain
2897 updates.emplace_back(
2898 C2Param::CopyAsStream(*info, true /* output */, stream));
2899 }
2900
2901 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2902 // for now only do the first block
2903 if (!blocks.empty()) {
2904 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2905 // block.crop().left, block.crop().top,
2906 // block.crop().width, block.crop().height,
2907 // block.width(), block.height());
2908 const C2ConstGraphicBlock &block = blocks[0];
2909 updates.emplace_back(new C2StreamCropRectInfo::output(
2910 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002911 }
2912 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002913 }
George Burgess IVc813a592020-02-22 22:54:44 -08002914
Wonsik Kim75e22f42021-04-14 23:34:51 -07002915 sp<AMessage> oldFormat = config->mOutputFormat;
2916 config->updateConfiguration(updates, config->mOutputDomain);
2917 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002918
Wonsik Kim75e22f42021-04-14 23:34:51 -07002919 // copy standard infos to graphic buffers if not already present (otherwise, we
2920 // may overwrite the actual intermediate value with a final value)
2921 stream = 0;
2922 const static C2Param::Index stdGfxInfos[] = {
2923 C2StreamRotationInfo::output::PARAM_TYPE,
2924 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2925 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2926 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Taehwan Kim2d222b82022-05-12 14:19:26 +09002927 C2StreamHdr10PlusInfo::output::PARAM_TYPE, // will be deprecated
2928 C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE,
Wonsik Kim75e22f42021-04-14 23:34:51 -07002929 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2930 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2931 };
2932 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2933 if (buf->data().graphicBlocks().size()) {
2934 for (C2Param::Index ix : stdGfxInfos) {
2935 if (!buf->hasInfo(ix)) {
2936 const C2Param *param =
2937 config->getConfigParameterValue(ix.withStream(stream));
2938 if (param) {
2939 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2940 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2941 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002942 }
2943 }
2944 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002945 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002946 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002947 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002948 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302949 if (work->worklets.empty()
2950 || !work->worklets.back()
2951 || (work->worklets.back()->output.flags
2952 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2953 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2954 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002955 }
2956 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002957 initData = initDataWatcher.update();
2958 AmendOutputFormatWithCodecSpecificData(
2959 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2960 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002961 }
2962 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002963 }
2964 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002965 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Songyue Han1e6769b2023-08-30 18:09:27 +00002966 // log metrics to MediaCodec
2967 if (mMetrics->countEntries() == 0) {
2968 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2969 const std::unique_ptr<Config> &config = *configLocked;
2970 uint32_t pf = PIXEL_FORMAT_UNKNOWN;
2971 if (!config->mInputSurface) {
2972 pf = mChannel->getBuffersPixelFormat(config->mDomain & Config::IS_ENCODER);
Songyue Hanad01f6a2023-08-17 05:45:35 +00002973 } else {
2974 pf = config->mInputSurface->getPixelFormat();
Songyue Han1e6769b2023-08-30 18:09:27 +00002975 }
2976 if (pf != PIXEL_FORMAT_UNKNOWN) {
2977 mMetrics->setInt64(kCodecPixelFormat, pf);
2978 mCallback->onMetricsUpdated(mMetrics);
2979 }
2980 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002981 break;
2982 }
2983 case kWhatWatch: {
2984 // watch message already posted; no-op.
2985 break;
2986 }
2987 default: {
2988 ALOGE("unrecognized message");
2989 break;
2990 }
2991 }
2992 setDeadline(TimePoint::max(), 0ms, "none");
2993}
2994
2995void CCodec::setDeadline(
2996 const TimePoint &now,
2997 const std::chrono::milliseconds &timeout,
2998 const char *name) {
2999 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
3000 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
3001 deadline->set(now + (timeout * mult), name);
3002}
3003
ted.sun765db4d2020-06-23 14:03:41 +08003004status_t CCodec::configureTunneledVideoPlayback(
3005 std::shared_ptr<Codec2Client::Component> comp,
3006 sp<NativeHandle> *sidebandHandle,
3007 const sp<AMessage> &msg) {
3008 std::vector<std::unique_ptr<C2SettingResult>> failures;
3009
3010 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
3011 C2PortTunneledModeTuning::output::AllocUnique(
3012 1,
3013 C2PortTunneledModeTuning::Struct::SIDEBAND,
3014 C2PortTunneledModeTuning::Struct::REALTIME,
3015 0);
3016 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
3017 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
3018 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
3019 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
3020 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
3021 } else {
3022 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
3023 tunneledPlayback->setFlexCount(0);
3024 }
3025 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
3026 if (c2err != C2_OK) {
3027 return UNKNOWN_ERROR;
3028 }
3029
Houxiang Dai5a97b472021-03-22 17:56:04 +08003030 if (sidebandHandle == nullptr) {
3031 return OK;
3032 }
3033
ted.sun765db4d2020-06-23 14:03:41 +08003034 std::vector<std::unique_ptr<C2Param>> params;
3035 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
3036 if (c2err == C2_OK && params.size() == 1u) {
3037 C2PortTunnelHandleTuning::output *videoTunnelSideband =
3038 C2PortTunnelHandleTuning::output::From(params[0].get());
3039 // Currently, Codec2 only supports non-fd case for sideband native_handle.
3040 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
3041 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
3042 if (handle != nullptr && videoTunnelSideband->flexCount()) {
3043 memcpy(handle->data, videoTunnelSideband->m.values,
3044 sizeof(int32_t) * videoTunnelSideband->flexCount());
3045 return OK;
3046 } else {
3047 return NO_MEMORY;
3048 }
3049 }
3050 return UNKNOWN_ERROR;
3051}
3052
Pawin Vongmasa36653902018-11-15 00:10:25 -08003053void CCodec::initiateReleaseIfStuck() {
Shrikara B3b87a532022-08-26 14:18:14 +05303054 std::string name;
3055 bool pendingDeadline = false;
3056 {
3057 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
3058 if (deadline->get() < std::chrono::steady_clock::now()) {
3059 name = deadline->getName();
3060 }
3061 if (deadline->get() != TimePoint::max()) {
3062 pendingDeadline = true;
3063 }
3064 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08003065 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08003066 // We're not stuck.
3067 if (pendingDeadline) {
3068 // If we are not stuck yet but still has deadline coming up,
3069 // post watch message to check back later.
3070 (new AMessage(kWhatWatch, this))->post();
3071 }
3072 return;
3073 }
3074
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09003075 C2String compName;
3076 {
3077 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07003078 if (!state->comp) {
3079 ALOGD("previous call to %s exceeded timeout "
3080 "and the component is already released", name.c_str());
3081 return;
3082 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09003083 compName = state->comp->getName();
3084 }
3085 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
3086
Pawin Vongmasa36653902018-11-15 00:10:25 -08003087 initiateRelease(false);
3088 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
3089}
3090
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003091// static
3092PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07003093 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07003094 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08003095 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07003096 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
3097 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08003098 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07003099 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
Sungtak Lee92bca442024-03-12 09:10:31 +00003100 if (Codec2Client::IsAidlSelected()) {
3101 sp<IGraphicBufferProducer> gbp;
3102 sp<AidlGraphicBufferSource> gbs = new AidlGraphicBufferSource();
3103 status_t err = gbs->initCheck();
3104 if (err != OK) {
3105 ALOGE("Failed to create persistent input surface: error %d", err);
3106 return nullptr;
3107 }
3108 ALOGD("aidl based PersistentSurface created");
3109 std::shared_ptr<WAidlGraphicBufferSource> wrapper =
3110 ::ndk::SharedRefBase::make<WAidlGraphicBufferSource>(gbs);
3111
3112 return new PersistentSurface(
3113 gbs->getIGraphicBufferProducer(), wrapper->asBinder());
3114 } else {
3115 sp<IGraphicBufferProducer> gbp;
3116 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
3117 status_t err = gbs->initCheck();
3118 if (err != OK) {
3119 ALOGE("Failed to create persistent input surface: error %d", err);
3120 return nullptr;
3121 }
3122 ALOGD("hidl based PersistentSurface created");
3123 return new PersistentSurface(
3124 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07003125 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07003126 } else {
3127 return nullptr;
3128 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08003129 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07003130 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08003131 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07003132 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08003133 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08003134}
3135
Wonsik Kimffb889a2020-05-28 11:32:25 -07003136class IntfCache {
3137public:
3138 IntfCache() = default;
3139
3140 status_t init(const std::string &name) {
3141 std::shared_ptr<Codec2Client::Interface> intf{
3142 Codec2Client::CreateInterfaceByName(name.c_str())};
3143 if (!intf) {
3144 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
3145 mInitStatus = NO_INIT;
3146 return NO_INIT;
3147 }
3148 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
3149 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
3150 C2ParamField{&sUsage, &sUsage.value}));
3151 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
3152 if (err != C2_OK) {
3153 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
3154 name.c_str(), err);
3155 mFields[0].status = err;
3156 }
3157 std::vector<std::unique_ptr<C2Param>> params;
3158 err = intf->query(
3159 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09003160 {
3161 C2StreamBufferTypeSetting::input::PARAM_TYPE,
3162 C2PortAllocatorsTuning::input::PARAM_TYPE
3163 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07003164 C2_MAY_BLOCK,
3165 &params);
3166 if (err != C2_OK && err != C2_BAD_INDEX) {
3167 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
3168 name.c_str(), err);
3169 }
3170 while (!params.empty()) {
3171 C2Param *param = params.back().release();
3172 params.pop_back();
3173 if (!param) {
3174 continue;
3175 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09003176 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
3177 mInputStreamFormat.reset(
3178 C2StreamBufferTypeSetting::input::From(param));
3179 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003180 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07003181 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07003182 }
3183 }
3184 mInitStatus = OK;
3185 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003186 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003187
3188 status_t initCheck() const { return mInitStatus; }
3189
3190 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
3191 CHECK_EQ(1u, mFields.size());
3192 return mFields[0];
3193 }
3194
3195 const C2ApiFeaturesSetting &getApiFeatures() const {
3196 return mApiFeatures;
3197 }
3198
Taehwan Kim900b49c2021-12-13 11:16:22 +09003199 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
3200 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
3201 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
3202 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
3203 param->invalidate();
3204 return param;
3205 }();
3206 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
3207 }
3208
Wonsik Kimffb889a2020-05-28 11:32:25 -07003209 const C2PortAllocatorsTuning::input &getInputAllocators() const {
3210 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
3211 std::unique_ptr<C2PortAllocatorsTuning::input> param =
3212 C2PortAllocatorsTuning::input::AllocUnique(0);
3213 param->invalidate();
3214 return param;
3215 }();
3216 return mInputAllocators ? *mInputAllocators : *sInvalidated;
3217 }
3218
3219private:
3220 status_t mInitStatus{NO_INIT};
3221
3222 std::vector<C2FieldSupportedValuesQuery> mFields;
3223 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09003224 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003225 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
3226};
3227
3228static const IntfCache &GetIntfCache(const std::string &name) {
3229 static IntfCache sNullIntfCache;
3230 static std::mutex sMutex;
3231 static std::map<std::string, IntfCache> sCache;
3232 std::unique_lock<std::mutex> lock{sMutex};
3233 auto it = sCache.find(name);
3234 if (it == sCache.end()) {
3235 lock.unlock();
3236 IntfCache intfCache;
3237 status_t err = intfCache.init(name);
3238 if (err != OK) {
3239 return sNullIntfCache;
3240 }
3241 lock.lock();
3242 it = sCache.insert({name, std::move(intfCache)}).first;
3243 }
3244 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003245}
3246
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003247static status_t GetCommonAllocatorIds(
3248 const std::vector<std::string> &names,
3249 C2Allocator::type_t type,
3250 std::set<C2Allocator::id_t> *ids) {
3251 int poolMask = GetCodec2PoolMask();
3252 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
3253 C2Allocator::id_t defaultAllocatorId =
3254 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
3255
3256 ids->clear();
3257 if (names.empty()) {
3258 return OK;
3259 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003260 bool firstIteration = true;
3261 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003262 const IntfCache &intfCache = GetIntfCache(name);
3263 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003264 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003265 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09003266 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
3267 if (streamFormat) {
3268 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
3269 if (streamFormat.value == C2BufferData::GRAPHIC
3270 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
3271 allocatorType = C2Allocator::GRAPHIC;
3272 }
3273
3274 if (type != allocatorType) {
3275 // requested type is not supported at input allocators
3276 ids->clear();
3277 ids->insert(defaultAllocatorId);
3278 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
3279 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
3280 break;
3281 }
3282 }
3283
Wonsik Kimffb889a2020-05-28 11:32:25 -07003284 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003285 if (firstIteration) {
3286 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003287 if (allocators && allocators.flexCount() > 0) {
3288 ids->insert(allocators.m.values,
3289 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003290 }
3291 if (ids->empty()) {
3292 // The component does not advertise allocators. Use default.
3293 ids->insert(defaultAllocatorId);
3294 }
3295 continue;
3296 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003297 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003298 if (allocators && allocators.flexCount() > 0) {
3299 filtered = true;
3300 for (auto it = ids->begin(); it != ids->end(); ) {
3301 bool found = false;
3302 for (size_t j = 0; j < allocators.flexCount(); ++j) {
3303 if (allocators.m.values[j] == *it) {
3304 found = true;
3305 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003306 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003307 }
3308 if (found) {
3309 ++it;
3310 } else {
3311 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003312 }
3313 }
3314 }
3315 if (!filtered) {
3316 // The component does not advertise supported allocators. Use default.
3317 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
3318 if (ids->size() != (containsDefault ? 1 : 0)) {
3319 ids->clear();
3320 if (containsDefault) {
3321 ids->insert(defaultAllocatorId);
3322 }
3323 }
3324 }
3325 }
3326 // Finally, filter with pool masks
3327 for (auto it = ids->begin(); it != ids->end(); ) {
3328 if ((poolMask >> *it) & 1) {
3329 ++it;
3330 } else {
3331 it = ids->erase(it);
3332 }
3333 }
3334 return OK;
3335}
3336
3337static status_t CalculateMinMaxUsage(
3338 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
3339 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
3340 *minUsage = 0;
3341 *maxUsage = ~0ull;
3342 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003343 const IntfCache &intfCache = GetIntfCache(name);
3344 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003345 continue;
3346 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003347 const C2FieldSupportedValuesQuery &usageSupportedValues =
3348 intfCache.getUsageSupportedValues();
3349 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003350 continue;
3351 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003352 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003353 if (supported.type != C2FieldSupportedValues::FLAGS) {
3354 continue;
3355 }
3356 if (supported.values.empty()) {
3357 *maxUsage = 0;
3358 continue;
3359 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08003360 if (supported.values.size() > 1) {
3361 *minUsage |= supported.values[1].u64;
3362 } else {
3363 *minUsage |= supported.values[0].u64;
3364 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003365 int64_t currentMaxUsage = 0;
3366 for (const C2Value::Primitive &flags : supported.values) {
3367 currentMaxUsage |= flags.u64;
3368 }
3369 *maxUsage &= currentMaxUsage;
3370 }
3371 return OK;
3372}
3373
3374// static
3375status_t CCodec::CanFetchLinearBlock(
3376 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003377 for (const std::string &name : names) {
3378 const IntfCache &intfCache = GetIntfCache(name);
3379 if (intfCache.initCheck() != OK) {
3380 continue;
3381 }
3382 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
3383 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
3384 *isCompatible = false;
3385 return OK;
3386 }
3387 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003388 std::set<C2Allocator::id_t> allocators;
3389 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
3390 if (allocators.empty()) {
3391 *isCompatible = false;
3392 return OK;
3393 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003394
3395 uint64_t minUsage = 0;
3396 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003397 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003398 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003399 *isCompatible = ((maxUsage & minUsage) == minUsage);
3400 return OK;
3401}
3402
3403static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
3404 static std::mutex sMutex{};
3405 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
3406 std::unique_lock<std::mutex> lock{sMutex};
3407 std::shared_ptr<C2BlockPool> pool;
3408 auto it = sPools.find(allocId);
3409 if (it == sPools.end()) {
3410 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3411 if (err == OK) {
3412 sPools.emplace(allocId, pool);
3413 } else {
3414 pool.reset();
3415 }
3416 } else {
3417 pool = it->second;
3418 }
3419 return pool;
3420}
3421
3422// static
3423std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
3424 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003425 std::set<C2Allocator::id_t> allocators;
3426 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
3427 if (allocators.empty()) {
3428 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
3429 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003430
3431 uint64_t minUsage = 0;
3432 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003433 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003434 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003435 if ((maxUsage & minUsage) != minUsage) {
3436 allocators.clear();
3437 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
3438 }
3439 std::shared_ptr<C2LinearBlock> block;
3440 for (C2Allocator::id_t allocId : allocators) {
3441 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
3442 if (!pool) {
3443 continue;
3444 }
3445 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
3446 if (err != C2_OK || !block) {
3447 block.reset();
3448 continue;
3449 }
3450 break;
3451 }
3452 return block;
3453}
3454
3455// static
3456status_t CCodec::CanFetchGraphicBlock(
3457 const std::vector<std::string> &names, bool *isCompatible) {
3458 uint64_t minUsage = 0;
3459 uint64_t maxUsage = ~0ull;
3460 std::set<C2Allocator::id_t> allocators;
3461 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3462 if (allocators.empty()) {
3463 *isCompatible = false;
3464 return OK;
3465 }
3466 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3467 *isCompatible = ((maxUsage & minUsage) == minUsage);
3468 return OK;
3469}
3470
3471// static
3472std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
3473 int32_t width,
3474 int32_t height,
3475 int32_t format,
3476 uint64_t usage,
3477 const std::vector<std::string> &names) {
3478 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
3479 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
3480 ALOGD("Unrecognized pixel format: %d", format);
3481 return nullptr;
3482 }
3483 uint64_t minUsage = 0;
3484 uint64_t maxUsage = ~0ull;
3485 std::set<C2Allocator::id_t> allocators;
3486 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3487 if (allocators.empty()) {
3488 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3489 }
3490 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3491 minUsage |= usage;
3492 if ((maxUsage & minUsage) != minUsage) {
3493 allocators.clear();
3494 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3495 }
3496 std::shared_ptr<C2GraphicBlock> block;
3497 for (C2Allocator::id_t allocId : allocators) {
3498 std::shared_ptr<C2BlockPool> pool;
3499 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3500 if (err != C2_OK || !pool) {
3501 continue;
3502 }
3503 err = pool->fetchGraphicBlock(
3504 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
3505 if (err != C2_OK || !block) {
3506 block.reset();
3507 continue;
3508 }
3509 break;
3510 }
3511 return block;
3512}
3513
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003514} // namespace android