blob: 64d8f07ab9803fe95de886c124543e945b2db1fe [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() {
99 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
100 static std::once_flag flag;
101 // Call Init() only once.
102 std::call_once(flag, Init, instance);
103 return instance;
104 }
105
106 ~CCodecWatchdog() = default;
107
108 void watch(sp<CCodec> codec) {
109 bool shouldPost = false;
110 {
111 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
112 // If a watch message is in flight, piggy-back this instance as well.
113 // Otherwise, post a new watch message.
114 shouldPost = codecs->empty();
115 codecs->emplace(codec);
116 }
117 if (shouldPost) {
118 ALOGV("posting watch message");
119 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
120 }
121 }
122
123protected:
124 void onMessageReceived(const sp<AMessage> &msg) {
125 switch (msg->what()) {
126 case kWhatWatch: {
127 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
128 ALOGV("watch for %zu codecs", codecs->size());
129 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
130 sp<CCodec> codec = it->promote();
131 if (codec == nullptr) {
132 continue;
133 }
134 codec->initiateReleaseIfStuck();
135 }
136 codecs->clear();
137 break;
138 }
139
140 default: {
141 TRESPASS("CCodecWatchdog: unrecognized message");
142 }
143 }
144 }
145
146private:
147 CCodecWatchdog() : mLooper(new ALooper) {}
148
149 static void Init(const sp<CCodecWatchdog> &thiz) {
150 ALOGV("Init");
151 thiz->mLooper->setName("CCodecWatchdog");
152 thiz->mLooper->registerHandler(thiz);
153 thiz->mLooper->start();
154 }
155
156 sp<ALooper> mLooper;
157
158 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
159};
160
161class C2InputSurfaceWrapper : public InputSurfaceWrapper {
162public:
163 explicit C2InputSurfaceWrapper(
164 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
165 mSurface(surface) {
166 }
167
168 ~C2InputSurfaceWrapper() override = default;
169
170 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
171 if (mConnection != nullptr) {
172 return ALREADY_EXISTS;
173 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800174 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800175 }
176
177 void disconnect() override {
178 if (mConnection != nullptr) {
179 mConnection->disconnect();
180 mConnection = nullptr;
181 }
182 }
183
184 status_t start() override {
185 // InputSurface does not distinguish started state
186 return OK;
187 }
188
189 status_t signalEndOfInputStream() override {
190 C2InputSurfaceEosTuning eos(true);
191 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800192 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800193 if (err != C2_OK) {
194 return UNKNOWN_ERROR;
195 }
196 return OK;
197 }
198
199 status_t configure(Config &config __unused) {
200 // TODO
201 return OK;
202 }
203
204private:
205 std::shared_ptr<Codec2Client::InputSurface> mSurface;
206 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
207};
208
Sungtak Lee92bca442024-03-12 09:10:31 +0000209class HGraphicBufferSourceWrapper : public InputSurfaceWrapper {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800210public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700211 typedef hardware::media::omx::V1_0::Status OmxStatus;
212
Sungtak Lee92bca442024-03-12 09:10:31 +0000213 HGraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700214 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800215 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700216 uint32_t height,
217 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800218 : mSource(source), mWidth(width), mHeight(height) {
219 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700220 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800221 }
Sungtak Lee92bca442024-03-12 09:10:31 +0000222 ~HGraphicBufferSourceWrapper() override = default;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800223
224 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700225 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
226 *node = new C2OMXNode(comp);
227 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(*node);
228 (*node)->setFrameSize(mWidth, mHeight);
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700229 // Usage is queried during configure(), so setting it beforehand.
Sungtak Lee0cd4fbc2023-02-02 00:59:01 +0000230 // 64 bit set parameter is existing only in C2OMXNode.
231 OMX_U64 usage64 = mConfig.mUsage;
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700232 status_t res = (*node)->setParameter(
Sungtak Lee0cd4fbc2023-02-02 00:59:01 +0000233 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits64,
234 &usage64, sizeof(usage64));
235
236 if (res != OK) {
237 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700238 (void)(*node)->setParameter(
Sungtak Lee0cd4fbc2023-02-02 00:59:01 +0000239 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
240 &usage, sizeof(usage));
241 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700242
Yanqiang Fanc56f3e62021-09-28 16:54:07 +0800243 return GetStatus(mSource->configure(
244 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800245 }
246
247 void disconnect() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700248 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
249 if ((*node) == nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800250 return;
251 }
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700252 sp<IOMXBufferSource> source = (*node)->getSource();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800253 if (source == nullptr) {
254 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
255 return;
256 }
257 source->onOmxIdle();
258 source->onOmxLoaded();
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700259 node->clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700260 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800261 }
262
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700263 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
264 if (status.isOk()) {
265 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
266 } else if (status.isDeadObject()) {
267 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800268 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700269 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800270 }
271
272 status_t start() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700273 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
274 if ((*node) == nullptr) {
275 return NO_INIT;
276 }
277 sp<IOMXBufferSource> source = (*node)->getSource();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800278 if (source == nullptr) {
279 return NO_INIT;
280 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900281
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800282 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800283 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900284
Wonsik Kim34d66012021-03-01 16:40:33 -0800285 OMX_PARAM_PORTDEFINITIONTYPE param;
286 param.nPortIndex = kPortIndexInput;
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700287 status_t err = (*node)->getParameter(OMX_IndexParamPortDefinition,
Wonsik Kim34d66012021-03-01 16:40:33 -0800288 &param, sizeof(param));
289 if (err == OK) {
290 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900291 }
292
293 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800294 source->onInputBufferAdded(i);
295 }
296
297 source->onOmxExecuting();
298 return OK;
299 }
300
301 status_t signalEndOfInputStream() override {
302 return GetStatus(mSource->signalEndOfInputStream());
303 }
304
305 status_t configure(Config &config) {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700306 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800307 std::stringstream status;
308 status_t err = OK;
309
310 // handle each configuration granually, in case we need to handle part of the configuration
311 // elsewhere
312
313 // TRICKY: we do not unset frame delay repeating
314 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
315 int64_t us = 1e6 / config.mMinFps + 0.5;
316 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
317 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
318 if (res != OK) {
319 status << " (=> " << asString(res) << ")";
320 err = res;
321 }
322 mConfig.mMinFps = config.mMinFps;
323 }
324
325 // pts gap
326 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700327 if ((*node) != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800328 OMX_PARAM_U32TYPE ptrGapParam = {};
329 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700330 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800331 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
332 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700333 // float -> uint32_t is undefined if the value is negative.
334 // First convert to int32_t to ensure the expected behavior.
335 ptrGapParam.nU32 = int32_t(gap);
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700336 (void)(*node)->setParameter(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800337 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
338 &ptrGapParam, sizeof(ptrGapParam));
339 }
340 }
341
342 // max fps
343 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700344 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800345 && config.mMaxFps != mConfig.mMaxFps) {
346 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
347 status << " maxFps=" << config.mMaxFps;
348 if (res != OK) {
349 status << " (=> " << asString(res) << ")";
350 err = res;
351 }
352 mConfig.mMaxFps = config.mMaxFps;
353 }
354
355 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
356 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
357 status << " timeOffset " << config.mTimeOffsetUs << "us";
358 if (res != OK) {
359 status << " (=> " << asString(res) << ")";
360 err = res;
361 }
362 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
363 }
364
365 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
366 status_t res =
367 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
368 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
369 if (res != OK) {
370 status << " (=> " << asString(res) << ")";
371 err = res;
372 }
373 mConfig.mCaptureFps = config.mCaptureFps;
374 mConfig.mCodedFps = config.mCodedFps;
375 }
376
377 if (config.mStartAtUs != mConfig.mStartAtUs
378 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
379 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
380 status << " start at " << config.mStartAtUs << "us";
381 if (res != OK) {
382 status << " (=> " << asString(res) << ")";
383 err = res;
384 }
385 mConfig.mStartAtUs = config.mStartAtUs;
386 mConfig.mStopped = config.mStopped;
387 }
388
389 // suspend-resume
390 if (config.mSuspended != mConfig.mSuspended) {
391 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
392 status << " " << (config.mSuspended ? "suspend" : "resume")
393 << " at " << config.mSuspendAtUs << "us";
394 if (res != OK) {
395 status << " (=> " << asString(res) << ")";
396 err = res;
397 }
398 mConfig.mSuspended = config.mSuspended;
399 mConfig.mSuspendAtUs = config.mSuspendAtUs;
400 }
401
402 if (config.mStopped != mConfig.mStopped && config.mStopped) {
403 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
404 status << " stop at " << config.mStopAtUs << "us";
405 if (res != OK) {
406 status << " (=> " << asString(res) << ")";
407 err = res;
408 } else {
409 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700410 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
411 [&res, &delayUs = config.mInputDelayUs](
412 auto status, auto stopTimeOffsetUs) {
413 res = static_cast<status_t>(status);
414 delayUs = stopTimeOffsetUs;
415 });
416 if (!trans.isOk()) {
417 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
418 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800419 if (res != OK) {
420 status << " (=> " << asString(res) << ")";
421 } else {
422 status << "=" << config.mInputDelayUs << "us";
423 }
424 mConfig.mInputDelayUs = config.mInputDelayUs;
425 }
426 mConfig.mStopAtUs = config.mStopAtUs;
427 mConfig.mStopped = config.mStopped;
428 }
429
430 // color aspects (android._color-aspects)
431
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700432 // consumer usage is queried earlier.
433
Wonsik Kima1335e12021-04-22 16:28:29 -0700434 // priority
435 if (mConfig.mPriority != config.mPriority) {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700436 if (config.mPriority != INT_MAX && (*node) != nullptr) {
437 (*node)->setPriority(config.mPriority);
Wonsik Kima1335e12021-04-22 16:28:29 -0700438 }
439 mConfig.mPriority = config.mPriority;
440 }
441
Wonsik Kimbd557932019-07-02 15:51:20 -0700442 if (status.str().empty()) {
443 ALOGD("ISConfig not changed");
444 } else {
445 ALOGD("ISConfig%s", status.str().c_str());
446 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800447 return err;
448 }
449
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700450 void onInputBufferDone(c2_cntr64_t index) override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700451 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
452 if ((*node) == nullptr) {
453 return;
454 }
455 (*node)->onInputBufferDone(index);
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700456 }
457
Wonsik Kim1951d932024-05-23 22:59:00 +0000458 void onInputBufferEmptied() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700459 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
460 if ((*node) == nullptr) {
461 return;
462 }
463 (*node)->onInputBufferEmptied();
Wonsik Kim1951d932024-05-23 22:59:00 +0000464 }
465
Wonsik Kim673dd192021-01-29 14:58:12 -0800466 android_dataspace getDataspace() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700467 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
468 if ((*node) == nullptr) {
469 return HAL_DATASPACE_UNKNOWN;
470 }
471 return (*node)->getDataspace();
Wonsik Kim673dd192021-01-29 14:58:12 -0800472 }
473
Songyue Hanad01f6a2023-08-17 05:45:35 +0000474 uint32_t getPixelFormat() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700475 Mutexed<sp<C2OMXNode>>::Locked node(mNode);
476 if ((*node) == nullptr) {
477 return PIXEL_FORMAT_UNKNOWN;
478 }
479 return (*node)->getPixelFormat();
Songyue Hanad01f6a2023-08-17 05:45:35 +0000480 }
481
Pawin Vongmasa36653902018-11-15 00:10:25 -0800482private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700483 sp<HGraphicBufferSource> mSource;
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700484 Mutexed<sp<C2OMXNode>> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700485 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800486 uint32_t mWidth;
487 uint32_t mHeight;
488 Config mConfig;
489};
490
Sungtak Lee92bca442024-03-12 09:10:31 +0000491class AGraphicBufferSourceWrapper : public InputSurfaceWrapper {
492public:
493 AGraphicBufferSourceWrapper(
494 const std::shared_ptr<AGraphicBufferSource> &source,
495 uint32_t width,
496 uint32_t height,
497 uint64_t usage)
498 : mSource(source), mWidth(width), mHeight(height) {
499 mDataSpace = HAL_DATASPACE_BT709;
500 mConfig.mUsage = usage;
501 }
502 ~AGraphicBufferSourceWrapper() override = default;
503
504 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700505 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
506 *node = ::ndk::SharedRefBase::make<C2AidlNode>(comp);
507 (*node)->setFrameSize(mWidth, mHeight);
Sungtak Lee92bca442024-03-12 09:10:31 +0000508 // Usage is queried during configure(), so setting it beforehand.
509 uint64_t usage = mConfig.mUsage;
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700510 (void)(*node)->setConsumerUsage((int64_t)usage);
Sungtak Lee92bca442024-03-12 09:10:31 +0000511
512 return fromAidlStatus(mSource->configure(
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700513 (*node), static_cast<::aidl::android::hardware::graphics::common::Dataspace>(
Sungtak Lee92bca442024-03-12 09:10:31 +0000514 mDataSpace)));
515 }
516
517 void disconnect() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700518 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
519 if ((*node) == nullptr) {
Sungtak Lee92bca442024-03-12 09:10:31 +0000520 return;
521 }
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700522 std::shared_ptr<IAidlBufferSource> source = (*node)->getSource();
Sungtak Lee92bca442024-03-12 09:10:31 +0000523 if (source == nullptr) {
524 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
525 return;
526 }
527 (void)source->onStop();
528 (void)source->onRelease();
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700529 node->reset();
Sungtak Lee92bca442024-03-12 09:10:31 +0000530 }
531
532 status_t start() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700533 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
534 if ((*node) == nullptr) {
535 return NO_INIT;
536 }
537 std::shared_ptr<IAidlBufferSource> source = (*node)->getSource();
Sungtak Lee92bca442024-03-12 09:10:31 +0000538 if (source == nullptr) {
539 return NO_INIT;
540 }
541
542 size_t numSlots = 16;
543
544 IAidlNode::InputBufferParams param;
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700545 status_t err = fromAidlStatus((*node)->getInputBufferParams(&param));
Sungtak Lee92bca442024-03-12 09:10:31 +0000546 if (err == OK) {
547 numSlots = param.bufferCountActual;
548 }
549
550 for (size_t i = 0; i < numSlots; ++i) {
551 (void)source->onInputBufferAdded(i);
552 }
553
554 (void)source->onStart();
555 return OK;
556 }
557
558 status_t signalEndOfInputStream() override {
559 return fromAidlStatus(mSource->signalEndOfInputStream());
560 }
561
562 status_t configure(Config &config) {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700563 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
Sungtak Lee92bca442024-03-12 09:10:31 +0000564 std::stringstream status;
565 status_t err = OK;
566
567 // handle each configuration granually, in case we need to handle part of the configuration
568 // elsewhere
569
570 // TRICKY: we do not unset frame delay repeating
571 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
572 int64_t us = 1e6 / config.mMinFps + 0.5;
573 status_t res = fromAidlStatus(mSource->setRepeatPreviousFrameDelayUs(us));
574 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
575 if (res != OK) {
576 status << " (=> " << asString(res) << ")";
577 err = res;
578 }
579 mConfig.mMinFps = config.mMinFps;
580 }
581
582 // pts gap
583 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700584 if ((*node) != nullptr) {
Sungtak Lee92bca442024-03-12 09:10:31 +0000585 float gap = (config.mMinAdjustedFps > 0)
586 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
587 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
588 // float -> uint32_t is undefined if the value is negative.
589 // First convert to int32_t to ensure the expected behavior.
590 int32_t gapUs = int32_t(gap);
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700591 (void)(*node)->setAdjustTimestampGapUs(gapUs);
Sungtak Lee92bca442024-03-12 09:10:31 +0000592 }
593 }
594
595 // max fps
596 // TRICKY: we do not unset max fps to 0 unless using fixed fps
597 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
598 && config.mMaxFps != mConfig.mMaxFps) {
599 status_t res = fromAidlStatus(mSource->setMaxFps(config.mMaxFps));
600 status << " maxFps=" << config.mMaxFps;
601 if (res != OK) {
602 status << " (=> " << asString(res) << ")";
603 err = res;
604 }
605 mConfig.mMaxFps = config.mMaxFps;
606 }
607
608 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
609 status_t res = fromAidlStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
610 status << " timeOffset " << config.mTimeOffsetUs << "us";
611 if (res != OK) {
612 status << " (=> " << asString(res) << ")";
613 err = res;
614 }
615 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
616 }
617
618 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
619 status_t res =
620 fromAidlStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
621 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
622 if (res != OK) {
623 status << " (=> " << asString(res) << ")";
624 err = res;
625 }
626 mConfig.mCaptureFps = config.mCaptureFps;
627 mConfig.mCodedFps = config.mCodedFps;
628 }
629
630 if (config.mStartAtUs != mConfig.mStartAtUs
631 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
632 status_t res = fromAidlStatus(mSource->setStartTimeUs(config.mStartAtUs));
633 status << " start at " << config.mStartAtUs << "us";
634 if (res != OK) {
635 status << " (=> " << asString(res) << ")";
636 err = res;
637 }
638 mConfig.mStartAtUs = config.mStartAtUs;
639 mConfig.mStopped = config.mStopped;
640 }
641
642 // suspend-resume
643 if (config.mSuspended != mConfig.mSuspended) {
644 status_t res = fromAidlStatus(mSource->setSuspend(
645 config.mSuspended, config.mSuspendAtUs));
646 status << " " << (config.mSuspended ? "suspend" : "resume")
647 << " at " << config.mSuspendAtUs << "us";
648 if (res != OK) {
649 status << " (=> " << asString(res) << ")";
650 err = res;
651 }
652 mConfig.mSuspended = config.mSuspended;
653 mConfig.mSuspendAtUs = config.mSuspendAtUs;
654 }
655
656 if (config.mStopped != mConfig.mStopped && config.mStopped) {
657 status_t res = fromAidlStatus(mSource->setStopTimeUs(config.mStopAtUs));
658 status << " stop at " << config.mStopAtUs << "us";
659 if (res != OK) {
660 status << " (=> " << asString(res) << ")";
661 err = res;
662 } else {
663 status << " delayUs";
664 res = fromAidlStatus(mSource->getStopTimeOffsetUs(&config.mInputDelayUs));
665 if (res != OK) {
666 status << " (=> " << asString(res) << ")";
667 } else {
668 status << "=" << config.mInputDelayUs << "us";
669 }
670 mConfig.mInputDelayUs = config.mInputDelayUs;
671 }
672 mConfig.mStopAtUs = config.mStopAtUs;
673 mConfig.mStopped = config.mStopped;
674 }
675
676 // color aspects (android._color-aspects)
677
678 // consumer usage is queried earlier.
679
680 // priority
681 if (mConfig.mPriority != config.mPriority) {
682 if (config.mPriority != INT_MAX) {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700683 (*node)->setPriority(config.mPriority);
Sungtak Lee92bca442024-03-12 09:10:31 +0000684 }
685 mConfig.mPriority = config.mPriority;
686 }
687
688 if (status.str().empty()) {
689 ALOGD("ISConfig not changed");
690 } else {
691 ALOGD("ISConfig%s", status.str().c_str());
692 }
693 return err;
694 }
695
696 void onInputBufferDone(c2_cntr64_t index) override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700697 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
698 if ((*node) == nullptr) {
699 return;
700 }
701 (*node)->onInputBufferDone(index);
Sungtak Lee92bca442024-03-12 09:10:31 +0000702 }
703
Wonsik Kim1951d932024-05-23 22:59:00 +0000704 void onInputBufferEmptied() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700705 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
706 if ((*node) == nullptr) {
707 return;
708 }
709 (*node)->onInputBufferEmptied();
Wonsik Kim1951d932024-05-23 22:59:00 +0000710 }
711
Sungtak Lee92bca442024-03-12 09:10:31 +0000712 android_dataspace getDataspace() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700713 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
714 if ((*node) == nullptr) {
715 return HAL_DATASPACE_UNKNOWN;
716 }
717 return (*node)->getDataspace();
Sungtak Lee92bca442024-03-12 09:10:31 +0000718 }
719
720 uint32_t getPixelFormat() override {
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700721 Mutexed<std::shared_ptr<C2AidlNode>>::Locked node(mNode);
722 if ((*node) == nullptr) {
723 return PIXEL_FORMAT_UNKNOWN;
724 }
725 return (*node)->getPixelFormat();
Sungtak Lee92bca442024-03-12 09:10:31 +0000726 }
727
728private:
729 std::shared_ptr<AGraphicBufferSource> mSource;
Wonsik Kimd4ba8462024-07-12 11:05:48 -0700730 Mutexed<std::shared_ptr<C2AidlNode>> mNode;
Sungtak Lee92bca442024-03-12 09:10:31 +0000731 uint32_t mWidth;
732 uint32_t mHeight;
733 Config mConfig;
734};
735
Pawin Vongmasa36653902018-11-15 00:10:25 -0800736class Codec2ClientInterfaceWrapper : public C2ComponentStore {
737 std::shared_ptr<Codec2Client> mClient;
738
739public:
740 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
741 : mClient(client) { }
742
743 virtual ~Codec2ClientInterfaceWrapper() = default;
744
745 virtual c2_status_t config_sm(
746 const std::vector<C2Param *> &params,
747 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
748 return mClient->config(params, C2_MAY_BLOCK, failures);
749 };
750
751 virtual c2_status_t copyBuffer(
752 std::shared_ptr<C2GraphicBuffer>,
753 std::shared_ptr<C2GraphicBuffer>) {
754 return C2_OMITTED;
755 }
756
757 virtual c2_status_t createComponent(
758 C2String, std::shared_ptr<C2Component> *const component) {
759 component->reset();
760 return C2_OMITTED;
761 }
762
763 virtual c2_status_t createInterface(
764 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
765 interface->reset();
766 return C2_OMITTED;
767 }
768
769 virtual c2_status_t query_sm(
770 const std::vector<C2Param *> &stackParams,
771 const std::vector<C2Param::Index> &heapParamIndices,
772 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
773 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
774 }
775
776 virtual c2_status_t querySupportedParams_nb(
777 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
778 return mClient->querySupportedParams(params);
779 }
780
781 virtual c2_status_t querySupportedValues_sm(
782 std::vector<C2FieldSupportedValuesQuery> &fields) const {
783 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
784 }
785
786 virtual C2String getName() const {
787 return mClient->getName();
788 }
789
790 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
791 return mClient->getParamReflector();
792 }
793
794 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
795 return std::vector<std::shared_ptr<const C2Component::Traits>>();
796 }
797};
798
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800799void RevertOutputFormatIfNeeded(
800 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
801 // We used to not report changes to these keys to the client.
802 const static std::set<std::string> sIgnoredKeys({
803 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800804 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800805 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800806 KEY_MAX_WIDTH,
807 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800808 "csd-0",
809 "csd-1",
810 "csd-2",
811 });
812 if (currentFormat == oldFormat) {
813 return;
814 }
815 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
816 AMessage::Type type;
817 for (size_t i = diff->countEntries(); i > 0; --i) {
818 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
819 diff->removeEntryAt(i - 1);
820 }
821 }
822 if (diff->countEntries() == 0) {
823 currentFormat = oldFormat;
824 }
825}
826
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700827void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700828 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700829 const sp<AMessage> &outputFormat) {
830 if (mediaType == MIMETYPE_VIDEO_AVC) {
831 // Codec specific data should be SPS and PPS in a single buffer,
832 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
833 // We separate the two and put them into the output format
834 // under the keys "csd-0" and "csd-1".
835
836 unsigned csdIndex = 0;
837
838 const uint8_t *nalStart;
839 size_t nalSize;
840 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
841 sp<ABuffer> csd = new ABuffer(nalSize + 4);
842 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
843 memcpy(csd->data() + 4, nalStart, nalSize);
844
845 outputFormat->setBuffer(
846 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
847
848 ++csdIndex;
849 }
850
851 if (csdIndex != 2) {
852 ALOGW("Expected two NAL units from AVC codec config, but %u found",
853 csdIndex);
854 }
855 } else {
856 // For everything else we just stash the codec specific data into
857 // the output format as a single piece of csd under "csd-0".
858 sp<ABuffer> csd = new ABuffer(size);
859 memcpy(csd->data(), data, size);
860 csd->setRange(0, size);
861 outputFormat->setBuffer("csd-0", csd);
862 }
863}
864
Pawin Vongmasa36653902018-11-15 00:10:25 -0800865} // namespace
866
867// CCodec::ClientListener
868
869struct CCodec::ClientListener : public Codec2Client::Listener {
870
871 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
872
873 virtual void onWorkDone(
874 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800875 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800876 (void)component;
877 sp<CCodec> codec(mCodec.promote());
878 if (!codec) {
879 return;
880 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800881 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800882 }
883
884 virtual void onTripped(
885 const std::weak_ptr<Codec2Client::Component>& component,
886 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
887 ) override {
888 // TODO
889 (void)component;
890 (void)settingResult;
891 }
892
893 virtual void onError(
894 const std::weak_ptr<Codec2Client::Component>& component,
895 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800896 {
897 // Component is only used for reporting as we use a separate listener for each instance
898 std::shared_ptr<Codec2Client::Component> comp = component.lock();
899 if (!comp) {
900 ALOGD("Component died with error: 0x%x", errorCode);
901 } else {
902 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
903 }
904 }
905
906 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800907 // Note: for now we do not propagate the error code to MediaCodec
908 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800909 sp<CCodec> codec(mCodec.promote());
910 if (!codec || !codec->mCallback) {
911 return;
912 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800913 codec->mCallback->onError(
914 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
915 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800916 }
917
918 virtual void onDeath(
919 const std::weak_ptr<Codec2Client::Component>& component) override {
920 { // Log the death of the component.
921 std::shared_ptr<Codec2Client::Component> comp = component.lock();
922 if (!comp) {
923 ALOGE("Codec2 component died.");
924 } else {
925 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
926 }
927 }
928
929 // Report to MediaCodec.
930 sp<CCodec> codec(mCodec.promote());
931 if (!codec || !codec->mCallback) {
932 return;
933 }
934 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
935 }
936
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800937 virtual void onFrameRendered(uint64_t bufferQueueId,
938 int32_t slotId,
939 int64_t timestampNs) override {
940 // TODO: implement
941 (void)bufferQueueId;
942 (void)slotId;
943 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800944 }
945
946 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800947 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800948 sp<CCodec> codec(mCodec.promote());
949 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800950 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800951 }
952 }
953
954private:
955 wp<CCodec> mCodec;
956};
957
958// CCodecCallbackImpl
959
960class CCodecCallbackImpl : public CCodecCallback {
961public:
962 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
963 ~CCodecCallbackImpl() override = default;
964
965 void onError(status_t err, enum ActionCode actionCode) override {
966 mCodec->mCallback->onError(err, actionCode);
967 }
968
969 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
Brian Lindahlff74e9d2023-07-20 14:44:04 -0600970 mCodec->mCallback->onOutputFramesRendered({RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
Pawin Vongmasa36653902018-11-15 00:10:25 -0800971 }
972
Pawin Vongmasa36653902018-11-15 00:10:25 -0800973 void onOutputBuffersChanged() override {
974 mCodec->mCallback->onOutputBuffersChanged();
975 }
976
Guillaume Chelfi5ffbcb32021-04-12 14:23:43 +0200977 void onFirstTunnelFrameReady() override {
978 mCodec->mCallback->onFirstTunnelFrameReady();
979 }
980
Pawin Vongmasa36653902018-11-15 00:10:25 -0800981private:
982 CCodec *mCodec;
983};
984
985// CCodec
986
987CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700988 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
989 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800990}
991
992CCodec::~CCodec() {
993}
994
995std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
996 return mChannel;
997}
998
999status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
1000 status_t err = job();
1001 if (err != C2_OK) {
1002 mCallback->onError(err, ACTION_CODE_FATAL);
1003 }
1004 return err;
1005}
1006
1007void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
1008 auto setAllocating = [this] {
1009 Mutexed<State>::Locked state(mState);
1010 if (state->get() != RELEASED) {
1011 return INVALID_OPERATION;
1012 }
1013 state->set(ALLOCATING);
1014 return OK;
1015 };
1016 if (tryAndReportOnError(setAllocating) != OK) {
1017 return;
1018 }
1019
1020 sp<RefBase> codecInfo;
1021 CHECK(msg->findObject("codecInfo", &codecInfo));
1022 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
1023
1024 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
1025 allocMsg->setObject("codecInfo", codecInfo);
1026 allocMsg->post();
1027}
1028
1029void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
1030 if (codecInfo == nullptr) {
1031 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1032 return;
1033 }
1034 ALOGD("allocate(%s)", codecInfo->getCodecName());
1035 mClientListener.reset(new ClientListener(this));
1036
1037 AString componentName = codecInfo->getCodecName();
1038 std::shared_ptr<Codec2Client> client;
1039
1040 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -07001041 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001042 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001043 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001044 SetPreferredCodec2ComponentStore(
1045 std::make_shared<Codec2ClientInterfaceWrapper>(client));
1046 }
1047
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +09001048 std::shared_ptr<Codec2Client::Component> comp;
1049 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001050 componentName.c_str(),
1051 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +09001052 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001053 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +09001054 if (status != C2_OK) {
1055 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001056 Mutexed<State>::Locked state(mState);
1057 state->set(RELEASED);
1058 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +09001059 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001060 state.lock();
1061 return;
1062 }
1063 ALOGI("Created component [%s]", componentName.c_str());
1064 mChannel->setComponent(comp);
1065 auto setAllocated = [this, comp, client] {
1066 Mutexed<State>::Locked state(mState);
1067 if (state->get() != ALLOCATING) {
1068 state->set(RELEASED);
1069 return UNKNOWN_ERROR;
1070 }
1071 state->set(ALLOCATED);
1072 state->comp = comp;
1073 mClient = client;
1074 return OK;
1075 };
1076 if (tryAndReportOnError(setAllocated) != OK) {
1077 return;
1078 }
1079
1080 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001081 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1082 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001083 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001084 if (err != OK) {
1085 ALOGW("Failed to initialize configuration support");
1086 // TODO: report error once we complete implementation.
1087 }
1088 config->queryConfiguration(comp);
1089
1090 mCallback->onComponentAllocated(componentName.c_str());
1091}
1092
1093void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
1094 auto checkAllocated = [this] {
1095 Mutexed<State>::Locked state(mState);
1096 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
1097 };
1098 if (tryAndReportOnError(checkAllocated) != OK) {
1099 return;
1100 }
1101
1102 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
1103 msg->setMessage("format", format);
1104 msg->post();
1105}
1106
1107void CCodec::configure(const sp<AMessage> &msg) {
1108 std::shared_ptr<Codec2Client::Component> comp;
1109 auto checkAllocated = [this, &comp] {
1110 Mutexed<State>::Locked state(mState);
1111 if (state->get() != ALLOCATED) {
1112 state->set(RELEASED);
1113 return UNKNOWN_ERROR;
1114 }
1115 comp = state->comp;
1116 return OK;
1117 };
1118 if (tryAndReportOnError(checkAllocated) != OK) {
1119 return;
1120 }
1121
1122 auto doConfig = [msg, comp, this]() -> status_t {
1123 AString mime;
1124 if (!msg->findString("mime", &mime)) {
1125 return BAD_VALUE;
1126 }
1127
1128 int32_t encoder;
1129 if (!msg->findInt32("encoder", &encoder)) {
1130 encoder = false;
1131 }
1132
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001133 int32_t flags;
1134 if (!msg->findInt32("flags", &flags)) {
1135 return BAD_VALUE;
1136 }
1137
Pawin Vongmasa36653902018-11-15 00:10:25 -08001138 // TODO: read from intf()
1139 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
1140 return UNKNOWN_ERROR;
1141 }
1142
1143 int32_t storeMeta;
1144 if (encoder
1145 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
1146 && storeMeta != kMetadataBufferTypeInvalid) {
1147 if (storeMeta != kMetadataBufferTypeANWBuffer) {
1148 ALOGD("Only ANW buffers are supported for legacy metadata mode");
1149 return BAD_VALUE;
1150 }
1151 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
1152 }
1153
ted.sun765db4d2020-06-23 14:03:41 +08001154 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001155 sp<RefBase> obj;
1156 sp<Surface> surface;
1157 if (msg->findObject("native-window", &obj)) {
1158 surface = static_cast<Surface *>(obj.get());
Sungtak Lee214ce612023-11-01 10:01:13 +00001159 int32_t generation;
1160 (void)msg->findInt32("native-window-generation", &generation);
ted.sun765db4d2020-06-23 14:03:41 +08001161 // setup tunneled playback
1162 if (surface != nullptr) {
1163 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1164 const std::unique_ptr<Config> &config = *configLocked;
1165 if ((config->mDomain & Config::IS_DECODER)
1166 && (config->mDomain & Config::IS_VIDEO)) {
1167 int32_t tunneled;
1168 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
1169 ALOGI("Configuring TUNNELED video playback.");
1170
1171 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
1172 if (err != OK) {
1173 ALOGE("configureTunneledVideoPlayback failed!");
1174 return err;
1175 }
1176 config->mTunneled = true;
1177 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +01001178
1179 int32_t pushBlankBuffersOnStop = 0;
1180 if (msg->findInt32(KEY_PUSH_BLANK_BUFFERS_ON_STOP, &pushBlankBuffersOnStop)) {
1181 config->mPushBlankBuffersOnStop = pushBlankBuffersOnStop == 1;
1182 }
shuanglong.wang480a8362023-02-17 20:55:51 +08001183 // secure compoment or protected content default with
1184 // "push-blank-buffers-on-shutdown" flag
1185 if (!config->mPushBlankBuffersOnStop) {
1186 int32_t usageProtected;
1187 if (comp->getName().find(".secure") != std::string::npos) {
1188 config->mPushBlankBuffersOnStop = true;
1189 } else if (msg->findInt32("protected", &usageProtected) && usageProtected) {
1190 config->mPushBlankBuffersOnStop = true;
1191 }
1192 }
ted.sun765db4d2020-06-23 14:03:41 +08001193 }
1194 }
Sungtak Lee214ce612023-11-01 10:01:13 +00001195 setSurface(surface, (uint32_t)generation);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001196 }
1197
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001198 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1199 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001200 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001201 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
1202 ALOGD("[%s] buffers are %sbound to CCodec for this session",
1203 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001204
Wonsik Kim1114eea2019-02-25 14:35:24 -08001205 // Enforce required parameters
1206 int32_t i32;
1207 float flt;
1208 if (config->mDomain & Config::IS_AUDIO) {
1209 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
1210 ALOGD("sample rate is missing, which is required for audio components.");
1211 return BAD_VALUE;
1212 }
1213 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
1214 ALOGD("channel count is missing, which is required for audio components.");
1215 return BAD_VALUE;
1216 }
1217 if ((config->mDomain & Config::IS_ENCODER)
1218 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
1219 && !msg->findInt32(KEY_BIT_RATE, &i32)
1220 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
1221 ALOGD("bitrate is missing, which is required for audio encoders.");
1222 return BAD_VALUE;
1223 }
1224 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001225 int32_t width = 0;
1226 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -08001227 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001228 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -08001229 ALOGD("width is missing, which is required for image/video components.");
1230 return BAD_VALUE;
1231 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001232 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -08001233 ALOGD("height is missing, which is required for image/video components.");
1234 return BAD_VALUE;
1235 }
1236 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -07001237 int32_t mode = BITRATE_MODE_VBR;
1238 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -07001239 if (!msg->findInt32(KEY_QUALITY, &i32)) {
1240 ALOGD("quality is missing, which is required for video encoders in CQ.");
1241 return BAD_VALUE;
1242 }
1243 } else {
1244 if (!msg->findInt32(KEY_BIT_RATE, &i32)
1245 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
1246 ALOGD("bitrate is missing, which is required for video encoders.");
1247 return BAD_VALUE;
1248 }
Wonsik Kim1114eea2019-02-25 14:35:24 -08001249 }
1250 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
1251 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
1252 ALOGD("I frame interval is missing, which is required for video encoders.");
1253 return BAD_VALUE;
1254 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001255 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
1256 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
1257 ALOGD("frame rate is missing, which is required for video encoders.");
1258 return BAD_VALUE;
1259 }
Wonsik Kim1114eea2019-02-25 14:35:24 -08001260 }
1261 }
1262
Pawin Vongmasa36653902018-11-15 00:10:25 -08001263 /*
1264 * Handle input surface configuration
1265 */
1266 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1267 && (config->mDomain & Config::IS_ENCODER)) {
1268 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
1269 {
1270 config->mISConfig->mMinFps = 0;
1271 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001272 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001273 config->mISConfig->mMinFps = 1e6 / value;
1274 }
Wonsik Kim95ba0162019-03-19 15:51:54 -07001275 if (!msg->findFloat(
1276 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
1277 config->mISConfig->mMaxFps = -1;
1278 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001279 config->mISConfig->mMinAdjustedFps = 0;
1280 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -08001281 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001282 if (value < 0 && value >= INT32_MIN) {
1283 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001284 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001285 } else if (value > 0 && value <= INT32_MAX) {
1286 config->mISConfig->mMinAdjustedFps = 1e6 / value;
1287 }
1288 }
1289 }
1290
1291 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -07001292 bool captureFpsFound = false;
1293 double timeLapseFps;
1294 float captureRate;
1295 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
1296 config->mISConfig->mCaptureFps = timeLapseFps;
1297 captureFpsFound = true;
1298 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
1299 config->mISConfig->mCaptureFps = captureRate;
1300 captureFpsFound = true;
1301 }
1302 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001303 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
1304 }
1305 }
1306
1307 {
1308 config->mISConfig->mSuspended = false;
1309 config->mISConfig->mSuspendAtUs = -1;
1310 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001311 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001312 config->mISConfig->mSuspended = true;
1313 }
1314 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001315 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -07001316 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001317 }
1318
1319 /*
1320 * Handle desired color format.
1321 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001322 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001323 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001324 int32_t format = 0;
1325 // Query vendor format for Flexible YUV
1326 std::vector<std::unique_ptr<C2Param>> heapParams;
1327 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
Wonsik Kim50811882022-04-28 15:57:27 -07001328 int vendorSdkVersion = base::GetIntProperty(
1329 "ro.vendor.build.version.sdk", android_get_device_api_level());
guochuang709b48b2022-10-25 20:40:42 +08001330 if (mClient->query(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001331 {},
1332 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1333 C2_MAY_BLOCK,
1334 &heapParams) == C2_OK
1335 && heapParams.size() == 1u) {
1336 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1337 heapParams[0].get());
1338 } else {
1339 pixelFormatInfo = nullptr;
1340 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001341 // bit depth -> format
1342 std::map<uint32_t, uint32_t> flexPixelFormat;
1343 std::map<uint32_t, uint32_t> flexPlanarPixelFormat;
1344 std::map<uint32_t, uint32_t> flexSemiPlanarPixelFormat;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001345 if (pixelFormatInfo && *pixelFormatInfo) {
1346 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1347 const C2FlexiblePixelFormatDescriptorStruct &desc =
1348 pixelFormatInfo->m.values[i];
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001349 if (desc.subsampling != C2Color::YUV_420
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001350 // TODO(b/180076105): some device report wrong layout
1351 // || desc.layout == C2Color::INTERLEAVED_PACKED
1352 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1353 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1354 continue;
1355 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001356 if (flexPixelFormat.count(desc.bitDepth) == 0) {
1357 flexPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001358 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001359 if (desc.layout == C2Color::PLANAR_PACKED
1360 && flexPlanarPixelFormat.count(desc.bitDepth) == 0) {
1361 flexPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001362 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001363 if (desc.layout == C2Color::SEMIPLANAR_PACKED
1364 && flexSemiPlanarPixelFormat.count(desc.bitDepth) == 0) {
1365 flexSemiPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001366 }
1367 }
1368 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001369 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001370 // Also handle default color format (encoders require color format, so this is only
1371 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001372 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001373 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001374 const char *prefix = "";
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001375 if (flexSemiPlanarPixelFormat.count(8) != 0) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001376 format = COLOR_FormatYUV420SemiPlanar;
1377 prefix = "semi-";
1378 } else {
1379 format = COLOR_FormatYUV420Planar;
1380 }
1381 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1382 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001383 } else {
1384 format = COLOR_FormatSurface;
1385 }
1386 defaultColorFormat = format;
1387 }
1388 } else {
1389 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001390 if (vendorSdkVersion < __ANDROID_API_S__ &&
Taehwan Kim43e715d2022-09-22 12:04:59 +09001391 (format == COLOR_FormatYUV420Planar ||
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001392 format == COLOR_FormatYUV420PackedPlanar ||
1393 format == COLOR_FormatYUV420SemiPlanar ||
1394 format == COLOR_FormatYUV420PackedSemiPlanar)) {
1395 // pre-S framework used to map these color formats into YV12.
1396 // Codecs from older vendor partition may be relying on
1397 // this assumption.
1398 format = HAL_PIXEL_FORMAT_YV12;
1399 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001400 switch (format) {
1401 case COLOR_FormatYUV420Flexible:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001402 format = COLOR_FormatYUV420Planar;
1403 if (flexPixelFormat.count(8) != 0) {
1404 format = flexPixelFormat[8];
1405 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001406 break;
1407 case COLOR_FormatYUV420Planar:
1408 case COLOR_FormatYUV420PackedPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001409 if (flexPlanarPixelFormat.count(8) != 0) {
1410 format = flexPlanarPixelFormat[8];
1411 } else if (flexPixelFormat.count(8) != 0) {
1412 format = flexPixelFormat[8];
1413 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001414 break;
1415 case COLOR_FormatYUV420SemiPlanar:
1416 case COLOR_FormatYUV420PackedSemiPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001417 if (flexSemiPlanarPixelFormat.count(8) != 0) {
1418 format = flexSemiPlanarPixelFormat[8];
1419 } else if (flexPixelFormat.count(8) != 0) {
1420 format = flexPixelFormat[8];
1421 }
1422 break;
1423 case COLOR_FormatYUVP010:
1424 format = COLOR_FormatYUVP010;
1425 if (flexSemiPlanarPixelFormat.count(10) != 0) {
1426 format = flexSemiPlanarPixelFormat[10];
1427 } else if (flexPixelFormat.count(10) != 0) {
1428 format = flexPixelFormat[10];
1429 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001430 break;
1431 default:
1432 // No-op
1433 break;
1434 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001435 }
1436 }
1437
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001438 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001439 msg->setInt32("android._color-format", format);
1440 }
1441 }
1442
Wonsik Kim77e97c72021-01-20 10:33:22 -08001443 /*
1444 * Handle dataspace
1445 */
1446 int32_t usingRecorder;
1447 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1448 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1449 int32_t width, height;
1450 if (msg->findInt32("width", &width)
1451 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001452 ColorAspects aspects;
1453 getColorAspectsFromFormat(msg, aspects);
1454 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001455 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001456 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1457 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001458 }
1459 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1460 ALOGD("setting dataspace to %x", dataSpace);
1461 }
1462
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001463 int32_t subscribeToAllVendorParams;
1464 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1465 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1466 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1467 }
1468 }
1469
Ram Mohan16511072023-12-11 19:41:31 +05301470 /*
1471 * configure mock region of interest if Feature_Roi is enabled
1472 */
1473 if (android::media::codec::provider_->region_of_interest()
1474 && android::media::codec::provider_->region_of_interest_support()) {
1475 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
1476 int32_t enableRoi;
1477 if (msg->findInt32("feature-region-of-interest", &enableRoi) && enableRoi != 0) {
1478 if (!msg->contains(PARAMETER_KEY_QP_OFFSET_MAP) &&
1479 !msg->contains(PARAMETER_KEY_QP_OFFSET_RECTS)) {
1480 msg->setString(PARAMETER_KEY_QP_OFFSET_RECTS,
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05301481 AStringPrintf("%d,%d-%d,%d=%d;", 0, 0, height, width, 0));
Ram Mohan16511072023-12-11 19:41:31 +05301482 }
1483 }
1484 }
1485 }
1486
Pawin Vongmasa36653902018-11-15 00:10:25 -08001487 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001488 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1489 // the behavior here.
1490 sp<AMessage> sdkParams = msg;
1491 int32_t videoBitrate;
1492 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1493 sdkParams = msg->dup();
1494 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1495 }
ted.sun765db4d2020-06-23 14:03:41 +08001496 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001497 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001498 if (err != OK) {
1499 ALOGW("failed to convert configuration to c2 params");
1500 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001501
1502 int32_t maxBframes = 0;
1503 if ((config->mDomain & Config::IS_ENCODER)
1504 && (config->mDomain & Config::IS_VIDEO)
1505 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1506 && maxBframes > 0) {
1507 std::unique_ptr<C2StreamGopTuning::output> gop =
1508 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1509 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1510 gop->m.values[1] = {
1511 C2Config::picture_type_t(P_FRAME | B_FRAME),
1512 uint32_t(maxBframes)
1513 };
1514 configUpdate.push_back(std::move(gop));
1515 }
1516
Ray Essicka0ae6972021-03-10 19:40:01 -08001517 if ((config->mDomain & Config::IS_ENCODER)
1518 && (config->mDomain & Config::IS_VIDEO)) {
1519 // we may not use all 3 of these entries
1520 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1521 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1522 0u /* stream */);
1523
1524 int ix = 0;
1525
1526 int32_t iMax = INT32_MAX;
1527 int32_t iMin = INT32_MIN;
1528 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1529 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1530 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1531 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1532 }
1533
1534 int32_t pMax = INT32_MAX;
1535 int32_t pMin = INT32_MIN;
1536 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1537 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1538 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1539 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1540 }
1541
1542 int32_t bMax = INT32_MAX;
1543 int32_t bMin = INT32_MIN;
1544 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1545 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1546 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1547 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1548 }
1549
1550 // adjust to reflect actual use.
1551 qp->setFlexCount(ix);
1552
1553 configUpdate.push_back(std::move(qp));
1554 }
1555
Wonsik Kima1335e12021-04-22 16:28:29 -07001556 int32_t background = 0;
1557 if ((config->mDomain & Config::IS_VIDEO)
1558 && msg->findInt32("android._background-mode", &background)
1559 && background) {
1560 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1561 if (config->mISConfig) {
1562 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1563 }
1564 }
1565
Pawin Vongmasa36653902018-11-15 00:10:25 -08001566 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1567 if (err != OK) {
1568 ALOGW("failed to configure c2 params");
1569 return err;
1570 }
1571
1572 std::vector<std::unique_ptr<C2Param>> params;
1573 C2StreamUsageTuning::input usage(0u, 0u);
1574 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001575 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001576
Wonsik Kim3baecda2021-02-07 22:19:56 -08001577 C2Param::Index colorAspectsRequestIndex =
1578 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001579 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001580 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001581 };
Chaejung Lim86c22dc2021-12-23 00:41:05 -08001582 int32_t colorTransferRequest = 0;
1583 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1584 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1585 colorTransferRequest = 0;
1586 }
1587 c2_status_t c2err = C2_OK;
1588 if (colorTransferRequest != 0) {
1589 c2err = comp->query(
1590 { &usage, &maxInputSize, &prepend },
1591 indices,
1592 C2_DONT_BLOCK,
1593 &params);
1594 } else {
1595 c2err = comp->query(
1596 { &usage, &maxInputSize, &prepend },
1597 {},
1598 C2_DONT_BLOCK,
1599 &params);
1600 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001601 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1602 ALOGE("Failed to query component interface: %d", c2err);
1603 return UNKNOWN_ERROR;
1604 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001605 if (usage) {
1606 if (usage.value & C2MemoryUsage::CPU_READ) {
1607 config->mInputFormat->setInt32("using-sw-read-often", true);
1608 }
1609 if (config->mISConfig) {
1610 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1611 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1612 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001613 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001614 }
1615
1616 // NOTE: we don't blindly use client specified input size if specified as clients
1617 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1618 // client specified size is only used to ask for bigger buffers than component suggested
1619 // size.
1620 int32_t clientInputSize = 0;
1621 bool clientSpecifiedInputSize =
1622 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1623 // TEMP: enforce minimum buffer size of 1MB for video decoders
1624 // and 16K / 4K for audio encoders/decoders
1625 if (maxInputSize.value == 0) {
1626 if (config->mDomain & Config::IS_AUDIO) {
1627 maxInputSize.value = encoder ? 16384 : 4096;
1628 } else if (!encoder) {
1629 maxInputSize.value = 1048576u;
1630 }
1631 }
1632
1633 // verify that CSD fits into this size (if defined)
1634 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1635 sp<ABuffer> csd;
1636 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1637 if (csd && csd->size() > maxInputSize.value) {
1638 maxInputSize.value = csd->size();
1639 }
1640 }
1641 }
1642
1643 // TODO: do this based on component requiring linear allocator for input
1644 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1645 if (clientSpecifiedInputSize) {
1646 // Warn that we're overriding client's max input size if necessary.
1647 if ((uint32_t)clientInputSize < maxInputSize.value) {
1648 ALOGD("client requested max input size %d, which is smaller than "
1649 "what component recommended (%u); overriding with component "
1650 "recommendation.", clientInputSize, maxInputSize.value);
1651 ALOGW("This behavior is subject to change. It is recommended that "
1652 "app developers double check whether the requested "
1653 "max input size is in reasonable range.");
1654 } else {
1655 maxInputSize.value = clientInputSize;
1656 }
1657 }
1658 // Pass max input size on input format to the buffer channel (if supplied by the
1659 // component or by a default)
1660 if (maxInputSize.value) {
1661 config->mInputFormat->setInt32(
1662 KEY_MAX_INPUT_SIZE,
1663 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1664 }
1665 }
1666
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001667 int32_t clientPrepend;
1668 if ((config->mDomain & Config::IS_VIDEO)
1669 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001670 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001671 && clientPrepend
1672 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001673 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001674 return BAD_VALUE;
1675 }
1676
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001677 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001678 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1679 // propagate HDR static info to output format for both encoders and decoders
1680 // if component supports this info, we will update from component, but only the raw port,
1681 // so don't propagate if component already filled it in.
1682 sp<ABuffer> hdrInfo;
1683 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1684 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1685 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1686 }
1687
1688 // Set desired color format from configuration parameter
1689 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001690 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1691 format = defaultColorFormat;
1692 }
1693 if (config->mDomain & Config::IS_ENCODER) {
1694 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001695 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1696 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001697 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001698 } else {
1699 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001700 }
1701 }
1702
1703 // propagate encoder delay and padding to output format
1704 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1705 int delay = 0;
1706 if (msg->findInt32("encoder-delay", &delay)) {
1707 config->mOutputFormat->setInt32("encoder-delay", delay);
1708 }
1709 int padding = 0;
1710 if (msg->findInt32("encoder-padding", &padding)) {
1711 config->mOutputFormat->setInt32("encoder-padding", padding);
1712 }
1713 }
1714
Pawin Vongmasa36653902018-11-15 00:10:25 -08001715 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001716 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001717 int32_t mask;
1718 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1719 if (config->mDomain & Config::IS_ENCODER) {
1720 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1721 } else {
1722 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1723 }
1724 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001725
1726 // set PCM encoding
1727 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1728 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1729 if (encoder) {
1730 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1731 } else {
1732 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1733 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001734 }
1735
Wonsik Kim3baecda2021-02-07 22:19:56 -08001736 std::unique_ptr<C2Param> colorTransferRequestParam;
1737 for (std::unique_ptr<C2Param> &param : params) {
1738 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1739 ALOGI("found color transfer request param");
1740 colorTransferRequestParam = std::move(param);
1741 }
1742 }
Wonsik Kim3baecda2021-02-07 22:19:56 -08001743
1744 if (colorTransferRequest != 0) {
1745 if (colorTransferRequestParam && *colorTransferRequestParam) {
1746 C2StreamColorAspectsInfo::output *info =
1747 static_cast<C2StreamColorAspectsInfo::output *>(
1748 colorTransferRequestParam.get());
1749 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1750 colorTransferRequest = 0;
1751 }
1752 } else {
1753 colorTransferRequest = 0;
1754 }
1755 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1756 }
1757
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001758 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1759 // Need to get stride/vstride
1760 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1761 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1762 // TODO: retrieve these values without allocating a buffer.
1763 // Currently allocating a buffer is necessary to retrieve the layout.
1764 int64_t blockUsage =
1765 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1766 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
Harish Mahendrakarf6b3e5e2024-03-21 21:04:28 +00001767 align(width, 2), align(height, 2), componentColorFormat, blockUsage,
1768 {comp->getName()});
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001769 sp<GraphicBlockBuffer> buffer;
1770 if (block) {
1771 buffer = GraphicBlockBuffer::Allocate(
1772 config->mInputFormat,
1773 block,
1774 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1775 } else {
1776 ALOGD("Failed to allocate a graphic block "
1777 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1778 width, height, pixelFormat, (long long)blockUsage);
1779 // This means that byte buffer mode is not supported in this configuration
1780 // anyway. Skip setting stride/vstride to input format.
1781 }
1782 if (buffer) {
1783 sp<ABuffer> imageData = buffer->getImageData();
1784 MediaImage2 *img = nullptr;
1785 if (imageData && imageData->data()
1786 && imageData->size() >= sizeof(MediaImage2)) {
1787 img = (MediaImage2*)imageData->data();
1788 }
1789 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1790 int32_t stride = img->mPlane[0].mRowInc;
1791 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1792 if (img->mNumPlanes > 1 && stride > 0) {
1793 int64_t offsetDelta =
1794 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1795 if (offsetDelta % stride == 0) {
1796 int32_t vstride = int32_t(offsetDelta / stride);
1797 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1798 } else {
1799 ALOGD("Cannot report accurate slice height: "
1800 "offsetDelta = %lld stride = %d",
1801 (long long)offsetDelta, stride);
1802 }
1803 }
1804 }
1805 }
1806 }
1807 }
1808
Wonsik Kimec585c32021-10-01 01:11:00 -07001809 if (config->mTunneled) {
1810 config->mOutputFormat->setInt32("android._tunneled", 1);
1811 }
1812
Yushin Cho91873b52021-12-21 04:08:35 -08001813 // Convert an encoding statistics level to corresponding encoding statistics
1814 // kinds
1815 int32_t encodingStatisticsLevel = VIDEO_ENCODING_STATISTICS_LEVEL_NONE;
1816 if ((config->mDomain & Config::IS_ENCODER)
1817 && (config->mDomain & Config::IS_VIDEO)
1818 && msg->findInt32(KEY_VIDEO_ENCODING_STATISTICS_LEVEL, &encodingStatisticsLevel)) {
1819 // Higher level include all the enc stats belong to lower level.
1820 switch (encodingStatisticsLevel) {
1821 // case VIDEO_ENCODING_STATISTICS_LEVEL_2: // reserved for the future level 2
1822 // with more enc stat kinds
1823 // Future extended encoding statistics for the level 2 should be added here
1824 case VIDEO_ENCODING_STATISTICS_LEVEL_1:
Wonsik Kimeebab652022-06-02 13:01:55 -07001825 config->subscribeToConfigUpdate(
1826 comp,
1827 {
1828 C2AndroidStreamAverageBlockQuantizationInfo::output::PARAM_TYPE,
1829 C2StreamPictureTypeInfo::output::PARAM_TYPE,
1830 });
Yushin Cho91873b52021-12-21 04:08:35 -08001831 break;
1832 case VIDEO_ENCODING_STATISTICS_LEVEL_NONE:
1833 break;
1834 }
1835 }
1836 ALOGD("encoding statistics level = %d", encodingStatisticsLevel);
1837
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001838 ALOGD("setup formats input: %s",
1839 config->mInputFormat->debugString().c_str());
1840 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001841 config->mOutputFormat->debugString().c_str());
1842 return OK;
1843 };
1844 if (tryAndReportOnError(doConfig) != OK) {
1845 return;
1846 }
1847
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001848 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1849 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001850
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001851 config->queryConfiguration(comp);
1852
Songyue Han1e6769b2023-08-30 18:09:27 +00001853 mMetrics = new AMessage;
1854 mChannel->resetBuffersPixelFormat((config->mDomain & Config::IS_ENCODER) ? true : false);
1855
Pawin Vongmasa36653902018-11-15 00:10:25 -08001856 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1857}
1858
1859void CCodec::initiateCreateInputSurface() {
1860 status_t err = [this] {
1861 Mutexed<State>::Locked state(mState);
1862 if (state->get() != ALLOCATED) {
1863 return UNKNOWN_ERROR;
1864 }
1865 // TODO: read it from intf() properly.
1866 if (state->comp->getName().find("encoder") == std::string::npos) {
1867 return INVALID_OPERATION;
1868 }
1869 return OK;
1870 }();
1871 if (err != OK) {
1872 mCallback->onInputSurfaceCreationFailed(err);
1873 return;
1874 }
1875
1876 (new AMessage(kWhatCreateInputSurface, this))->post();
1877}
1878
Lajos Molnar47118272019-01-31 16:28:04 -08001879sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1880 using namespace android::hardware::media::omx::V1_0;
1881 using namespace android::hardware::media::omx::V1_0::utils;
1882 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1883 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1884 android::sp<IOmx> omx = IOmx::getService();
Sungtak Lee47dcb482022-04-15 10:47:08 -07001885 if (omx == nullptr) {
1886 return nullptr;
1887 }
Lajos Molnar47118272019-01-31 16:28:04 -08001888 typedef android::hardware::graphics::bufferqueue::V1_0::
1889 IGraphicBufferProducer HGraphicBufferProducer;
1890 typedef android::hardware::media::omx::V1_0::
1891 IGraphicBufferSource HGraphicBufferSource;
1892 OmxStatus s;
1893 android::sp<HGraphicBufferProducer> gbp;
1894 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001895
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001896 using ::android::hardware::Return;
1897 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001898 [&s, &gbp, &gbs](
1899 OmxStatus status,
1900 const android::sp<HGraphicBufferProducer>& producer,
1901 const android::sp<HGraphicBufferSource>& source) {
1902 s = status;
1903 gbp = producer;
1904 gbs = source;
1905 });
1906 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001907 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001908 }
1909
1910 return nullptr;
1911}
1912
1913sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1914 sp<PersistentSurface> surface(CreateInputSurface());
1915
1916 if (surface == nullptr) {
1917 surface = CreateOmxInputSurface();
1918 }
1919
1920 return surface;
1921}
1922
Pawin Vongmasa36653902018-11-15 00:10:25 -08001923void CCodec::createInputSurface() {
1924 status_t err;
1925 sp<IGraphicBufferProducer> bufferProducer;
1926
Pawin Vongmasa36653902018-11-15 00:10:25 -08001927 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001928 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001929 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001930 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1931 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001932 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001933 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001934 }
1935
Lajos Molnar47118272019-01-31 16:28:04 -08001936 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Sungtak Lee92bca442024-03-12 09:10:31 +00001937 if (persistentSurface->isTargetAidl()) {
1938 ::ndk::SpAIBinder aidlTarget = persistentSurface->getAidlTarget();
1939 std::shared_ptr<AGraphicBufferSource> gbs = AGraphicBufferSource::fromBinder(aidlTarget);
1940 if (gbs) {
1941 int32_t width = 0;
1942 (void)outputFormat->findInt32("width", &width);
1943 int32_t height = 0;
1944 (void)outputFormat->findInt32("height", &height);
1945 err = setupInputSurface(std::make_shared<AGraphicBufferSourceWrapper>(
1946 gbs, width, height, usage));
1947 bufferProducer = persistentSurface->getBufferProducer();
1948 } else {
1949 ALOGE("Corrupted input surface(aidl)");
1950 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1951 return;
1952 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001953 } else {
Sungtak Lee92bca442024-03-12 09:10:31 +00001954 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1955 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1956 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1957
1958 if (hidlInputSurface) {
1959 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1960 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
1961 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1962 inputSurface));
1963 bufferProducer = inputSurface->getGraphicBufferProducer();
1964 } else if (gbs) {
1965 int32_t width = 0;
1966 (void)outputFormat->findInt32("width", &width);
1967 int32_t height = 0;
1968 (void)outputFormat->findInt32("height", &height);
1969 err = setupInputSurface(std::make_shared<HGraphicBufferSourceWrapper>(
1970 gbs, width, height, usage));
1971 bufferProducer = persistentSurface->getBufferProducer();
1972 } else {
1973 ALOGE("Corrupted input surface");
1974 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1975 return;
1976 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001977 }
1978
1979 if (err != OK) {
1980 ALOGE("Failed to set up input surface: %d", err);
1981 mCallback->onInputSurfaceCreationFailed(err);
1982 return;
1983 }
1984
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001985 // Formats can change after setupInputSurface
1986 sp<AMessage> inputFormat;
1987 {
1988 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1989 const std::unique_ptr<Config> &config = *configLocked;
1990 inputFormat = config->mInputFormat;
1991 outputFormat = config->mOutputFormat;
1992 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001993 mCallback->onInputSurfaceCreated(
1994 inputFormat,
1995 outputFormat,
1996 new BufferProducerWrapper(bufferProducer));
1997}
1998
1999status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002000 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2001 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002002 config->mUsingSurface = true;
2003
2004 // we are now using surface - apply default color aspects to input format - as well as
2005 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002006 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002007
2008 // configure dataspace
2009 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
Wonsik Kim66b19552021-08-02 16:07:49 -07002010
2011 // The output format contains app-configured color aspects, and the input format
2012 // has the default color aspects. Use the default for the unspecified params.
2013 ColorAspects inputColorAspects, colorAspects;
2014 getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
2015 getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
2016 if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
2017 colorAspects.mRange = inputColorAspects.mRange;
2018 }
2019 if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
2020 colorAspects.mPrimaries = inputColorAspects.mPrimaries;
2021 }
2022 if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
2023 colorAspects.mTransfer = inputColorAspects.mTransfer;
2024 }
2025 if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
2026 colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
2027 }
2028 android_dataspace dataSpace = getDataSpaceForColorAspects(
2029 colorAspects, /* mayExtend = */ false);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002030 surface->setDataSpace(dataSpace);
Wonsik Kim66b19552021-08-02 16:07:49 -07002031 setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
2032 config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
2033
2034 ALOGD("input format %s to %s",
2035 inputFormatChanged ? "changed" : "unchanged",
2036 config->mInputFormat->debugString().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002037
2038 status_t err = mChannel->setInputSurface(surface);
2039 if (err != OK) {
2040 // undo input format update
2041 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002042 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002043 return err;
2044 }
2045 config->mInputSurface = surface;
2046
2047 if (config->mISConfig) {
2048 surface->configure(*config->mISConfig);
2049 } else {
2050 ALOGD("ISConfig: no configuration");
2051 }
2052
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002053 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002054}
2055
2056void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
2057 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
2058 msg->setObject("surface", surface);
2059 msg->post();
2060}
2061
2062void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002063 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07002064 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002065 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002066 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2067 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002068 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07002069 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002070 }
Sungtak Lee92bca442024-03-12 09:10:31 +00002071 if (surface->isTargetAidl()) {
2072 ::ndk::SpAIBinder aidlTarget = surface->getAidlTarget();
2073 std::shared_ptr<AGraphicBufferSource> gbs = AGraphicBufferSource::fromBinder(aidlTarget);
2074 if (gbs) {
2075 int32_t width = 0;
2076 (void)outputFormat->findInt32("width", &width);
2077 int32_t height = 0;
2078 (void)outputFormat->findInt32("height", &height);
2079
2080 status_t err = setupInputSurface(std::make_shared<AGraphicBufferSourceWrapper>(
2081 gbs, width, height, usage));
2082 if (err != OK) {
2083 ALOGE("Failed to set up input surface(aidl): %d", err);
2084 mCallback->onInputSurfaceDeclined(err);
2085 return;
2086 }
2087 } else {
2088 ALOGE("Failed to set input surface(aidl): Corrupted surface.");
2089 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002090 return;
2091 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002092 } else {
Sungtak Lee92bca442024-03-12 09:10:31 +00002093 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
2094 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
2095 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
2096 if (inputSurface) {
2097 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
2098 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
2099 if (err != OK) {
2100 ALOGE("Failed to set up input surface: %d", err);
2101 mCallback->onInputSurfaceDeclined(err);
2102 return;
2103 }
2104 } else if (gbs) {
2105 int32_t width = 0;
2106 (void)outputFormat->findInt32("width", &width);
2107 int32_t height = 0;
2108 (void)outputFormat->findInt32("height", &height);
2109 status_t err = setupInputSurface(std::make_shared<HGraphicBufferSourceWrapper>(
2110 gbs, width, height, usage));
2111 if (err != OK) {
2112 ALOGE("Failed to set up input surface: %d", err);
2113 mCallback->onInputSurfaceDeclined(err);
2114 return;
2115 }
2116 } else {
2117 ALOGE("Failed to set input surface: Corrupted surface.");
2118 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
2119 return;
2120 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002121 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07002122 // Formats can change after setupInputSurface
2123 sp<AMessage> inputFormat;
2124 {
2125 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2126 const std::unique_ptr<Config> &config = *configLocked;
2127 inputFormat = config->mInputFormat;
2128 outputFormat = config->mOutputFormat;
2129 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002130 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
2131}
2132
2133void CCodec::initiateStart() {
2134 auto setStarting = [this] {
2135 Mutexed<State>::Locked state(mState);
2136 if (state->get() != ALLOCATED) {
2137 return UNKNOWN_ERROR;
2138 }
2139 state->set(STARTING);
2140 return OK;
2141 };
2142 if (tryAndReportOnError(setStarting) != OK) {
2143 return;
2144 }
2145
2146 (new AMessage(kWhatStart, this))->post();
2147}
2148
2149void CCodec::start() {
2150 std::shared_ptr<Codec2Client::Component> comp;
2151 auto checkStarting = [this, &comp] {
2152 Mutexed<State>::Locked state(mState);
2153 if (state->get() != STARTING) {
2154 return UNKNOWN_ERROR;
2155 }
2156 comp = state->comp;
2157 return OK;
2158 };
2159 if (tryAndReportOnError(checkStarting) != OK) {
2160 return;
2161 }
2162
2163 c2_status_t err = comp->start();
2164 if (err != C2_OK) {
2165 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
2166 ACTION_CODE_FATAL);
2167 return;
2168 }
Wonsik Kimd55ed3b2023-06-22 14:42:17 -07002169
2170 // clear the deadline after the component starts
2171 setDeadline(TimePoint::max(), 0ms, "none");
2172
Pawin Vongmasa36653902018-11-15 00:10:25 -08002173 sp<AMessage> inputFormat;
2174 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002175 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002176 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002177 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002178 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2179 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002180 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08002181 // start triggers format dup
2182 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002183 if (config->mInputSurface) {
2184 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08002185 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002186 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002187 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002188 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002189 if (err2 != OK) {
2190 mCallback->onError(err2, ACTION_CODE_FATAL);
2191 return;
2192 }
Arun Johnson106fe7a2023-04-26 17:49:43 +00002193
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002194 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002195 if (err2 != OK) {
2196 mCallback->onError(err2, ACTION_CODE_FATAL);
2197 return;
2198 }
2199
2200 auto setRunning = [this] {
2201 Mutexed<State>::Locked state(mState);
2202 if (state->get() != STARTING) {
2203 return UNKNOWN_ERROR;
2204 }
2205 state->set(RUNNING);
2206 return OK;
2207 };
2208 if (tryAndReportOnError(setRunning) != OK) {
2209 return;
2210 }
Arun Johnson5997bb02022-04-01 19:35:44 +00002211
Wonsik Kim34b28b42022-05-20 15:49:32 -07002212 // preparation of input buffers may not succeed due to the lack of
2213 // memory; returning correct error code (NO_MEMORY) as an error allows
2214 // MediaCodec to try reclaim and restart codec gracefully.
2215 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
2216 err2 = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
2217 if (err2 != OK) {
2218 ALOGE("Initial preparation for Input Buffers failed");
2219 mCallback->onError(err2, ACTION_CODE_FATAL);
2220 return;
2221 }
2222
Pawin Vongmasa36653902018-11-15 00:10:25 -08002223 mCallback->onStartCompleted();
2224
Wonsik Kim34b28b42022-05-20 15:49:32 -07002225 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002226}
2227
2228void CCodec::initiateShutdown(bool keepComponentAllocated) {
2229 if (keepComponentAllocated) {
2230 initiateStop();
2231 } else {
2232 initiateRelease();
2233 }
2234}
2235
2236void CCodec::initiateStop() {
2237 {
2238 Mutexed<State>::Locked state(mState);
2239 if (state->get() == ALLOCATED
2240 || state->get() == RELEASED
2241 || state->get() == STOPPING
2242 || state->get() == RELEASING) {
2243 // We're already stopped, released, or doing it right now.
2244 state.unlock();
2245 mCallback->onStopCompleted();
2246 state.lock();
2247 return;
2248 }
2249 state->set(STOPPING);
2250 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002251 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00002252 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
2253 sp<AMessage> stopMessage(new AMessage(kWhatStop, this));
2254 stopMessage->setInt32("pushBlankBuffer", pushBlankBuffer);
2255 stopMessage->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002256}
2257
Sungtak Lee99144332023-01-26 11:03:14 +00002258void CCodec::stop(bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002259 std::shared_ptr<Codec2Client::Component> comp;
2260 {
2261 Mutexed<State>::Locked state(mState);
2262 if (state->get() == RELEASING) {
2263 state.unlock();
2264 // We're already stopped or release is in progress.
2265 mCallback->onStopCompleted();
2266 state.lock();
2267 return;
2268 } else if (state->get() != STOPPING) {
2269 state.unlock();
2270 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2271 state.lock();
2272 return;
2273 }
2274 comp = state->comp;
2275 }
Sungtak Leec0c05962023-10-25 08:14:13 +00002276
2277 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->stop().
2278 // But in the case some HAL implementations hang forever on comp->stop().
2279 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
2280 // completing stop()).
2281 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
2282 // prior to comp->stop().
2283 // See also b/300350761.
Sungtak Lee34402ae2024-05-07 19:51:28 +00002284 //
2285 // The workaround is no longer needed with fetchGraphicBlock & C2Fence changes.
Sungtak Leeb7b1cf42024-05-14 22:45:35 +00002286 // so we are reverting back to the logical sequence of the operations when
2287 // AIDL HALs are selected.
2288 // When the HIDL HALs are selected, we retained workaround(the reversed
2289 // order) as default in order to keep legacy behavior.
2290 bool stopHalBeforeSurface =
2291 Codec2Client::IsAidlSelected() ||
2292 property_get_bool("debug.codec2.stop_hal_before_surface", false);
Sungtak Lee34402ae2024-05-07 19:51:28 +00002293 status_t err = C2_OK;
Sungtak Leeb7b1cf42024-05-14 22:45:35 +00002294 if (stopHalBeforeSurface && android::media::codec::provider_->stop_hal_before_surface()) {
Sungtak Lee34402ae2024-05-07 19:51:28 +00002295 err = comp->stop();
2296 mChannel->stopUseOutputSurface(pushBlankBuffer);
2297 } else {
2298 mChannel->stopUseOutputSurface(pushBlankBuffer);
2299 err = comp->stop();
2300 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002301 if (err != C2_OK) {
2302 // TODO: convert err into status_t
2303 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2304 }
2305
2306 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002307 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2308 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002309 if (config->mInputSurface) {
2310 config->mInputSurface->disconnect();
2311 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08002312 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002313 }
2314 }
2315 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002316 Mutexed<State>::Locked state(mState);
2317 if (state->get() == STOPPING) {
2318 state->set(ALLOCATED);
2319 }
2320 }
2321 mCallback->onStopCompleted();
2322}
2323
2324void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002325 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002326 {
2327 Mutexed<State>::Locked state(mState);
2328 if (state->get() == RELEASED || state->get() == RELEASING) {
2329 // We're already released or doing it right now.
2330 if (sendCallback) {
2331 state.unlock();
2332 mCallback->onReleaseCompleted();
2333 state.lock();
2334 }
2335 return;
2336 }
2337 if (state->get() == ALLOCATING) {
2338 state->set(RELEASING);
2339 // With the altered state allocate() would fail and clean up.
2340 if (sendCallback) {
2341 state.unlock();
2342 mCallback->onReleaseCompleted();
2343 state.lock();
2344 }
2345 return;
2346 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002347 if (state->get() == STARTING
2348 || state->get() == RUNNING
2349 || state->get() == STOPPING) {
2350 // Input surface may have been started, so clean up is needed.
2351 clearInputSurfaceIfNeeded = true;
2352 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002353 state->set(RELEASING);
2354 }
2355
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002356 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002357 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2358 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002359 if (config->mInputSurface) {
2360 config->mInputSurface->disconnect();
2361 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08002362 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002363 }
2364 }
2365
Wonsik Kim936a89c2020-05-08 16:07:50 -07002366 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00002367 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002368 // thiz holds strong ref to this while the thread is running.
2369 sp<CCodec> thiz(this);
Sungtak Lee99144332023-01-26 11:03:14 +00002370 std::thread([thiz, sendCallback, pushBlankBuffer]
2371 { thiz->release(sendCallback, pushBlankBuffer); }).detach();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002372}
2373
Sungtak Lee99144332023-01-26 11:03:14 +00002374void CCodec::release(bool sendCallback, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002375 std::shared_ptr<Codec2Client::Component> comp;
2376 {
2377 Mutexed<State>::Locked state(mState);
2378 if (state->get() == RELEASED) {
2379 if (sendCallback) {
2380 state.unlock();
2381 mCallback->onReleaseCompleted();
2382 state.lock();
2383 }
2384 return;
2385 }
2386 comp = state->comp;
2387 }
Sungtak Leec0c05962023-10-25 08:14:13 +00002388 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->release().
2389 // But in the case some HAL implementations hang forever on comp->release().
2390 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
2391 // completing release()).
2392 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
2393 // prior to comp->release().
2394 // See also b/300350761.
Sungtak Lee34402ae2024-05-07 19:51:28 +00002395 //
2396 // The workaround is no longer needed with fetchGraphicBlock & C2Fence changes.
Sungtak Leeb7b1cf42024-05-14 22:45:35 +00002397 // so we are reverting back to the logical sequence of the operations when
2398 // AIDL HALs are selected.
2399 // When the HIDL HALs are selected, we retained workaround(the reversed
2400 // order) as default in order to keep legacy behavior.
2401 bool stopHalBeforeSurface =
2402 Codec2Client::IsAidlSelected() ||
2403 property_get_bool("debug.codec2.stop_hal_before_surface", false);
2404 if (stopHalBeforeSurface && android::media::codec::provider_->stop_hal_before_surface()) {
Sungtak Lee34402ae2024-05-07 19:51:28 +00002405 comp->release();
2406 mChannel->stopUseOutputSurface(pushBlankBuffer);
2407 } else {
2408 mChannel->stopUseOutputSurface(pushBlankBuffer);
2409 comp->release();
2410 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002411
2412 {
2413 Mutexed<State>::Locked state(mState);
2414 state->set(RELEASED);
2415 state->comp.reset();
2416 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002417 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002418 if (sendCallback) {
2419 mCallback->onReleaseCompleted();
2420 }
2421}
2422
Sungtak Lee214ce612023-11-01 10:01:13 +00002423status_t CCodec::setSurface(const sp<Surface> &surface, uint32_t generation) {
Sungtak Lee99144332023-01-26 11:03:14 +00002424 bool pushBlankBuffer = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002425 {
2426 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2427 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002428 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
2429 status_t err = OK;
2430
Wonsik Kim75e22f42021-04-14 23:34:51 -07002431 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002432 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07002433 nativeWindow.get(),
2434 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
2435 if (err != OK) {
2436 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
2437 nativeWindow.get(), config->mSidebandHandle->handle(), err);
2438 return err;
2439 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002440 } else {
2441 // Explicitly reset the sideband handle of the window for
2442 // non-tunneled video in case the window was previously used
2443 // for a tunneled video playback.
2444 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
2445 if (err != OK) {
2446 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
2447 return err;
2448 }
ted.sun765db4d2020-06-23 14:03:41 +08002449 }
Sungtak Lee99144332023-01-26 11:03:14 +00002450 pushBlankBuffer = config->mPushBlankBuffersOnStop;
ted.sun765db4d2020-06-23 14:03:41 +08002451 }
Sungtak Lee214ce612023-11-01 10:01:13 +00002452 return mChannel->setSurface(surface, generation, pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002453}
2454
2455void CCodec::signalFlush() {
2456 status_t err = [this] {
2457 Mutexed<State>::Locked state(mState);
2458 if (state->get() == FLUSHED) {
2459 return ALREADY_EXISTS;
2460 }
2461 if (state->get() != RUNNING) {
2462 return UNKNOWN_ERROR;
2463 }
2464 state->set(FLUSHING);
2465 return OK;
2466 }();
2467 switch (err) {
2468 case ALREADY_EXISTS:
2469 mCallback->onFlushCompleted();
2470 return;
2471 case OK:
2472 break;
2473 default:
2474 mCallback->onError(err, ACTION_CODE_FATAL);
2475 return;
2476 }
2477
2478 mChannel->stop();
2479 (new AMessage(kWhatFlush, this))->post();
2480}
2481
2482void CCodec::flush() {
2483 std::shared_ptr<Codec2Client::Component> comp;
2484 auto checkFlushing = [this, &comp] {
2485 Mutexed<State>::Locked state(mState);
2486 if (state->get() != FLUSHING) {
2487 return UNKNOWN_ERROR;
2488 }
2489 comp = state->comp;
2490 return OK;
2491 };
2492 if (tryAndReportOnError(checkFlushing) != OK) {
2493 return;
2494 }
2495
2496 std::list<std::unique_ptr<C2Work>> flushedWork;
2497 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2498 {
2499 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2500 flushedWork.splice(flushedWork.end(), *queue);
2501 }
2502 if (err != C2_OK) {
2503 // TODO: convert err into status_t
2504 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2505 }
2506
2507 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002508
2509 {
2510 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002511 if (state->get() == FLUSHING) {
2512 state->set(FLUSHED);
2513 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002514 }
2515 mCallback->onFlushCompleted();
2516}
2517
2518void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002519 std::shared_ptr<Codec2Client::Component> comp;
2520 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002521 Mutexed<State>::Locked state(mState);
2522 if (state->get() != FLUSHED) {
2523 return UNKNOWN_ERROR;
2524 }
2525 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002526 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002527 return OK;
2528 };
2529 if (tryAndReportOnError(setResuming) != OK) {
2530 return;
2531 }
2532
Wonsik Kime75a5da2020-02-14 17:29:03 -08002533 {
2534 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2535 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002536 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002537 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002538 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002539 }
2540
Arun Johnson106fe7a2023-04-26 17:49:43 +00002541 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
Arun Johnson326166e2023-07-28 19:11:52 +00002542 status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers, true);
Arun Johnson106fe7a2023-04-26 17:49:43 +00002543 if (err != OK) {
2544 if (err == NO_MEMORY) {
2545 // NO_MEMORY happens here when all the buffers are still
2546 // with the codec. That is not an error as it is momentarily
2547 // and the buffers are send to the client as soon as the codec
2548 // releases them
2549 ALOGI("Resuming with all input buffers still with codec");
2550 } else {
2551 ALOGE("Resume request for Input Buffers failed");
2552 mCallback->onError(err, ACTION_CODE_FATAL);
2553 return;
2554 }
2555 }
2556
2557 // channel start should be called after prepareInitialBuffers
2558 // Calling before can cause a failure during prepare when
2559 // buffers are sent to the client before preparation from onWorkDone
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002560 (void)mChannel->start(nullptr, nullptr, [&]{
2561 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2562 const std::unique_ptr<Config> &config = *configLocked;
2563 return config->mBuffersBoundToCodec;
2564 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002565 {
2566 Mutexed<State>::Locked state(mState);
2567 if (state->get() != RESUMING) {
2568 state.unlock();
2569 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2570 state.lock();
2571 return;
2572 }
2573 state->set(RUNNING);
2574 }
2575
Wonsik Kim34b28b42022-05-20 15:49:32 -07002576 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002577}
2578
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002579void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002580 std::shared_ptr<Codec2Client::Component> comp;
2581 auto checkState = [this, &comp] {
2582 Mutexed<State>::Locked state(mState);
2583 if (state->get() == RELEASED) {
2584 return INVALID_OPERATION;
2585 }
2586 comp = state->comp;
2587 return OK;
2588 };
2589 if (tryAndReportOnError(checkState) != OK) {
2590 return;
2591 }
2592
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002593 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2594 // the behavior here.
2595 sp<AMessage> params = msg;
2596 int32_t bitrate;
2597 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2598 params = msg->dup();
2599 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2600 }
2601
Houxiang Dai5a97b472021-03-22 17:56:04 +08002602 int32_t syncId = 0;
2603 if (params->findInt32("audio-hw-sync", &syncId)
2604 || params->findInt32("hw-av-sync-id", &syncId)) {
2605 configureTunneledVideoPlayback(comp, nullptr, params);
2606 }
2607
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002608 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2609 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002610
2611 /**
2612 * Handle input surface parameters
2613 */
2614 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002615 && (config->mDomain & Config::IS_ENCODER)
2616 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002617 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002618
2619 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2620 config->mISConfig->mStopped = false;
2621 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2622 config->mISConfig->mStopped = true;
2623 }
2624
2625 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002626 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002627 config->mISConfig->mSuspended = value;
2628 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002629 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002630 }
2631
2632 (void)config->mInputSurface->configure(*config->mISConfig);
2633 if (config->mISConfig->mStopped) {
2634 config->mInputFormat->setInt64(
2635 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2636 }
2637 }
2638
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302639 /**
2640 * Handle ROI QP map configuration. Recover the QP map configuration from AMessage as an
2641 * ABuffer and configure to CCodecBufferChannel as a C2InfoBuffer
2642 */
2643 if (android::media::codec::provider_->region_of_interest()
2644 && android::media::codec::provider_->region_of_interest_support()) {
2645 sp<ABuffer> qpOffsetMap;
2646 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
2647 && (config->mDomain & Config::IS_ENCODER)
2648 && params->findBuffer(PARAMETER_KEY_QP_OFFSET_MAP, &qpOffsetMap)) {
2649 std::shared_ptr<C2BlockPool> pool;
2650 // TODO(b/331443865) Use pooled block pool to improve efficiency
2651 c2_status_t status = GetCodec2BlockPool(C2BlockPool::BASIC_LINEAR, nullptr, &pool);
2652
2653 if (status == C2_OK) {
Suyog Paware23970e2024-06-03 15:57:49 +05302654 int width, height;
2655 config->mInputFormat->findInt32("width", &width);
2656 config->mInputFormat->findInt32("height", &height);
2657 // The length of the qp-map corresponds to the number of 16x16 blocks in one frame
2658 int expectedMapSize = ((width + 15) / 16) * ((height + 15) / 16);
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302659 size_t mapSize = qpOffsetMap->size();
Suyog Paware23970e2024-06-03 15:57:49 +05302660 if (mapSize >= expectedMapSize) {
2661 std::shared_ptr<C2LinearBlock> block;
2662 status = pool->fetchLinearBlock(
2663 expectedMapSize,
2664 C2MemoryUsage{C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
2665 &block);
2666 if (status == C2_OK && !block->map().get().error()) {
2667 C2WriteView wView = block->map().get();
2668 uint8_t* outData = wView.data();
2669 memcpy(outData, qpOffsetMap->data(), expectedMapSize);
2670 C2InfoBuffer info = C2InfoBuffer::CreateLinearBuffer(
2671 kParamIndexQpOffsetMapBuffer,
2672 block->share(0, expectedMapSize, C2Fence()));
2673 mChannel->setInfoBuffer(std::make_shared<C2InfoBuffer>(info));
2674 }
2675 } else {
2676 ALOGE("Ignoring param key %s as buffer size %d is less than expected "
2677 "buffer size %d",
2678 PARAMETER_KEY_QP_OFFSET_MAP, mapSize, expectedMapSize);
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302679 }
2680 }
2681 params->removeEntryByName(PARAMETER_KEY_QP_OFFSET_MAP);
2682 }
2683 }
2684
2685
Pawin Vongmasa36653902018-11-15 00:10:25 -08002686 std::vector<std::unique_ptr<C2Param>> configUpdate;
2687 (void)config->getConfigUpdateFromSdkParams(
2688 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2689 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2690 // Parameter synchronization is not defined when using input surface. For now, route
2691 // these directly to the component.
2692 if (config->mInputSurface == nullptr
2693 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2694 || comp->getName().find("c2.android.") == 0)) {
Wonsik Kim051238c2024-06-13 21:16:23 +00002695 std::vector<std::unique_ptr<C2Param>> localConfigUpdate;
2696 for (const std::unique_ptr<C2Param> &param : configUpdate) {
2697 if (param && param->coreIndex().coreIndex() == C2StreamSurfaceScalingInfo::CORE_INDEX) {
2698 localConfigUpdate.push_back(C2Param::Copy(*param));
2699 }
2700 }
2701 if (!localConfigUpdate.empty()) {
2702 (void)config->setParameters(comp, localConfigUpdate, C2_MAY_BLOCK);
2703 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002704 mChannel->setParameters(configUpdate);
2705 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002706 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002707 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002708 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002709 }
2710}
2711
2712void CCodec::signalEndOfInputStream() {
2713 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2714}
2715
2716void CCodec::signalRequestIDRFrame() {
2717 std::shared_ptr<Codec2Client::Component> comp;
2718 {
2719 Mutexed<State>::Locked state(mState);
2720 if (state->get() == RELEASED) {
2721 ALOGD("no IDR request sent since component is released");
2722 return;
2723 }
2724 comp = state->comp;
2725 }
2726 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002727 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2728 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002729 std::vector<std::unique_ptr<C2Param>> params;
2730 params.push_back(
2731 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2732 config->setParameters(comp, params, C2_MAY_BLOCK);
2733}
2734
Wonsik Kim874ad382021-03-12 09:59:36 -08002735status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2736 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2737 const std::unique_ptr<Config> &config = *configLocked;
2738 return config->querySupportedParameters(names);
2739}
2740
2741status_t CCodec::describeParameter(
2742 const std::string &name, CodecParameterDescriptor *desc) {
2743 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2744 const std::unique_ptr<Config> &config = *configLocked;
2745 return config->describe(name, desc);
2746}
2747
2748status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2749 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2750 if (!comp) {
2751 return INVALID_OPERATION;
2752 }
2753 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2754 const std::unique_ptr<Config> &config = *configLocked;
2755 return config->subscribeToVendorConfigUpdate(comp, names);
2756}
2757
2758status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2759 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2760 if (!comp) {
2761 return INVALID_OPERATION;
2762 }
2763 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2764 const std::unique_ptr<Config> &config = *configLocked;
2765 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2766}
2767
Wonsik Kimab34ed62019-01-31 15:28:46 -08002768void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002769 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002770 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002771 bool shouldPost = queue->empty();
Wonsik Kimab34ed62019-01-31 15:28:46 -08002772 queue->splice(queue->end(), workItems);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002773 if (shouldPost) {
2774 (new AMessage(kWhatWorkDone, this))->post();
2775 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002776 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002777}
2778
Wonsik Kimab34ed62019-01-31 15:28:46 -08002779void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2780 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002781 if (arrayIndex == 0) {
2782 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002783 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2784 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002785 if (config->mInputSurface) {
2786 config->mInputSurface->onInputBufferDone(frameIndex);
2787 }
2788 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002789}
2790
2791void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2792 TimePoint now = std::chrono::steady_clock::now();
2793 CCodecWatchdog::getInstance()->watch(this);
2794 switch (msg->what()) {
2795 case kWhatAllocate: {
2796 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002797 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002798 sp<RefBase> obj;
2799 CHECK(msg->findObject("codecInfo", &obj));
2800 allocate((MediaCodecInfo *)obj.get());
2801 break;
2802 }
2803 case kWhatConfigure: {
2804 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002805 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002806 sp<AMessage> format;
2807 CHECK(msg->findMessage("format", &format));
2808 configure(format);
2809 break;
2810 }
2811 case kWhatStart: {
2812 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002813 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002814 start();
2815 break;
2816 }
2817 case kWhatStop: {
2818 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002819 setDeadline(now, 1500ms, "stop");
Sungtak Lee99144332023-01-26 11:03:14 +00002820 int32_t pushBlankBuffer;
2821 if (!msg->findInt32("pushBlankBuffer", &pushBlankBuffer)) {
2822 pushBlankBuffer = 0;
2823 }
2824 stop(static_cast<bool>(pushBlankBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002825 break;
2826 }
2827 case kWhatFlush: {
2828 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002829 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002830 flush();
2831 break;
2832 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002833 case kWhatRelease: {
2834 mChannel->release();
2835 mClient.reset();
2836 mClientListener.reset();
2837 break;
2838 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002839 case kWhatCreateInputSurface: {
2840 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002841 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002842 createInputSurface();
2843 break;
2844 }
2845 case kWhatSetInputSurface: {
2846 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002847 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002848 sp<RefBase> obj;
2849 CHECK(msg->findObject("surface", &obj));
2850 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2851 setInputSurface(surface);
2852 break;
2853 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002854 case kWhatWorkDone: {
2855 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002856 bool shouldPost = false;
2857 {
2858 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2859 if (queue->empty()) {
2860 break;
2861 }
2862 work.swap(queue->front());
2863 queue->pop_front();
2864 shouldPost = !queue->empty();
2865 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002866 if (shouldPost) {
2867 (new AMessage(kWhatWorkDone, this))->post();
2868 }
2869
Pawin Vongmasa36653902018-11-15 00:10:25 -08002870 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002871 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002872 sp<AMessage> outputFormat = nullptr;
2873 {
2874 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2875 const std::unique_ptr<Config> &config = *configLocked;
2876 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2877 config->watch<C2StreamInitDataInfo::output>();
2878 if (!work->worklets.empty()
2879 && (work->worklets.front()->output.flags
2880 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002881
Wonsik Kim75e22f42021-04-14 23:34:51 -07002882 // copy buffer info to config
2883 std::vector<std::unique_ptr<C2Param>> updates;
2884 for (const std::unique_ptr<C2Param> &param
2885 : work->worklets.front()->output.configUpdate) {
2886 updates.push_back(C2Param::Copy(*param));
2887 }
2888 unsigned stream = 0;
2889 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2890 work->worklets.front()->output.buffers;
2891 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2892 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2893 // move all info into output-stream #0 domain
2894 updates.emplace_back(
2895 C2Param::CopyAsStream(*info, true /* output */, stream));
2896 }
2897
2898 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2899 // for now only do the first block
2900 if (!blocks.empty()) {
2901 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2902 // block.crop().left, block.crop().top,
2903 // block.crop().width, block.crop().height,
2904 // block.width(), block.height());
2905 const C2ConstGraphicBlock &block = blocks[0];
2906 updates.emplace_back(new C2StreamCropRectInfo::output(
2907 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002908 }
2909 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002910 }
George Burgess IVc813a592020-02-22 22:54:44 -08002911
Wonsik Kim75e22f42021-04-14 23:34:51 -07002912 sp<AMessage> oldFormat = config->mOutputFormat;
2913 config->updateConfiguration(updates, config->mOutputDomain);
2914 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002915
Wonsik Kim75e22f42021-04-14 23:34:51 -07002916 // copy standard infos to graphic buffers if not already present (otherwise, we
2917 // may overwrite the actual intermediate value with a final value)
2918 stream = 0;
2919 const static C2Param::Index stdGfxInfos[] = {
2920 C2StreamRotationInfo::output::PARAM_TYPE,
2921 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2922 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2923 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Taehwan Kim2d222b82022-05-12 14:19:26 +09002924 C2StreamHdr10PlusInfo::output::PARAM_TYPE, // will be deprecated
2925 C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE,
Wonsik Kim75e22f42021-04-14 23:34:51 -07002926 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2927 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2928 };
2929 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2930 if (buf->data().graphicBlocks().size()) {
2931 for (C2Param::Index ix : stdGfxInfos) {
2932 if (!buf->hasInfo(ix)) {
2933 const C2Param *param =
2934 config->getConfigParameterValue(ix.withStream(stream));
2935 if (param) {
2936 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2937 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2938 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002939 }
2940 }
2941 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002942 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002943 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002944 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002945 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302946 if (work->worklets.empty()
2947 || !work->worklets.back()
2948 || (work->worklets.back()->output.flags
2949 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2950 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2951 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002952 }
2953 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002954 initData = initDataWatcher.update();
2955 AmendOutputFormatWithCodecSpecificData(
2956 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2957 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002958 }
2959 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002960 }
2961 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002962 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Songyue Han1e6769b2023-08-30 18:09:27 +00002963 // log metrics to MediaCodec
2964 if (mMetrics->countEntries() == 0) {
2965 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2966 const std::unique_ptr<Config> &config = *configLocked;
2967 uint32_t pf = PIXEL_FORMAT_UNKNOWN;
2968 if (!config->mInputSurface) {
2969 pf = mChannel->getBuffersPixelFormat(config->mDomain & Config::IS_ENCODER);
Songyue Hanad01f6a2023-08-17 05:45:35 +00002970 } else {
2971 pf = config->mInputSurface->getPixelFormat();
Songyue Han1e6769b2023-08-30 18:09:27 +00002972 }
2973 if (pf != PIXEL_FORMAT_UNKNOWN) {
2974 mMetrics->setInt64(kCodecPixelFormat, pf);
2975 mCallback->onMetricsUpdated(mMetrics);
2976 }
2977 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002978 break;
2979 }
2980 case kWhatWatch: {
2981 // watch message already posted; no-op.
2982 break;
2983 }
2984 default: {
2985 ALOGE("unrecognized message");
2986 break;
2987 }
2988 }
2989 setDeadline(TimePoint::max(), 0ms, "none");
2990}
2991
2992void CCodec::setDeadline(
2993 const TimePoint &now,
2994 const std::chrono::milliseconds &timeout,
2995 const char *name) {
2996 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2997 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2998 deadline->set(now + (timeout * mult), name);
2999}
3000
ted.sun765db4d2020-06-23 14:03:41 +08003001status_t CCodec::configureTunneledVideoPlayback(
3002 std::shared_ptr<Codec2Client::Component> comp,
3003 sp<NativeHandle> *sidebandHandle,
3004 const sp<AMessage> &msg) {
3005 std::vector<std::unique_ptr<C2SettingResult>> failures;
3006
3007 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
3008 C2PortTunneledModeTuning::output::AllocUnique(
3009 1,
3010 C2PortTunneledModeTuning::Struct::SIDEBAND,
3011 C2PortTunneledModeTuning::Struct::REALTIME,
3012 0);
3013 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
3014 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
3015 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
3016 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
3017 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
3018 } else {
3019 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
3020 tunneledPlayback->setFlexCount(0);
3021 }
3022 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
3023 if (c2err != C2_OK) {
3024 return UNKNOWN_ERROR;
3025 }
3026
Houxiang Dai5a97b472021-03-22 17:56:04 +08003027 if (sidebandHandle == nullptr) {
3028 return OK;
3029 }
3030
ted.sun765db4d2020-06-23 14:03:41 +08003031 std::vector<std::unique_ptr<C2Param>> params;
3032 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
3033 if (c2err == C2_OK && params.size() == 1u) {
3034 C2PortTunnelHandleTuning::output *videoTunnelSideband =
3035 C2PortTunnelHandleTuning::output::From(params[0].get());
3036 // Currently, Codec2 only supports non-fd case for sideband native_handle.
3037 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
3038 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
3039 if (handle != nullptr && videoTunnelSideband->flexCount()) {
3040 memcpy(handle->data, videoTunnelSideband->m.values,
3041 sizeof(int32_t) * videoTunnelSideband->flexCount());
3042 return OK;
3043 } else {
3044 return NO_MEMORY;
3045 }
3046 }
3047 return UNKNOWN_ERROR;
3048}
3049
Pawin Vongmasa36653902018-11-15 00:10:25 -08003050void CCodec::initiateReleaseIfStuck() {
Shrikara B3b87a532022-08-26 14:18:14 +05303051 std::string name;
3052 bool pendingDeadline = false;
3053 {
3054 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
3055 if (deadline->get() < std::chrono::steady_clock::now()) {
3056 name = deadline->getName();
3057 }
3058 if (deadline->get() != TimePoint::max()) {
3059 pendingDeadline = true;
3060 }
3061 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08003062 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08003063 // We're not stuck.
3064 if (pendingDeadline) {
3065 // If we are not stuck yet but still has deadline coming up,
3066 // post watch message to check back later.
3067 (new AMessage(kWhatWatch, this))->post();
3068 }
3069 return;
3070 }
3071
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09003072 C2String compName;
3073 {
3074 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07003075 if (!state->comp) {
3076 ALOGD("previous call to %s exceeded timeout "
3077 "and the component is already released", name.c_str());
3078 return;
3079 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09003080 compName = state->comp->getName();
3081 }
3082 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
3083
Pawin Vongmasa36653902018-11-15 00:10:25 -08003084 initiateRelease(false);
3085 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
3086}
3087
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003088// static
3089PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07003090 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07003091 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08003092 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07003093 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
3094 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08003095 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07003096 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
Sungtak Lee92bca442024-03-12 09:10:31 +00003097 if (Codec2Client::IsAidlSelected()) {
3098 sp<IGraphicBufferProducer> gbp;
3099 sp<AidlGraphicBufferSource> gbs = new AidlGraphicBufferSource();
3100 status_t err = gbs->initCheck();
3101 if (err != OK) {
3102 ALOGE("Failed to create persistent input surface: error %d", err);
3103 return nullptr;
3104 }
3105 ALOGD("aidl based PersistentSurface created");
3106 std::shared_ptr<WAidlGraphicBufferSource> wrapper =
3107 ::ndk::SharedRefBase::make<WAidlGraphicBufferSource>(gbs);
3108
3109 return new PersistentSurface(
3110 gbs->getIGraphicBufferProducer(), wrapper->asBinder());
3111 } else {
3112 sp<IGraphicBufferProducer> gbp;
3113 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
3114 status_t err = gbs->initCheck();
3115 if (err != OK) {
3116 ALOGE("Failed to create persistent input surface: error %d", err);
3117 return nullptr;
3118 }
3119 ALOGD("hidl based PersistentSurface created");
3120 return new PersistentSurface(
3121 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07003122 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07003123 } else {
3124 return nullptr;
3125 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08003126 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07003127 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08003128 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07003129 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08003130 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08003131}
3132
Wonsik Kimffb889a2020-05-28 11:32:25 -07003133class IntfCache {
3134public:
3135 IntfCache() = default;
3136
3137 status_t init(const std::string &name) {
3138 std::shared_ptr<Codec2Client::Interface> intf{
3139 Codec2Client::CreateInterfaceByName(name.c_str())};
3140 if (!intf) {
3141 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
3142 mInitStatus = NO_INIT;
3143 return NO_INIT;
3144 }
3145 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
3146 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
3147 C2ParamField{&sUsage, &sUsage.value}));
3148 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
3149 if (err != C2_OK) {
3150 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
3151 name.c_str(), err);
3152 mFields[0].status = err;
3153 }
3154 std::vector<std::unique_ptr<C2Param>> params;
3155 err = intf->query(
3156 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09003157 {
3158 C2StreamBufferTypeSetting::input::PARAM_TYPE,
3159 C2PortAllocatorsTuning::input::PARAM_TYPE
3160 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07003161 C2_MAY_BLOCK,
3162 &params);
3163 if (err != C2_OK && err != C2_BAD_INDEX) {
3164 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
3165 name.c_str(), err);
3166 }
3167 while (!params.empty()) {
3168 C2Param *param = params.back().release();
3169 params.pop_back();
3170 if (!param) {
3171 continue;
3172 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09003173 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
3174 mInputStreamFormat.reset(
3175 C2StreamBufferTypeSetting::input::From(param));
3176 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003177 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07003178 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07003179 }
3180 }
3181 mInitStatus = OK;
3182 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003183 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003184
3185 status_t initCheck() const { return mInitStatus; }
3186
3187 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
3188 CHECK_EQ(1u, mFields.size());
3189 return mFields[0];
3190 }
3191
3192 const C2ApiFeaturesSetting &getApiFeatures() const {
3193 return mApiFeatures;
3194 }
3195
Taehwan Kim900b49c2021-12-13 11:16:22 +09003196 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
3197 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
3198 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
3199 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
3200 param->invalidate();
3201 return param;
3202 }();
3203 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
3204 }
3205
Wonsik Kimffb889a2020-05-28 11:32:25 -07003206 const C2PortAllocatorsTuning::input &getInputAllocators() const {
3207 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
3208 std::unique_ptr<C2PortAllocatorsTuning::input> param =
3209 C2PortAllocatorsTuning::input::AllocUnique(0);
3210 param->invalidate();
3211 return param;
3212 }();
3213 return mInputAllocators ? *mInputAllocators : *sInvalidated;
3214 }
3215
3216private:
3217 status_t mInitStatus{NO_INIT};
3218
3219 std::vector<C2FieldSupportedValuesQuery> mFields;
3220 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09003221 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003222 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
3223};
3224
3225static const IntfCache &GetIntfCache(const std::string &name) {
3226 static IntfCache sNullIntfCache;
3227 static std::mutex sMutex;
3228 static std::map<std::string, IntfCache> sCache;
3229 std::unique_lock<std::mutex> lock{sMutex};
3230 auto it = sCache.find(name);
3231 if (it == sCache.end()) {
3232 lock.unlock();
3233 IntfCache intfCache;
3234 status_t err = intfCache.init(name);
3235 if (err != OK) {
3236 return sNullIntfCache;
3237 }
3238 lock.lock();
3239 it = sCache.insert({name, std::move(intfCache)}).first;
3240 }
3241 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003242}
3243
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003244static status_t GetCommonAllocatorIds(
3245 const std::vector<std::string> &names,
3246 C2Allocator::type_t type,
3247 std::set<C2Allocator::id_t> *ids) {
3248 int poolMask = GetCodec2PoolMask();
3249 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
3250 C2Allocator::id_t defaultAllocatorId =
3251 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
3252
3253 ids->clear();
3254 if (names.empty()) {
3255 return OK;
3256 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003257 bool firstIteration = true;
3258 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003259 const IntfCache &intfCache = GetIntfCache(name);
3260 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003261 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003262 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09003263 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
3264 if (streamFormat) {
3265 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
3266 if (streamFormat.value == C2BufferData::GRAPHIC
3267 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
3268 allocatorType = C2Allocator::GRAPHIC;
3269 }
3270
3271 if (type != allocatorType) {
3272 // requested type is not supported at input allocators
3273 ids->clear();
3274 ids->insert(defaultAllocatorId);
3275 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
3276 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
3277 break;
3278 }
3279 }
3280
Wonsik Kimffb889a2020-05-28 11:32:25 -07003281 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003282 if (firstIteration) {
3283 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003284 if (allocators && allocators.flexCount() > 0) {
3285 ids->insert(allocators.m.values,
3286 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003287 }
3288 if (ids->empty()) {
3289 // The component does not advertise allocators. Use default.
3290 ids->insert(defaultAllocatorId);
3291 }
3292 continue;
3293 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003294 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003295 if (allocators && allocators.flexCount() > 0) {
3296 filtered = true;
3297 for (auto it = ids->begin(); it != ids->end(); ) {
3298 bool found = false;
3299 for (size_t j = 0; j < allocators.flexCount(); ++j) {
3300 if (allocators.m.values[j] == *it) {
3301 found = true;
3302 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003303 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003304 }
3305 if (found) {
3306 ++it;
3307 } else {
3308 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003309 }
3310 }
3311 }
3312 if (!filtered) {
3313 // The component does not advertise supported allocators. Use default.
3314 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
3315 if (ids->size() != (containsDefault ? 1 : 0)) {
3316 ids->clear();
3317 if (containsDefault) {
3318 ids->insert(defaultAllocatorId);
3319 }
3320 }
3321 }
3322 }
3323 // Finally, filter with pool masks
3324 for (auto it = ids->begin(); it != ids->end(); ) {
3325 if ((poolMask >> *it) & 1) {
3326 ++it;
3327 } else {
3328 it = ids->erase(it);
3329 }
3330 }
3331 return OK;
3332}
3333
3334static status_t CalculateMinMaxUsage(
3335 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
3336 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
3337 *minUsage = 0;
3338 *maxUsage = ~0ull;
3339 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003340 const IntfCache &intfCache = GetIntfCache(name);
3341 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003342 continue;
3343 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003344 const C2FieldSupportedValuesQuery &usageSupportedValues =
3345 intfCache.getUsageSupportedValues();
3346 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003347 continue;
3348 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003349 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003350 if (supported.type != C2FieldSupportedValues::FLAGS) {
3351 continue;
3352 }
3353 if (supported.values.empty()) {
3354 *maxUsage = 0;
3355 continue;
3356 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08003357 if (supported.values.size() > 1) {
3358 *minUsage |= supported.values[1].u64;
3359 } else {
3360 *minUsage |= supported.values[0].u64;
3361 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003362 int64_t currentMaxUsage = 0;
3363 for (const C2Value::Primitive &flags : supported.values) {
3364 currentMaxUsage |= flags.u64;
3365 }
3366 *maxUsage &= currentMaxUsage;
3367 }
3368 return OK;
3369}
3370
3371// static
3372status_t CCodec::CanFetchLinearBlock(
3373 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003374 for (const std::string &name : names) {
3375 const IntfCache &intfCache = GetIntfCache(name);
3376 if (intfCache.initCheck() != OK) {
3377 continue;
3378 }
3379 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
3380 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
3381 *isCompatible = false;
3382 return OK;
3383 }
3384 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003385 std::set<C2Allocator::id_t> allocators;
3386 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
3387 if (allocators.empty()) {
3388 *isCompatible = false;
3389 return OK;
3390 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003391
3392 uint64_t minUsage = 0;
3393 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003394 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003395 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003396 *isCompatible = ((maxUsage & minUsage) == minUsage);
3397 return OK;
3398}
3399
3400static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
3401 static std::mutex sMutex{};
3402 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
3403 std::unique_lock<std::mutex> lock{sMutex};
3404 std::shared_ptr<C2BlockPool> pool;
3405 auto it = sPools.find(allocId);
3406 if (it == sPools.end()) {
3407 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3408 if (err == OK) {
3409 sPools.emplace(allocId, pool);
3410 } else {
3411 pool.reset();
3412 }
3413 } else {
3414 pool = it->second;
3415 }
3416 return pool;
3417}
3418
3419// static
3420std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
3421 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003422 std::set<C2Allocator::id_t> allocators;
3423 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
3424 if (allocators.empty()) {
3425 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
3426 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003427
3428 uint64_t minUsage = 0;
3429 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003430 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003431 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003432 if ((maxUsage & minUsage) != minUsage) {
3433 allocators.clear();
3434 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
3435 }
3436 std::shared_ptr<C2LinearBlock> block;
3437 for (C2Allocator::id_t allocId : allocators) {
3438 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
3439 if (!pool) {
3440 continue;
3441 }
3442 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
3443 if (err != C2_OK || !block) {
3444 block.reset();
3445 continue;
3446 }
3447 break;
3448 }
3449 return block;
3450}
3451
3452// static
3453status_t CCodec::CanFetchGraphicBlock(
3454 const std::vector<std::string> &names, bool *isCompatible) {
3455 uint64_t minUsage = 0;
3456 uint64_t maxUsage = ~0ull;
3457 std::set<C2Allocator::id_t> allocators;
3458 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3459 if (allocators.empty()) {
3460 *isCompatible = false;
3461 return OK;
3462 }
3463 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3464 *isCompatible = ((maxUsage & minUsage) == minUsage);
3465 return OK;
3466}
3467
3468// static
3469std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
3470 int32_t width,
3471 int32_t height,
3472 int32_t format,
3473 uint64_t usage,
3474 const std::vector<std::string> &names) {
3475 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
3476 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
3477 ALOGD("Unrecognized pixel format: %d", format);
3478 return nullptr;
3479 }
3480 uint64_t minUsage = 0;
3481 uint64_t maxUsage = ~0ull;
3482 std::set<C2Allocator::id_t> allocators;
3483 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3484 if (allocators.empty()) {
3485 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3486 }
3487 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3488 minUsage |= usage;
3489 if ((maxUsage & minUsage) != minUsage) {
3490 allocators.clear();
3491 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3492 }
3493 std::shared_ptr<C2GraphicBlock> block;
3494 for (C2Allocator::id_t allocId : allocators) {
3495 std::shared_ptr<C2BlockPool> pool;
3496 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3497 if (err != C2_OK || !pool) {
3498 continue;
3499 }
3500 err = pool->fetchGraphicBlock(
3501 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
3502 if (err != C2_OK || !block) {
3503 block.reset();
3504 continue;
3505 }
3506 break;
3507 }
3508 return block;
3509}
3510
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003511} // namespace android