blob: 5396d2517051894e91f1fdcbff17ca2b813f0169 [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 {
225 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700226 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800227 mNode->setFrameSize(mWidth, mHeight);
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700228 // Usage is queried during configure(), so setting it beforehand.
Sungtak Lee0cd4fbc2023-02-02 00:59:01 +0000229 // 64 bit set parameter is existing only in C2OMXNode.
230 OMX_U64 usage64 = mConfig.mUsage;
231 status_t res = mNode->setParameter(
232 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits64,
233 &usage64, sizeof(usage64));
234
235 if (res != OK) {
236 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
237 (void)mNode->setParameter(
238 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
239 &usage, sizeof(usage));
240 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700241
Yanqiang Fanc56f3e62021-09-28 16:54:07 +0800242 return GetStatus(mSource->configure(
243 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800244 }
245
246 void disconnect() override {
247 if (mNode == nullptr) {
248 return;
249 }
250 sp<IOMXBufferSource> source = mNode->getSource();
251 if (source == nullptr) {
252 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
253 return;
254 }
255 source->onOmxIdle();
256 source->onOmxLoaded();
257 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700258 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800259 }
260
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700261 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
262 if (status.isOk()) {
263 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
264 } else if (status.isDeadObject()) {
265 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800266 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700267 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800268 }
269
270 status_t start() override {
271 sp<IOMXBufferSource> source = mNode->getSource();
272 if (source == nullptr) {
273 return NO_INIT;
274 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900275
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800276 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800277 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900278
Wonsik Kim34d66012021-03-01 16:40:33 -0800279 OMX_PARAM_PORTDEFINITIONTYPE param;
280 param.nPortIndex = kPortIndexInput;
281 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
282 &param, sizeof(param));
283 if (err == OK) {
284 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900285 }
286
287 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800288 source->onInputBufferAdded(i);
289 }
290
291 source->onOmxExecuting();
292 return OK;
293 }
294
295 status_t signalEndOfInputStream() override {
296 return GetStatus(mSource->signalEndOfInputStream());
297 }
298
299 status_t configure(Config &config) {
300 std::stringstream status;
301 status_t err = OK;
302
303 // handle each configuration granually, in case we need to handle part of the configuration
304 // elsewhere
305
306 // TRICKY: we do not unset frame delay repeating
307 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
308 int64_t us = 1e6 / config.mMinFps + 0.5;
309 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
310 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
311 if (res != OK) {
312 status << " (=> " << asString(res) << ")";
313 err = res;
314 }
315 mConfig.mMinFps = config.mMinFps;
316 }
317
318 // pts gap
319 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
320 if (mNode != nullptr) {
321 OMX_PARAM_U32TYPE ptrGapParam = {};
322 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700323 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800324 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
325 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700326 // float -> uint32_t is undefined if the value is negative.
327 // First convert to int32_t to ensure the expected behavior.
328 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800329 (void)mNode->setParameter(
330 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
331 &ptrGapParam, sizeof(ptrGapParam));
332 }
333 }
334
335 // max fps
336 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700337 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800338 && config.mMaxFps != mConfig.mMaxFps) {
339 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
340 status << " maxFps=" << config.mMaxFps;
341 if (res != OK) {
342 status << " (=> " << asString(res) << ")";
343 err = res;
344 }
345 mConfig.mMaxFps = config.mMaxFps;
346 }
347
348 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
349 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
350 status << " timeOffset " << config.mTimeOffsetUs << "us";
351 if (res != OK) {
352 status << " (=> " << asString(res) << ")";
353 err = res;
354 }
355 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
356 }
357
358 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
359 status_t res =
360 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
361 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
362 if (res != OK) {
363 status << " (=> " << asString(res) << ")";
364 err = res;
365 }
366 mConfig.mCaptureFps = config.mCaptureFps;
367 mConfig.mCodedFps = config.mCodedFps;
368 }
369
370 if (config.mStartAtUs != mConfig.mStartAtUs
371 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
372 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
373 status << " start at " << config.mStartAtUs << "us";
374 if (res != OK) {
375 status << " (=> " << asString(res) << ")";
376 err = res;
377 }
378 mConfig.mStartAtUs = config.mStartAtUs;
379 mConfig.mStopped = config.mStopped;
380 }
381
382 // suspend-resume
383 if (config.mSuspended != mConfig.mSuspended) {
384 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
385 status << " " << (config.mSuspended ? "suspend" : "resume")
386 << " at " << config.mSuspendAtUs << "us";
387 if (res != OK) {
388 status << " (=> " << asString(res) << ")";
389 err = res;
390 }
391 mConfig.mSuspended = config.mSuspended;
392 mConfig.mSuspendAtUs = config.mSuspendAtUs;
393 }
394
395 if (config.mStopped != mConfig.mStopped && config.mStopped) {
396 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
397 status << " stop at " << config.mStopAtUs << "us";
398 if (res != OK) {
399 status << " (=> " << asString(res) << ")";
400 err = res;
401 } else {
402 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700403 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
404 [&res, &delayUs = config.mInputDelayUs](
405 auto status, auto stopTimeOffsetUs) {
406 res = static_cast<status_t>(status);
407 delayUs = stopTimeOffsetUs;
408 });
409 if (!trans.isOk()) {
410 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
411 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800412 if (res != OK) {
413 status << " (=> " << asString(res) << ")";
414 } else {
415 status << "=" << config.mInputDelayUs << "us";
416 }
417 mConfig.mInputDelayUs = config.mInputDelayUs;
418 }
419 mConfig.mStopAtUs = config.mStopAtUs;
420 mConfig.mStopped = config.mStopped;
421 }
422
423 // color aspects (android._color-aspects)
424
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700425 // consumer usage is queried earlier.
426
Wonsik Kima1335e12021-04-22 16:28:29 -0700427 // priority
428 if (mConfig.mPriority != config.mPriority) {
429 if (config.mPriority != INT_MAX) {
430 mNode->setPriority(config.mPriority);
431 }
432 mConfig.mPriority = config.mPriority;
433 }
434
Wonsik Kimbd557932019-07-02 15:51:20 -0700435 if (status.str().empty()) {
436 ALOGD("ISConfig not changed");
437 } else {
438 ALOGD("ISConfig%s", status.str().c_str());
439 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800440 return err;
441 }
442
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700443 void onInputBufferDone(c2_cntr64_t index) override {
444 mNode->onInputBufferDone(index);
445 }
446
Wonsik Kim673dd192021-01-29 14:58:12 -0800447 android_dataspace getDataspace() override {
448 return mNode->getDataspace();
449 }
450
Songyue Hanad01f6a2023-08-17 05:45:35 +0000451 uint32_t getPixelFormat() override {
452 return mNode->getPixelFormat();
453 }
454
Pawin Vongmasa36653902018-11-15 00:10:25 -0800455private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700456 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800457 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700458 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800459 uint32_t mWidth;
460 uint32_t mHeight;
461 Config mConfig;
462};
463
Sungtak Lee92bca442024-03-12 09:10:31 +0000464class AGraphicBufferSourceWrapper : public InputSurfaceWrapper {
465public:
466 AGraphicBufferSourceWrapper(
467 const std::shared_ptr<AGraphicBufferSource> &source,
468 uint32_t width,
469 uint32_t height,
470 uint64_t usage)
471 : mSource(source), mWidth(width), mHeight(height) {
472 mDataSpace = HAL_DATASPACE_BT709;
473 mConfig.mUsage = usage;
474 }
475 ~AGraphicBufferSourceWrapper() override = default;
476
477 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
478 mNode = ::ndk::SharedRefBase::make<C2AidlNode>(comp);
479 mNode->setFrameSize(mWidth, mHeight);
480 // Usage is queried during configure(), so setting it beforehand.
481 uint64_t usage = mConfig.mUsage;
482 (void)mNode->setConsumerUsage((int64_t)usage);
483
484 return fromAidlStatus(mSource->configure(
485 mNode, static_cast<::aidl::android::hardware::graphics::common::Dataspace>(
486 mDataSpace)));
487 }
488
489 void disconnect() override {
490 if (mNode == nullptr) {
491 return;
492 }
493 std::shared_ptr<IAidlBufferSource> source = mNode->getSource();
494 if (source == nullptr) {
495 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
496 return;
497 }
498 (void)source->onStop();
499 (void)source->onRelease();
500 mNode.reset();
501 }
502
503 status_t start() override {
504 std::shared_ptr<IAidlBufferSource> source = mNode->getSource();
505 if (source == nullptr) {
506 return NO_INIT;
507 }
508
509 size_t numSlots = 16;
510
511 IAidlNode::InputBufferParams param;
512 status_t err = fromAidlStatus(mNode->getInputBufferParams(&param));
513 if (err == OK) {
514 numSlots = param.bufferCountActual;
515 }
516
517 for (size_t i = 0; i < numSlots; ++i) {
518 (void)source->onInputBufferAdded(i);
519 }
520
521 (void)source->onStart();
522 return OK;
523 }
524
525 status_t signalEndOfInputStream() override {
526 return fromAidlStatus(mSource->signalEndOfInputStream());
527 }
528
529 status_t configure(Config &config) {
530 std::stringstream status;
531 status_t err = OK;
532
533 // handle each configuration granually, in case we need to handle part of the configuration
534 // elsewhere
535
536 // TRICKY: we do not unset frame delay repeating
537 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
538 int64_t us = 1e6 / config.mMinFps + 0.5;
539 status_t res = fromAidlStatus(mSource->setRepeatPreviousFrameDelayUs(us));
540 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
541 if (res != OK) {
542 status << " (=> " << asString(res) << ")";
543 err = res;
544 }
545 mConfig.mMinFps = config.mMinFps;
546 }
547
548 // pts gap
549 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
550 if (mNode != nullptr) {
551 float gap = (config.mMinAdjustedFps > 0)
552 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
553 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
554 // float -> uint32_t is undefined if the value is negative.
555 // First convert to int32_t to ensure the expected behavior.
556 int32_t gapUs = int32_t(gap);
557 (void)mNode->setAdjustTimestampGapUs(gapUs);
558 }
559 }
560
561 // max fps
562 // TRICKY: we do not unset max fps to 0 unless using fixed fps
563 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
564 && config.mMaxFps != mConfig.mMaxFps) {
565 status_t res = fromAidlStatus(mSource->setMaxFps(config.mMaxFps));
566 status << " maxFps=" << config.mMaxFps;
567 if (res != OK) {
568 status << " (=> " << asString(res) << ")";
569 err = res;
570 }
571 mConfig.mMaxFps = config.mMaxFps;
572 }
573
574 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
575 status_t res = fromAidlStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
576 status << " timeOffset " << config.mTimeOffsetUs << "us";
577 if (res != OK) {
578 status << " (=> " << asString(res) << ")";
579 err = res;
580 }
581 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
582 }
583
584 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
585 status_t res =
586 fromAidlStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
587 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
588 if (res != OK) {
589 status << " (=> " << asString(res) << ")";
590 err = res;
591 }
592 mConfig.mCaptureFps = config.mCaptureFps;
593 mConfig.mCodedFps = config.mCodedFps;
594 }
595
596 if (config.mStartAtUs != mConfig.mStartAtUs
597 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
598 status_t res = fromAidlStatus(mSource->setStartTimeUs(config.mStartAtUs));
599 status << " start at " << config.mStartAtUs << "us";
600 if (res != OK) {
601 status << " (=> " << asString(res) << ")";
602 err = res;
603 }
604 mConfig.mStartAtUs = config.mStartAtUs;
605 mConfig.mStopped = config.mStopped;
606 }
607
608 // suspend-resume
609 if (config.mSuspended != mConfig.mSuspended) {
610 status_t res = fromAidlStatus(mSource->setSuspend(
611 config.mSuspended, config.mSuspendAtUs));
612 status << " " << (config.mSuspended ? "suspend" : "resume")
613 << " at " << config.mSuspendAtUs << "us";
614 if (res != OK) {
615 status << " (=> " << asString(res) << ")";
616 err = res;
617 }
618 mConfig.mSuspended = config.mSuspended;
619 mConfig.mSuspendAtUs = config.mSuspendAtUs;
620 }
621
622 if (config.mStopped != mConfig.mStopped && config.mStopped) {
623 status_t res = fromAidlStatus(mSource->setStopTimeUs(config.mStopAtUs));
624 status << " stop at " << config.mStopAtUs << "us";
625 if (res != OK) {
626 status << " (=> " << asString(res) << ")";
627 err = res;
628 } else {
629 status << " delayUs";
630 res = fromAidlStatus(mSource->getStopTimeOffsetUs(&config.mInputDelayUs));
631 if (res != OK) {
632 status << " (=> " << asString(res) << ")";
633 } else {
634 status << "=" << config.mInputDelayUs << "us";
635 }
636 mConfig.mInputDelayUs = config.mInputDelayUs;
637 }
638 mConfig.mStopAtUs = config.mStopAtUs;
639 mConfig.mStopped = config.mStopped;
640 }
641
642 // color aspects (android._color-aspects)
643
644 // consumer usage is queried earlier.
645
646 // priority
647 if (mConfig.mPriority != config.mPriority) {
648 if (config.mPriority != INT_MAX) {
649 mNode->setPriority(config.mPriority);
650 }
651 mConfig.mPriority = config.mPriority;
652 }
653
654 if (status.str().empty()) {
655 ALOGD("ISConfig not changed");
656 } else {
657 ALOGD("ISConfig%s", status.str().c_str());
658 }
659 return err;
660 }
661
662 void onInputBufferDone(c2_cntr64_t index) override {
663 mNode->onInputBufferDone(index);
664 }
665
666 android_dataspace getDataspace() override {
667 return mNode->getDataspace();
668 }
669
670 uint32_t getPixelFormat() override {
671 return mNode->getPixelFormat();
672 }
673
674private:
675 std::shared_ptr<AGraphicBufferSource> mSource;
676 std::shared_ptr<C2AidlNode> mNode;
677 uint32_t mWidth;
678 uint32_t mHeight;
679 Config mConfig;
680};
681
Pawin Vongmasa36653902018-11-15 00:10:25 -0800682class Codec2ClientInterfaceWrapper : public C2ComponentStore {
683 std::shared_ptr<Codec2Client> mClient;
684
685public:
686 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
687 : mClient(client) { }
688
689 virtual ~Codec2ClientInterfaceWrapper() = default;
690
691 virtual c2_status_t config_sm(
692 const std::vector<C2Param *> &params,
693 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
694 return mClient->config(params, C2_MAY_BLOCK, failures);
695 };
696
697 virtual c2_status_t copyBuffer(
698 std::shared_ptr<C2GraphicBuffer>,
699 std::shared_ptr<C2GraphicBuffer>) {
700 return C2_OMITTED;
701 }
702
703 virtual c2_status_t createComponent(
704 C2String, std::shared_ptr<C2Component> *const component) {
705 component->reset();
706 return C2_OMITTED;
707 }
708
709 virtual c2_status_t createInterface(
710 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
711 interface->reset();
712 return C2_OMITTED;
713 }
714
715 virtual c2_status_t query_sm(
716 const std::vector<C2Param *> &stackParams,
717 const std::vector<C2Param::Index> &heapParamIndices,
718 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
719 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
720 }
721
722 virtual c2_status_t querySupportedParams_nb(
723 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
724 return mClient->querySupportedParams(params);
725 }
726
727 virtual c2_status_t querySupportedValues_sm(
728 std::vector<C2FieldSupportedValuesQuery> &fields) const {
729 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
730 }
731
732 virtual C2String getName() const {
733 return mClient->getName();
734 }
735
736 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
737 return mClient->getParamReflector();
738 }
739
740 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
741 return std::vector<std::shared_ptr<const C2Component::Traits>>();
742 }
743};
744
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800745void RevertOutputFormatIfNeeded(
746 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
747 // We used to not report changes to these keys to the client.
748 const static std::set<std::string> sIgnoredKeys({
749 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800750 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800751 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800752 KEY_MAX_WIDTH,
753 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800754 "csd-0",
755 "csd-1",
756 "csd-2",
757 });
758 if (currentFormat == oldFormat) {
759 return;
760 }
761 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
762 AMessage::Type type;
763 for (size_t i = diff->countEntries(); i > 0; --i) {
764 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
765 diff->removeEntryAt(i - 1);
766 }
767 }
768 if (diff->countEntries() == 0) {
769 currentFormat = oldFormat;
770 }
771}
772
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700773void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700774 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700775 const sp<AMessage> &outputFormat) {
776 if (mediaType == MIMETYPE_VIDEO_AVC) {
777 // Codec specific data should be SPS and PPS in a single buffer,
778 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
779 // We separate the two and put them into the output format
780 // under the keys "csd-0" and "csd-1".
781
782 unsigned csdIndex = 0;
783
784 const uint8_t *nalStart;
785 size_t nalSize;
786 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
787 sp<ABuffer> csd = new ABuffer(nalSize + 4);
788 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
789 memcpy(csd->data() + 4, nalStart, nalSize);
790
791 outputFormat->setBuffer(
792 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
793
794 ++csdIndex;
795 }
796
797 if (csdIndex != 2) {
798 ALOGW("Expected two NAL units from AVC codec config, but %u found",
799 csdIndex);
800 }
801 } else {
802 // For everything else we just stash the codec specific data into
803 // the output format as a single piece of csd under "csd-0".
804 sp<ABuffer> csd = new ABuffer(size);
805 memcpy(csd->data(), data, size);
806 csd->setRange(0, size);
807 outputFormat->setBuffer("csd-0", csd);
808 }
809}
810
Pawin Vongmasa36653902018-11-15 00:10:25 -0800811} // namespace
812
813// CCodec::ClientListener
814
815struct CCodec::ClientListener : public Codec2Client::Listener {
816
817 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
818
819 virtual void onWorkDone(
820 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800821 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800822 (void)component;
823 sp<CCodec> codec(mCodec.promote());
824 if (!codec) {
825 return;
826 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800827 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800828 }
829
830 virtual void onTripped(
831 const std::weak_ptr<Codec2Client::Component>& component,
832 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
833 ) override {
834 // TODO
835 (void)component;
836 (void)settingResult;
837 }
838
839 virtual void onError(
840 const std::weak_ptr<Codec2Client::Component>& component,
841 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800842 {
843 // Component is only used for reporting as we use a separate listener for each instance
844 std::shared_ptr<Codec2Client::Component> comp = component.lock();
845 if (!comp) {
846 ALOGD("Component died with error: 0x%x", errorCode);
847 } else {
848 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
849 }
850 }
851
852 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800853 // Note: for now we do not propagate the error code to MediaCodec
854 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800855 sp<CCodec> codec(mCodec.promote());
856 if (!codec || !codec->mCallback) {
857 return;
858 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800859 codec->mCallback->onError(
860 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
861 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800862 }
863
864 virtual void onDeath(
865 const std::weak_ptr<Codec2Client::Component>& component) override {
866 { // Log the death of the component.
867 std::shared_ptr<Codec2Client::Component> comp = component.lock();
868 if (!comp) {
869 ALOGE("Codec2 component died.");
870 } else {
871 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
872 }
873 }
874
875 // Report to MediaCodec.
876 sp<CCodec> codec(mCodec.promote());
877 if (!codec || !codec->mCallback) {
878 return;
879 }
880 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
881 }
882
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800883 virtual void onFrameRendered(uint64_t bufferQueueId,
884 int32_t slotId,
885 int64_t timestampNs) override {
886 // TODO: implement
887 (void)bufferQueueId;
888 (void)slotId;
889 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800890 }
891
892 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800893 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800894 sp<CCodec> codec(mCodec.promote());
895 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800896 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800897 }
898 }
899
900private:
901 wp<CCodec> mCodec;
902};
903
904// CCodecCallbackImpl
905
906class CCodecCallbackImpl : public CCodecCallback {
907public:
908 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
909 ~CCodecCallbackImpl() override = default;
910
911 void onError(status_t err, enum ActionCode actionCode) override {
912 mCodec->mCallback->onError(err, actionCode);
913 }
914
915 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
Brian Lindahlff74e9d2023-07-20 14:44:04 -0600916 mCodec->mCallback->onOutputFramesRendered({RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
Pawin Vongmasa36653902018-11-15 00:10:25 -0800917 }
918
Pawin Vongmasa36653902018-11-15 00:10:25 -0800919 void onOutputBuffersChanged() override {
920 mCodec->mCallback->onOutputBuffersChanged();
921 }
922
Guillaume Chelfi5ffbcb32021-04-12 14:23:43 +0200923 void onFirstTunnelFrameReady() override {
924 mCodec->mCallback->onFirstTunnelFrameReady();
925 }
926
Pawin Vongmasa36653902018-11-15 00:10:25 -0800927private:
928 CCodec *mCodec;
929};
930
931// CCodec
932
933CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700934 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
935 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800936}
937
938CCodec::~CCodec() {
939}
940
941std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
942 return mChannel;
943}
944
945status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
946 status_t err = job();
947 if (err != C2_OK) {
948 mCallback->onError(err, ACTION_CODE_FATAL);
949 }
950 return err;
951}
952
953void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
954 auto setAllocating = [this] {
955 Mutexed<State>::Locked state(mState);
956 if (state->get() != RELEASED) {
957 return INVALID_OPERATION;
958 }
959 state->set(ALLOCATING);
960 return OK;
961 };
962 if (tryAndReportOnError(setAllocating) != OK) {
963 return;
964 }
965
966 sp<RefBase> codecInfo;
967 CHECK(msg->findObject("codecInfo", &codecInfo));
968 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
969
970 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
971 allocMsg->setObject("codecInfo", codecInfo);
972 allocMsg->post();
973}
974
975void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
976 if (codecInfo == nullptr) {
977 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
978 return;
979 }
980 ALOGD("allocate(%s)", codecInfo->getCodecName());
981 mClientListener.reset(new ClientListener(this));
982
983 AString componentName = codecInfo->getCodecName();
984 std::shared_ptr<Codec2Client> client;
985
986 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700987 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800988 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800989 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800990 SetPreferredCodec2ComponentStore(
991 std::make_shared<Codec2ClientInterfaceWrapper>(client));
992 }
993
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900994 std::shared_ptr<Codec2Client::Component> comp;
995 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800996 componentName.c_str(),
997 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900998 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800999 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +09001000 if (status != C2_OK) {
1001 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001002 Mutexed<State>::Locked state(mState);
1003 state->set(RELEASED);
1004 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +09001005 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001006 state.lock();
1007 return;
1008 }
1009 ALOGI("Created component [%s]", componentName.c_str());
1010 mChannel->setComponent(comp);
1011 auto setAllocated = [this, comp, client] {
1012 Mutexed<State>::Locked state(mState);
1013 if (state->get() != ALLOCATING) {
1014 state->set(RELEASED);
1015 return UNKNOWN_ERROR;
1016 }
1017 state->set(ALLOCATED);
1018 state->comp = comp;
1019 mClient = client;
1020 return OK;
1021 };
1022 if (tryAndReportOnError(setAllocated) != OK) {
1023 return;
1024 }
1025
1026 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001027 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1028 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001029 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001030 if (err != OK) {
1031 ALOGW("Failed to initialize configuration support");
1032 // TODO: report error once we complete implementation.
1033 }
1034 config->queryConfiguration(comp);
1035
1036 mCallback->onComponentAllocated(componentName.c_str());
1037}
1038
1039void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
1040 auto checkAllocated = [this] {
1041 Mutexed<State>::Locked state(mState);
1042 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
1043 };
1044 if (tryAndReportOnError(checkAllocated) != OK) {
1045 return;
1046 }
1047
1048 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
1049 msg->setMessage("format", format);
1050 msg->post();
1051}
1052
1053void CCodec::configure(const sp<AMessage> &msg) {
1054 std::shared_ptr<Codec2Client::Component> comp;
1055 auto checkAllocated = [this, &comp] {
1056 Mutexed<State>::Locked state(mState);
1057 if (state->get() != ALLOCATED) {
1058 state->set(RELEASED);
1059 return UNKNOWN_ERROR;
1060 }
1061 comp = state->comp;
1062 return OK;
1063 };
1064 if (tryAndReportOnError(checkAllocated) != OK) {
1065 return;
1066 }
1067
1068 auto doConfig = [msg, comp, this]() -> status_t {
1069 AString mime;
1070 if (!msg->findString("mime", &mime)) {
1071 return BAD_VALUE;
1072 }
1073
1074 int32_t encoder;
1075 if (!msg->findInt32("encoder", &encoder)) {
1076 encoder = false;
1077 }
1078
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001079 int32_t flags;
1080 if (!msg->findInt32("flags", &flags)) {
1081 return BAD_VALUE;
1082 }
1083
Pawin Vongmasa36653902018-11-15 00:10:25 -08001084 // TODO: read from intf()
1085 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
1086 return UNKNOWN_ERROR;
1087 }
1088
1089 int32_t storeMeta;
1090 if (encoder
1091 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
1092 && storeMeta != kMetadataBufferTypeInvalid) {
1093 if (storeMeta != kMetadataBufferTypeANWBuffer) {
1094 ALOGD("Only ANW buffers are supported for legacy metadata mode");
1095 return BAD_VALUE;
1096 }
1097 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
1098 }
1099
ted.sun765db4d2020-06-23 14:03:41 +08001100 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001101 sp<RefBase> obj;
1102 sp<Surface> surface;
1103 if (msg->findObject("native-window", &obj)) {
1104 surface = static_cast<Surface *>(obj.get());
Sungtak Lee214ce612023-11-01 10:01:13 +00001105 int32_t generation;
1106 (void)msg->findInt32("native-window-generation", &generation);
ted.sun765db4d2020-06-23 14:03:41 +08001107 // setup tunneled playback
1108 if (surface != nullptr) {
1109 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1110 const std::unique_ptr<Config> &config = *configLocked;
1111 if ((config->mDomain & Config::IS_DECODER)
1112 && (config->mDomain & Config::IS_VIDEO)) {
1113 int32_t tunneled;
1114 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
1115 ALOGI("Configuring TUNNELED video playback.");
1116
1117 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
1118 if (err != OK) {
1119 ALOGE("configureTunneledVideoPlayback failed!");
1120 return err;
1121 }
1122 config->mTunneled = true;
1123 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +01001124
1125 int32_t pushBlankBuffersOnStop = 0;
1126 if (msg->findInt32(KEY_PUSH_BLANK_BUFFERS_ON_STOP, &pushBlankBuffersOnStop)) {
1127 config->mPushBlankBuffersOnStop = pushBlankBuffersOnStop == 1;
1128 }
shuanglong.wang480a8362023-02-17 20:55:51 +08001129 // secure compoment or protected content default with
1130 // "push-blank-buffers-on-shutdown" flag
1131 if (!config->mPushBlankBuffersOnStop) {
1132 int32_t usageProtected;
1133 if (comp->getName().find(".secure") != std::string::npos) {
1134 config->mPushBlankBuffersOnStop = true;
1135 } else if (msg->findInt32("protected", &usageProtected) && usageProtected) {
1136 config->mPushBlankBuffersOnStop = true;
1137 }
1138 }
ted.sun765db4d2020-06-23 14:03:41 +08001139 }
1140 }
Sungtak Lee214ce612023-11-01 10:01:13 +00001141 setSurface(surface, (uint32_t)generation);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001142 }
1143
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001144 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1145 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001146 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001147 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
1148 ALOGD("[%s] buffers are %sbound to CCodec for this session",
1149 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001150
Wonsik Kim1114eea2019-02-25 14:35:24 -08001151 // Enforce required parameters
1152 int32_t i32;
1153 float flt;
1154 if (config->mDomain & Config::IS_AUDIO) {
1155 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
1156 ALOGD("sample rate is missing, which is required for audio components.");
1157 return BAD_VALUE;
1158 }
1159 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
1160 ALOGD("channel count is missing, which is required for audio components.");
1161 return BAD_VALUE;
1162 }
1163 if ((config->mDomain & Config::IS_ENCODER)
1164 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
1165 && !msg->findInt32(KEY_BIT_RATE, &i32)
1166 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
1167 ALOGD("bitrate is missing, which is required for audio encoders.");
1168 return BAD_VALUE;
1169 }
1170 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001171 int32_t width = 0;
1172 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -08001173 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001174 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -08001175 ALOGD("width is missing, which is required for image/video components.");
1176 return BAD_VALUE;
1177 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001178 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -08001179 ALOGD("height is missing, which is required for image/video components.");
1180 return BAD_VALUE;
1181 }
1182 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -07001183 int32_t mode = BITRATE_MODE_VBR;
1184 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -07001185 if (!msg->findInt32(KEY_QUALITY, &i32)) {
1186 ALOGD("quality is missing, which is required for video encoders in CQ.");
1187 return BAD_VALUE;
1188 }
1189 } else {
1190 if (!msg->findInt32(KEY_BIT_RATE, &i32)
1191 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
1192 ALOGD("bitrate is missing, which is required for video encoders.");
1193 return BAD_VALUE;
1194 }
Wonsik Kim1114eea2019-02-25 14:35:24 -08001195 }
1196 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
1197 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
1198 ALOGD("I frame interval is missing, which is required for video encoders.");
1199 return BAD_VALUE;
1200 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001201 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
1202 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
1203 ALOGD("frame rate is missing, which is required for video encoders.");
1204 return BAD_VALUE;
1205 }
Wonsik Kim1114eea2019-02-25 14:35:24 -08001206 }
1207 }
1208
Pawin Vongmasa36653902018-11-15 00:10:25 -08001209 /*
1210 * Handle input surface configuration
1211 */
1212 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1213 && (config->mDomain & Config::IS_ENCODER)) {
1214 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
1215 {
1216 config->mISConfig->mMinFps = 0;
1217 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001218 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001219 config->mISConfig->mMinFps = 1e6 / value;
1220 }
Wonsik Kim95ba0162019-03-19 15:51:54 -07001221 if (!msg->findFloat(
1222 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
1223 config->mISConfig->mMaxFps = -1;
1224 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001225 config->mISConfig->mMinAdjustedFps = 0;
1226 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -08001227 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001228 if (value < 0 && value >= INT32_MIN) {
1229 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001230 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001231 } else if (value > 0 && value <= INT32_MAX) {
1232 config->mISConfig->mMinAdjustedFps = 1e6 / value;
1233 }
1234 }
1235 }
1236
1237 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -07001238 bool captureFpsFound = false;
1239 double timeLapseFps;
1240 float captureRate;
1241 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
1242 config->mISConfig->mCaptureFps = timeLapseFps;
1243 captureFpsFound = true;
1244 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
1245 config->mISConfig->mCaptureFps = captureRate;
1246 captureFpsFound = true;
1247 }
1248 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001249 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
1250 }
1251 }
1252
1253 {
1254 config->mISConfig->mSuspended = false;
1255 config->mISConfig->mSuspendAtUs = -1;
1256 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001257 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001258 config->mISConfig->mSuspended = true;
1259 }
1260 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001261 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -07001262 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001263 }
1264
1265 /*
1266 * Handle desired color format.
1267 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001268 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001269 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001270 int32_t format = 0;
1271 // Query vendor format for Flexible YUV
1272 std::vector<std::unique_ptr<C2Param>> heapParams;
1273 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
Wonsik Kim50811882022-04-28 15:57:27 -07001274 int vendorSdkVersion = base::GetIntProperty(
1275 "ro.vendor.build.version.sdk", android_get_device_api_level());
guochuang709b48b2022-10-25 20:40:42 +08001276 if (mClient->query(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001277 {},
1278 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1279 C2_MAY_BLOCK,
1280 &heapParams) == C2_OK
1281 && heapParams.size() == 1u) {
1282 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1283 heapParams[0].get());
1284 } else {
1285 pixelFormatInfo = nullptr;
1286 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001287 // bit depth -> format
1288 std::map<uint32_t, uint32_t> flexPixelFormat;
1289 std::map<uint32_t, uint32_t> flexPlanarPixelFormat;
1290 std::map<uint32_t, uint32_t> flexSemiPlanarPixelFormat;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001291 if (pixelFormatInfo && *pixelFormatInfo) {
1292 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1293 const C2FlexiblePixelFormatDescriptorStruct &desc =
1294 pixelFormatInfo->m.values[i];
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001295 if (desc.subsampling != C2Color::YUV_420
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001296 // TODO(b/180076105): some device report wrong layout
1297 // || desc.layout == C2Color::INTERLEAVED_PACKED
1298 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1299 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1300 continue;
1301 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001302 if (flexPixelFormat.count(desc.bitDepth) == 0) {
1303 flexPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001304 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001305 if (desc.layout == C2Color::PLANAR_PACKED
1306 && flexPlanarPixelFormat.count(desc.bitDepth) == 0) {
1307 flexPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001308 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001309 if (desc.layout == C2Color::SEMIPLANAR_PACKED
1310 && flexSemiPlanarPixelFormat.count(desc.bitDepth) == 0) {
1311 flexSemiPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001312 }
1313 }
1314 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001315 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001316 // Also handle default color format (encoders require color format, so this is only
1317 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001318 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001319 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001320 const char *prefix = "";
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001321 if (flexSemiPlanarPixelFormat.count(8) != 0) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001322 format = COLOR_FormatYUV420SemiPlanar;
1323 prefix = "semi-";
1324 } else {
1325 format = COLOR_FormatYUV420Planar;
1326 }
1327 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1328 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001329 } else {
1330 format = COLOR_FormatSurface;
1331 }
1332 defaultColorFormat = format;
1333 }
1334 } else {
1335 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001336 if (vendorSdkVersion < __ANDROID_API_S__ &&
Taehwan Kim43e715d2022-09-22 12:04:59 +09001337 (format == COLOR_FormatYUV420Planar ||
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001338 format == COLOR_FormatYUV420PackedPlanar ||
1339 format == COLOR_FormatYUV420SemiPlanar ||
1340 format == COLOR_FormatYUV420PackedSemiPlanar)) {
1341 // pre-S framework used to map these color formats into YV12.
1342 // Codecs from older vendor partition may be relying on
1343 // this assumption.
1344 format = HAL_PIXEL_FORMAT_YV12;
1345 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001346 switch (format) {
1347 case COLOR_FormatYUV420Flexible:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001348 format = COLOR_FormatYUV420Planar;
1349 if (flexPixelFormat.count(8) != 0) {
1350 format = flexPixelFormat[8];
1351 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001352 break;
1353 case COLOR_FormatYUV420Planar:
1354 case COLOR_FormatYUV420PackedPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001355 if (flexPlanarPixelFormat.count(8) != 0) {
1356 format = flexPlanarPixelFormat[8];
1357 } else if (flexPixelFormat.count(8) != 0) {
1358 format = flexPixelFormat[8];
1359 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001360 break;
1361 case COLOR_FormatYUV420SemiPlanar:
1362 case COLOR_FormatYUV420PackedSemiPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001363 if (flexSemiPlanarPixelFormat.count(8) != 0) {
1364 format = flexSemiPlanarPixelFormat[8];
1365 } else if (flexPixelFormat.count(8) != 0) {
1366 format = flexPixelFormat[8];
1367 }
1368 break;
1369 case COLOR_FormatYUVP010:
1370 format = COLOR_FormatYUVP010;
1371 if (flexSemiPlanarPixelFormat.count(10) != 0) {
1372 format = flexSemiPlanarPixelFormat[10];
1373 } else if (flexPixelFormat.count(10) != 0) {
1374 format = flexPixelFormat[10];
1375 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001376 break;
1377 default:
1378 // No-op
1379 break;
1380 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001381 }
1382 }
1383
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001384 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001385 msg->setInt32("android._color-format", format);
1386 }
1387 }
1388
Wonsik Kim77e97c72021-01-20 10:33:22 -08001389 /*
1390 * Handle dataspace
1391 */
1392 int32_t usingRecorder;
1393 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1394 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1395 int32_t width, height;
1396 if (msg->findInt32("width", &width)
1397 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001398 ColorAspects aspects;
1399 getColorAspectsFromFormat(msg, aspects);
1400 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001401 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001402 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1403 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001404 }
1405 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1406 ALOGD("setting dataspace to %x", dataSpace);
1407 }
1408
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001409 int32_t subscribeToAllVendorParams;
1410 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1411 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1412 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1413 }
1414 }
1415
Ram Mohan16511072023-12-11 19:41:31 +05301416 /*
1417 * configure mock region of interest if Feature_Roi is enabled
1418 */
1419 if (android::media::codec::provider_->region_of_interest()
1420 && android::media::codec::provider_->region_of_interest_support()) {
1421 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
1422 int32_t enableRoi;
1423 if (msg->findInt32("feature-region-of-interest", &enableRoi) && enableRoi != 0) {
1424 if (!msg->contains(PARAMETER_KEY_QP_OFFSET_MAP) &&
1425 !msg->contains(PARAMETER_KEY_QP_OFFSET_RECTS)) {
1426 msg->setString(PARAMETER_KEY_QP_OFFSET_RECTS,
1427 AStringPrintf("%d,%d-%d,%d=%d;", 0, 0, 16, 16, 0));
1428 }
1429 }
1430 }
1431 }
1432
Pawin Vongmasa36653902018-11-15 00:10:25 -08001433 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001434 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1435 // the behavior here.
1436 sp<AMessage> sdkParams = msg;
1437 int32_t videoBitrate;
1438 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1439 sdkParams = msg->dup();
1440 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1441 }
ted.sun765db4d2020-06-23 14:03:41 +08001442 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001443 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001444 if (err != OK) {
1445 ALOGW("failed to convert configuration to c2 params");
1446 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001447
1448 int32_t maxBframes = 0;
1449 if ((config->mDomain & Config::IS_ENCODER)
1450 && (config->mDomain & Config::IS_VIDEO)
1451 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1452 && maxBframes > 0) {
1453 std::unique_ptr<C2StreamGopTuning::output> gop =
1454 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1455 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1456 gop->m.values[1] = {
1457 C2Config::picture_type_t(P_FRAME | B_FRAME),
1458 uint32_t(maxBframes)
1459 };
1460 configUpdate.push_back(std::move(gop));
1461 }
1462
Ray Essicka0ae6972021-03-10 19:40:01 -08001463 if ((config->mDomain & Config::IS_ENCODER)
1464 && (config->mDomain & Config::IS_VIDEO)) {
1465 // we may not use all 3 of these entries
1466 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1467 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1468 0u /* stream */);
1469
1470 int ix = 0;
1471
1472 int32_t iMax = INT32_MAX;
1473 int32_t iMin = INT32_MIN;
1474 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1475 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1476 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1477 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1478 }
1479
1480 int32_t pMax = INT32_MAX;
1481 int32_t pMin = INT32_MIN;
1482 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1483 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1484 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1485 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1486 }
1487
1488 int32_t bMax = INT32_MAX;
1489 int32_t bMin = INT32_MIN;
1490 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1491 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1492 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1493 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1494 }
1495
1496 // adjust to reflect actual use.
1497 qp->setFlexCount(ix);
1498
1499 configUpdate.push_back(std::move(qp));
1500 }
1501
Wonsik Kima1335e12021-04-22 16:28:29 -07001502 int32_t background = 0;
1503 if ((config->mDomain & Config::IS_VIDEO)
1504 && msg->findInt32("android._background-mode", &background)
1505 && background) {
1506 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1507 if (config->mISConfig) {
1508 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1509 }
1510 }
1511
Pawin Vongmasa36653902018-11-15 00:10:25 -08001512 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1513 if (err != OK) {
1514 ALOGW("failed to configure c2 params");
1515 return err;
1516 }
1517
1518 std::vector<std::unique_ptr<C2Param>> params;
1519 C2StreamUsageTuning::input usage(0u, 0u);
1520 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001521 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001522
Wonsik Kim3baecda2021-02-07 22:19:56 -08001523 C2Param::Index colorAspectsRequestIndex =
1524 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001525 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001526 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001527 };
Chaejung Lim86c22dc2021-12-23 00:41:05 -08001528 int32_t colorTransferRequest = 0;
1529 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1530 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1531 colorTransferRequest = 0;
1532 }
1533 c2_status_t c2err = C2_OK;
1534 if (colorTransferRequest != 0) {
1535 c2err = comp->query(
1536 { &usage, &maxInputSize, &prepend },
1537 indices,
1538 C2_DONT_BLOCK,
1539 &params);
1540 } else {
1541 c2err = comp->query(
1542 { &usage, &maxInputSize, &prepend },
1543 {},
1544 C2_DONT_BLOCK,
1545 &params);
1546 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001547 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1548 ALOGE("Failed to query component interface: %d", c2err);
1549 return UNKNOWN_ERROR;
1550 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001551 if (usage) {
1552 if (usage.value & C2MemoryUsage::CPU_READ) {
1553 config->mInputFormat->setInt32("using-sw-read-often", true);
1554 }
1555 if (config->mISConfig) {
1556 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1557 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1558 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001559 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001560 }
1561
1562 // NOTE: we don't blindly use client specified input size if specified as clients
1563 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1564 // client specified size is only used to ask for bigger buffers than component suggested
1565 // size.
1566 int32_t clientInputSize = 0;
1567 bool clientSpecifiedInputSize =
1568 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1569 // TEMP: enforce minimum buffer size of 1MB for video decoders
1570 // and 16K / 4K for audio encoders/decoders
1571 if (maxInputSize.value == 0) {
1572 if (config->mDomain & Config::IS_AUDIO) {
1573 maxInputSize.value = encoder ? 16384 : 4096;
1574 } else if (!encoder) {
1575 maxInputSize.value = 1048576u;
1576 }
1577 }
1578
1579 // verify that CSD fits into this size (if defined)
1580 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1581 sp<ABuffer> csd;
1582 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1583 if (csd && csd->size() > maxInputSize.value) {
1584 maxInputSize.value = csd->size();
1585 }
1586 }
1587 }
1588
1589 // TODO: do this based on component requiring linear allocator for input
1590 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1591 if (clientSpecifiedInputSize) {
1592 // Warn that we're overriding client's max input size if necessary.
1593 if ((uint32_t)clientInputSize < maxInputSize.value) {
1594 ALOGD("client requested max input size %d, which is smaller than "
1595 "what component recommended (%u); overriding with component "
1596 "recommendation.", clientInputSize, maxInputSize.value);
1597 ALOGW("This behavior is subject to change. It is recommended that "
1598 "app developers double check whether the requested "
1599 "max input size is in reasonable range.");
1600 } else {
1601 maxInputSize.value = clientInputSize;
1602 }
1603 }
1604 // Pass max input size on input format to the buffer channel (if supplied by the
1605 // component or by a default)
1606 if (maxInputSize.value) {
1607 config->mInputFormat->setInt32(
1608 KEY_MAX_INPUT_SIZE,
1609 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1610 }
1611 }
1612
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001613 int32_t clientPrepend;
1614 if ((config->mDomain & Config::IS_VIDEO)
1615 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001616 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001617 && clientPrepend
1618 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001619 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001620 return BAD_VALUE;
1621 }
1622
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001623 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001624 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1625 // propagate HDR static info to output format for both encoders and decoders
1626 // if component supports this info, we will update from component, but only the raw port,
1627 // so don't propagate if component already filled it in.
1628 sp<ABuffer> hdrInfo;
1629 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1630 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1631 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1632 }
1633
1634 // Set desired color format from configuration parameter
1635 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001636 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1637 format = defaultColorFormat;
1638 }
1639 if (config->mDomain & Config::IS_ENCODER) {
1640 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001641 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1642 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001643 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001644 } else {
1645 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001646 }
1647 }
1648
1649 // propagate encoder delay and padding to output format
1650 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1651 int delay = 0;
1652 if (msg->findInt32("encoder-delay", &delay)) {
1653 config->mOutputFormat->setInt32("encoder-delay", delay);
1654 }
1655 int padding = 0;
1656 if (msg->findInt32("encoder-padding", &padding)) {
1657 config->mOutputFormat->setInt32("encoder-padding", padding);
1658 }
1659 }
1660
Pawin Vongmasa36653902018-11-15 00:10:25 -08001661 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001662 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001663 int32_t mask;
1664 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1665 if (config->mDomain & Config::IS_ENCODER) {
1666 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1667 } else {
1668 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1669 }
1670 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001671
1672 // set PCM encoding
1673 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1674 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1675 if (encoder) {
1676 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1677 } else {
1678 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1679 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001680 }
1681
Wonsik Kim3baecda2021-02-07 22:19:56 -08001682 std::unique_ptr<C2Param> colorTransferRequestParam;
1683 for (std::unique_ptr<C2Param> &param : params) {
1684 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1685 ALOGI("found color transfer request param");
1686 colorTransferRequestParam = std::move(param);
1687 }
1688 }
Wonsik Kim3baecda2021-02-07 22:19:56 -08001689
1690 if (colorTransferRequest != 0) {
1691 if (colorTransferRequestParam && *colorTransferRequestParam) {
1692 C2StreamColorAspectsInfo::output *info =
1693 static_cast<C2StreamColorAspectsInfo::output *>(
1694 colorTransferRequestParam.get());
1695 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1696 colorTransferRequest = 0;
1697 }
1698 } else {
1699 colorTransferRequest = 0;
1700 }
1701 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1702 }
1703
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001704 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1705 // Need to get stride/vstride
1706 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1707 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1708 // TODO: retrieve these values without allocating a buffer.
1709 // Currently allocating a buffer is necessary to retrieve the layout.
1710 int64_t blockUsage =
1711 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1712 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
Harish Mahendrakarf6b3e5e2024-03-21 21:04:28 +00001713 align(width, 2), align(height, 2), componentColorFormat, blockUsage,
1714 {comp->getName()});
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001715 sp<GraphicBlockBuffer> buffer;
1716 if (block) {
1717 buffer = GraphicBlockBuffer::Allocate(
1718 config->mInputFormat,
1719 block,
1720 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1721 } else {
1722 ALOGD("Failed to allocate a graphic block "
1723 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1724 width, height, pixelFormat, (long long)blockUsage);
1725 // This means that byte buffer mode is not supported in this configuration
1726 // anyway. Skip setting stride/vstride to input format.
1727 }
1728 if (buffer) {
1729 sp<ABuffer> imageData = buffer->getImageData();
1730 MediaImage2 *img = nullptr;
1731 if (imageData && imageData->data()
1732 && imageData->size() >= sizeof(MediaImage2)) {
1733 img = (MediaImage2*)imageData->data();
1734 }
1735 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1736 int32_t stride = img->mPlane[0].mRowInc;
1737 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1738 if (img->mNumPlanes > 1 && stride > 0) {
1739 int64_t offsetDelta =
1740 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1741 if (offsetDelta % stride == 0) {
1742 int32_t vstride = int32_t(offsetDelta / stride);
1743 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1744 } else {
1745 ALOGD("Cannot report accurate slice height: "
1746 "offsetDelta = %lld stride = %d",
1747 (long long)offsetDelta, stride);
1748 }
1749 }
1750 }
1751 }
1752 }
1753 }
1754
Wonsik Kimec585c32021-10-01 01:11:00 -07001755 if (config->mTunneled) {
1756 config->mOutputFormat->setInt32("android._tunneled", 1);
1757 }
1758
Yushin Cho91873b52021-12-21 04:08:35 -08001759 // Convert an encoding statistics level to corresponding encoding statistics
1760 // kinds
1761 int32_t encodingStatisticsLevel = VIDEO_ENCODING_STATISTICS_LEVEL_NONE;
1762 if ((config->mDomain & Config::IS_ENCODER)
1763 && (config->mDomain & Config::IS_VIDEO)
1764 && msg->findInt32(KEY_VIDEO_ENCODING_STATISTICS_LEVEL, &encodingStatisticsLevel)) {
1765 // Higher level include all the enc stats belong to lower level.
1766 switch (encodingStatisticsLevel) {
1767 // case VIDEO_ENCODING_STATISTICS_LEVEL_2: // reserved for the future level 2
1768 // with more enc stat kinds
1769 // Future extended encoding statistics for the level 2 should be added here
1770 case VIDEO_ENCODING_STATISTICS_LEVEL_1:
Wonsik Kimeebab652022-06-02 13:01:55 -07001771 config->subscribeToConfigUpdate(
1772 comp,
1773 {
1774 C2AndroidStreamAverageBlockQuantizationInfo::output::PARAM_TYPE,
1775 C2StreamPictureTypeInfo::output::PARAM_TYPE,
1776 });
Yushin Cho91873b52021-12-21 04:08:35 -08001777 break;
1778 case VIDEO_ENCODING_STATISTICS_LEVEL_NONE:
1779 break;
1780 }
1781 }
1782 ALOGD("encoding statistics level = %d", encodingStatisticsLevel);
1783
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001784 ALOGD("setup formats input: %s",
1785 config->mInputFormat->debugString().c_str());
1786 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001787 config->mOutputFormat->debugString().c_str());
1788 return OK;
1789 };
1790 if (tryAndReportOnError(doConfig) != OK) {
1791 return;
1792 }
1793
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001794 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1795 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001796
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001797 config->queryConfiguration(comp);
1798
Songyue Han1e6769b2023-08-30 18:09:27 +00001799 mMetrics = new AMessage;
1800 mChannel->resetBuffersPixelFormat((config->mDomain & Config::IS_ENCODER) ? true : false);
1801
Pawin Vongmasa36653902018-11-15 00:10:25 -08001802 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1803}
1804
1805void CCodec::initiateCreateInputSurface() {
1806 status_t err = [this] {
1807 Mutexed<State>::Locked state(mState);
1808 if (state->get() != ALLOCATED) {
1809 return UNKNOWN_ERROR;
1810 }
1811 // TODO: read it from intf() properly.
1812 if (state->comp->getName().find("encoder") == std::string::npos) {
1813 return INVALID_OPERATION;
1814 }
1815 return OK;
1816 }();
1817 if (err != OK) {
1818 mCallback->onInputSurfaceCreationFailed(err);
1819 return;
1820 }
1821
1822 (new AMessage(kWhatCreateInputSurface, this))->post();
1823}
1824
Lajos Molnar47118272019-01-31 16:28:04 -08001825sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1826 using namespace android::hardware::media::omx::V1_0;
1827 using namespace android::hardware::media::omx::V1_0::utils;
1828 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1829 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1830 android::sp<IOmx> omx = IOmx::getService();
Sungtak Lee47dcb482022-04-15 10:47:08 -07001831 if (omx == nullptr) {
1832 return nullptr;
1833 }
Lajos Molnar47118272019-01-31 16:28:04 -08001834 typedef android::hardware::graphics::bufferqueue::V1_0::
1835 IGraphicBufferProducer HGraphicBufferProducer;
1836 typedef android::hardware::media::omx::V1_0::
1837 IGraphicBufferSource HGraphicBufferSource;
1838 OmxStatus s;
1839 android::sp<HGraphicBufferProducer> gbp;
1840 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001841
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001842 using ::android::hardware::Return;
1843 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001844 [&s, &gbp, &gbs](
1845 OmxStatus status,
1846 const android::sp<HGraphicBufferProducer>& producer,
1847 const android::sp<HGraphicBufferSource>& source) {
1848 s = status;
1849 gbp = producer;
1850 gbs = source;
1851 });
1852 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001853 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001854 }
1855
1856 return nullptr;
1857}
1858
1859sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1860 sp<PersistentSurface> surface(CreateInputSurface());
1861
1862 if (surface == nullptr) {
1863 surface = CreateOmxInputSurface();
1864 }
1865
1866 return surface;
1867}
1868
Pawin Vongmasa36653902018-11-15 00:10:25 -08001869void CCodec::createInputSurface() {
1870 status_t err;
1871 sp<IGraphicBufferProducer> bufferProducer;
1872
Pawin Vongmasa36653902018-11-15 00:10:25 -08001873 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001874 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001875 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001876 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1877 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001878 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001879 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001880 }
1881
Lajos Molnar47118272019-01-31 16:28:04 -08001882 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Sungtak Lee92bca442024-03-12 09:10:31 +00001883 if (persistentSurface->isTargetAidl()) {
1884 ::ndk::SpAIBinder aidlTarget = persistentSurface->getAidlTarget();
1885 std::shared_ptr<AGraphicBufferSource> gbs = AGraphicBufferSource::fromBinder(aidlTarget);
1886 if (gbs) {
1887 int32_t width = 0;
1888 (void)outputFormat->findInt32("width", &width);
1889 int32_t height = 0;
1890 (void)outputFormat->findInt32("height", &height);
1891 err = setupInputSurface(std::make_shared<AGraphicBufferSourceWrapper>(
1892 gbs, width, height, usage));
1893 bufferProducer = persistentSurface->getBufferProducer();
1894 } else {
1895 ALOGE("Corrupted input surface(aidl)");
1896 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1897 return;
1898 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001899 } else {
Sungtak Lee92bca442024-03-12 09:10:31 +00001900 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1901 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1902 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1903
1904 if (hidlInputSurface) {
1905 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1906 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
1907 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1908 inputSurface));
1909 bufferProducer = inputSurface->getGraphicBufferProducer();
1910 } else if (gbs) {
1911 int32_t width = 0;
1912 (void)outputFormat->findInt32("width", &width);
1913 int32_t height = 0;
1914 (void)outputFormat->findInt32("height", &height);
1915 err = setupInputSurface(std::make_shared<HGraphicBufferSourceWrapper>(
1916 gbs, width, height, usage));
1917 bufferProducer = persistentSurface->getBufferProducer();
1918 } else {
1919 ALOGE("Corrupted input surface");
1920 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1921 return;
1922 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001923 }
1924
1925 if (err != OK) {
1926 ALOGE("Failed to set up input surface: %d", err);
1927 mCallback->onInputSurfaceCreationFailed(err);
1928 return;
1929 }
1930
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001931 // Formats can change after setupInputSurface
1932 sp<AMessage> inputFormat;
1933 {
1934 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1935 const std::unique_ptr<Config> &config = *configLocked;
1936 inputFormat = config->mInputFormat;
1937 outputFormat = config->mOutputFormat;
1938 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001939 mCallback->onInputSurfaceCreated(
1940 inputFormat,
1941 outputFormat,
1942 new BufferProducerWrapper(bufferProducer));
1943}
1944
1945status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001946 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1947 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001948 config->mUsingSurface = true;
1949
1950 // we are now using surface - apply default color aspects to input format - as well as
1951 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001952 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001953
1954 // configure dataspace
1955 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
Wonsik Kim66b19552021-08-02 16:07:49 -07001956
1957 // The output format contains app-configured color aspects, and the input format
1958 // has the default color aspects. Use the default for the unspecified params.
1959 ColorAspects inputColorAspects, colorAspects;
1960 getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
1961 getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
1962 if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
1963 colorAspects.mRange = inputColorAspects.mRange;
1964 }
1965 if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
1966 colorAspects.mPrimaries = inputColorAspects.mPrimaries;
1967 }
1968 if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
1969 colorAspects.mTransfer = inputColorAspects.mTransfer;
1970 }
1971 if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
1972 colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
1973 }
1974 android_dataspace dataSpace = getDataSpaceForColorAspects(
1975 colorAspects, /* mayExtend = */ false);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001976 surface->setDataSpace(dataSpace);
Wonsik Kim66b19552021-08-02 16:07:49 -07001977 setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
1978 config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
1979
1980 ALOGD("input format %s to %s",
1981 inputFormatChanged ? "changed" : "unchanged",
1982 config->mInputFormat->debugString().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001983
1984 status_t err = mChannel->setInputSurface(surface);
1985 if (err != OK) {
1986 // undo input format update
1987 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001988 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001989 return err;
1990 }
1991 config->mInputSurface = surface;
1992
1993 if (config->mISConfig) {
1994 surface->configure(*config->mISConfig);
1995 } else {
1996 ALOGD("ISConfig: no configuration");
1997 }
1998
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001999 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002000}
2001
2002void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
2003 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
2004 msg->setObject("surface", surface);
2005 msg->post();
2006}
2007
2008void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002009 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07002010 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002011 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002012 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2013 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002014 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07002015 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002016 }
Sungtak Lee92bca442024-03-12 09:10:31 +00002017 if (surface->isTargetAidl()) {
2018 ::ndk::SpAIBinder aidlTarget = surface->getAidlTarget();
2019 std::shared_ptr<AGraphicBufferSource> gbs = AGraphicBufferSource::fromBinder(aidlTarget);
2020 if (gbs) {
2021 int32_t width = 0;
2022 (void)outputFormat->findInt32("width", &width);
2023 int32_t height = 0;
2024 (void)outputFormat->findInt32("height", &height);
2025
2026 status_t err = setupInputSurface(std::make_shared<AGraphicBufferSourceWrapper>(
2027 gbs, width, height, usage));
2028 if (err != OK) {
2029 ALOGE("Failed to set up input surface(aidl): %d", err);
2030 mCallback->onInputSurfaceDeclined(err);
2031 return;
2032 }
2033 } else {
2034 ALOGE("Failed to set input surface(aidl): Corrupted surface.");
2035 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002036 return;
2037 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002038 } else {
Sungtak Lee92bca442024-03-12 09:10:31 +00002039 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
2040 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
2041 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
2042 if (inputSurface) {
2043 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
2044 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
2045 if (err != OK) {
2046 ALOGE("Failed to set up input surface: %d", err);
2047 mCallback->onInputSurfaceDeclined(err);
2048 return;
2049 }
2050 } else if (gbs) {
2051 int32_t width = 0;
2052 (void)outputFormat->findInt32("width", &width);
2053 int32_t height = 0;
2054 (void)outputFormat->findInt32("height", &height);
2055 status_t err = setupInputSurface(std::make_shared<HGraphicBufferSourceWrapper>(
2056 gbs, width, height, usage));
2057 if (err != OK) {
2058 ALOGE("Failed to set up input surface: %d", err);
2059 mCallback->onInputSurfaceDeclined(err);
2060 return;
2061 }
2062 } else {
2063 ALOGE("Failed to set input surface: Corrupted surface.");
2064 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
2065 return;
2066 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002067 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07002068 // Formats can change after setupInputSurface
2069 sp<AMessage> inputFormat;
2070 {
2071 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2072 const std::unique_ptr<Config> &config = *configLocked;
2073 inputFormat = config->mInputFormat;
2074 outputFormat = config->mOutputFormat;
2075 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002076 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
2077}
2078
2079void CCodec::initiateStart() {
2080 auto setStarting = [this] {
2081 Mutexed<State>::Locked state(mState);
2082 if (state->get() != ALLOCATED) {
2083 return UNKNOWN_ERROR;
2084 }
2085 state->set(STARTING);
2086 return OK;
2087 };
2088 if (tryAndReportOnError(setStarting) != OK) {
2089 return;
2090 }
2091
2092 (new AMessage(kWhatStart, this))->post();
2093}
2094
2095void CCodec::start() {
2096 std::shared_ptr<Codec2Client::Component> comp;
2097 auto checkStarting = [this, &comp] {
2098 Mutexed<State>::Locked state(mState);
2099 if (state->get() != STARTING) {
2100 return UNKNOWN_ERROR;
2101 }
2102 comp = state->comp;
2103 return OK;
2104 };
2105 if (tryAndReportOnError(checkStarting) != OK) {
2106 return;
2107 }
2108
2109 c2_status_t err = comp->start();
2110 if (err != C2_OK) {
2111 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
2112 ACTION_CODE_FATAL);
2113 return;
2114 }
Wonsik Kimd55ed3b2023-06-22 14:42:17 -07002115
2116 // clear the deadline after the component starts
2117 setDeadline(TimePoint::max(), 0ms, "none");
2118
Pawin Vongmasa36653902018-11-15 00:10:25 -08002119 sp<AMessage> inputFormat;
2120 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002121 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002122 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002123 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002124 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2125 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002126 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08002127 // start triggers format dup
2128 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002129 if (config->mInputSurface) {
2130 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08002131 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002132 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002133 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002134 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002135 if (err2 != OK) {
2136 mCallback->onError(err2, ACTION_CODE_FATAL);
2137 return;
2138 }
Arun Johnson106fe7a2023-04-26 17:49:43 +00002139
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002140 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002141 if (err2 != OK) {
2142 mCallback->onError(err2, ACTION_CODE_FATAL);
2143 return;
2144 }
2145
2146 auto setRunning = [this] {
2147 Mutexed<State>::Locked state(mState);
2148 if (state->get() != STARTING) {
2149 return UNKNOWN_ERROR;
2150 }
2151 state->set(RUNNING);
2152 return OK;
2153 };
2154 if (tryAndReportOnError(setRunning) != OK) {
2155 return;
2156 }
Arun Johnson5997bb02022-04-01 19:35:44 +00002157
Wonsik Kim34b28b42022-05-20 15:49:32 -07002158 // preparation of input buffers may not succeed due to the lack of
2159 // memory; returning correct error code (NO_MEMORY) as an error allows
2160 // MediaCodec to try reclaim and restart codec gracefully.
2161 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
2162 err2 = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
2163 if (err2 != OK) {
2164 ALOGE("Initial preparation for Input Buffers failed");
2165 mCallback->onError(err2, ACTION_CODE_FATAL);
2166 return;
2167 }
2168
Pawin Vongmasa36653902018-11-15 00:10:25 -08002169 mCallback->onStartCompleted();
2170
Wonsik Kim34b28b42022-05-20 15:49:32 -07002171 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002172}
2173
2174void CCodec::initiateShutdown(bool keepComponentAllocated) {
2175 if (keepComponentAllocated) {
2176 initiateStop();
2177 } else {
2178 initiateRelease();
2179 }
2180}
2181
2182void CCodec::initiateStop() {
2183 {
2184 Mutexed<State>::Locked state(mState);
2185 if (state->get() == ALLOCATED
2186 || state->get() == RELEASED
2187 || state->get() == STOPPING
2188 || state->get() == RELEASING) {
2189 // We're already stopped, released, or doing it right now.
2190 state.unlock();
2191 mCallback->onStopCompleted();
2192 state.lock();
2193 return;
2194 }
2195 state->set(STOPPING);
2196 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002197 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00002198 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
2199 sp<AMessage> stopMessage(new AMessage(kWhatStop, this));
2200 stopMessage->setInt32("pushBlankBuffer", pushBlankBuffer);
2201 stopMessage->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002202}
2203
Sungtak Lee99144332023-01-26 11:03:14 +00002204void CCodec::stop(bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002205 std::shared_ptr<Codec2Client::Component> comp;
2206 {
2207 Mutexed<State>::Locked state(mState);
2208 if (state->get() == RELEASING) {
2209 state.unlock();
2210 // We're already stopped or release is in progress.
2211 mCallback->onStopCompleted();
2212 state.lock();
2213 return;
2214 } else if (state->get() != STOPPING) {
2215 state.unlock();
2216 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2217 state.lock();
2218 return;
2219 }
2220 comp = state->comp;
2221 }
Sungtak Leec0c05962023-10-25 08:14:13 +00002222
2223 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->stop().
2224 // But in the case some HAL implementations hang forever on comp->stop().
2225 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
2226 // completing stop()).
2227 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
2228 // prior to comp->stop().
2229 // See also b/300350761.
Sungtak Lee99144332023-01-26 11:03:14 +00002230 mChannel->stopUseOutputSurface(pushBlankBuffer);
Sungtak Leec0c05962023-10-25 08:14:13 +00002231 status_t err = comp->stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002232 if (err != C2_OK) {
2233 // TODO: convert err into status_t
2234 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2235 }
2236
2237 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002238 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2239 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002240 if (config->mInputSurface) {
2241 config->mInputSurface->disconnect();
2242 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08002243 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002244 }
2245 }
2246 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002247 Mutexed<State>::Locked state(mState);
2248 if (state->get() == STOPPING) {
2249 state->set(ALLOCATED);
2250 }
2251 }
2252 mCallback->onStopCompleted();
2253}
2254
2255void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002256 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002257 {
2258 Mutexed<State>::Locked state(mState);
2259 if (state->get() == RELEASED || state->get() == RELEASING) {
2260 // We're already released or doing it right now.
2261 if (sendCallback) {
2262 state.unlock();
2263 mCallback->onReleaseCompleted();
2264 state.lock();
2265 }
2266 return;
2267 }
2268 if (state->get() == ALLOCATING) {
2269 state->set(RELEASING);
2270 // With the altered state allocate() would fail and clean up.
2271 if (sendCallback) {
2272 state.unlock();
2273 mCallback->onReleaseCompleted();
2274 state.lock();
2275 }
2276 return;
2277 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002278 if (state->get() == STARTING
2279 || state->get() == RUNNING
2280 || state->get() == STOPPING) {
2281 // Input surface may have been started, so clean up is needed.
2282 clearInputSurfaceIfNeeded = true;
2283 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002284 state->set(RELEASING);
2285 }
2286
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002287 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002288 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2289 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002290 if (config->mInputSurface) {
2291 config->mInputSurface->disconnect();
2292 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08002293 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002294 }
2295 }
2296
Wonsik Kim936a89c2020-05-08 16:07:50 -07002297 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00002298 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002299 // thiz holds strong ref to this while the thread is running.
2300 sp<CCodec> thiz(this);
Sungtak Lee99144332023-01-26 11:03:14 +00002301 std::thread([thiz, sendCallback, pushBlankBuffer]
2302 { thiz->release(sendCallback, pushBlankBuffer); }).detach();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002303}
2304
Sungtak Lee99144332023-01-26 11:03:14 +00002305void CCodec::release(bool sendCallback, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002306 std::shared_ptr<Codec2Client::Component> comp;
2307 {
2308 Mutexed<State>::Locked state(mState);
2309 if (state->get() == RELEASED) {
2310 if (sendCallback) {
2311 state.unlock();
2312 mCallback->onReleaseCompleted();
2313 state.lock();
2314 }
2315 return;
2316 }
2317 comp = state->comp;
2318 }
Sungtak Leec0c05962023-10-25 08:14:13 +00002319 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->release().
2320 // But in the case some HAL implementations hang forever on comp->release().
2321 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
2322 // completing release()).
2323 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
2324 // prior to comp->release().
2325 // See also b/300350761.
Sungtak Lee99144332023-01-26 11:03:14 +00002326 mChannel->stopUseOutputSurface(pushBlankBuffer);
Sungtak Leec0c05962023-10-25 08:14:13 +00002327 comp->release();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002328
2329 {
2330 Mutexed<State>::Locked state(mState);
2331 state->set(RELEASED);
2332 state->comp.reset();
2333 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002334 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002335 if (sendCallback) {
2336 mCallback->onReleaseCompleted();
2337 }
2338}
2339
Sungtak Lee214ce612023-11-01 10:01:13 +00002340status_t CCodec::setSurface(const sp<Surface> &surface, uint32_t generation) {
Sungtak Lee99144332023-01-26 11:03:14 +00002341 bool pushBlankBuffer = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002342 {
2343 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2344 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002345 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
2346 status_t err = OK;
2347
Wonsik Kim75e22f42021-04-14 23:34:51 -07002348 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002349 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07002350 nativeWindow.get(),
2351 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
2352 if (err != OK) {
2353 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
2354 nativeWindow.get(), config->mSidebandHandle->handle(), err);
2355 return err;
2356 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002357 } else {
2358 // Explicitly reset the sideband handle of the window for
2359 // non-tunneled video in case the window was previously used
2360 // for a tunneled video playback.
2361 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
2362 if (err != OK) {
2363 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
2364 return err;
2365 }
ted.sun765db4d2020-06-23 14:03:41 +08002366 }
Sungtak Lee99144332023-01-26 11:03:14 +00002367 pushBlankBuffer = config->mPushBlankBuffersOnStop;
ted.sun765db4d2020-06-23 14:03:41 +08002368 }
Sungtak Lee214ce612023-11-01 10:01:13 +00002369 return mChannel->setSurface(surface, generation, pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002370}
2371
2372void CCodec::signalFlush() {
2373 status_t err = [this] {
2374 Mutexed<State>::Locked state(mState);
2375 if (state->get() == FLUSHED) {
2376 return ALREADY_EXISTS;
2377 }
2378 if (state->get() != RUNNING) {
2379 return UNKNOWN_ERROR;
2380 }
2381 state->set(FLUSHING);
2382 return OK;
2383 }();
2384 switch (err) {
2385 case ALREADY_EXISTS:
2386 mCallback->onFlushCompleted();
2387 return;
2388 case OK:
2389 break;
2390 default:
2391 mCallback->onError(err, ACTION_CODE_FATAL);
2392 return;
2393 }
2394
2395 mChannel->stop();
2396 (new AMessage(kWhatFlush, this))->post();
2397}
2398
2399void CCodec::flush() {
2400 std::shared_ptr<Codec2Client::Component> comp;
2401 auto checkFlushing = [this, &comp] {
2402 Mutexed<State>::Locked state(mState);
2403 if (state->get() != FLUSHING) {
2404 return UNKNOWN_ERROR;
2405 }
2406 comp = state->comp;
2407 return OK;
2408 };
2409 if (tryAndReportOnError(checkFlushing) != OK) {
2410 return;
2411 }
2412
2413 std::list<std::unique_ptr<C2Work>> flushedWork;
2414 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2415 {
2416 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2417 flushedWork.splice(flushedWork.end(), *queue);
2418 }
2419 if (err != C2_OK) {
2420 // TODO: convert err into status_t
2421 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2422 }
2423
2424 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002425
2426 {
2427 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002428 if (state->get() == FLUSHING) {
2429 state->set(FLUSHED);
2430 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002431 }
2432 mCallback->onFlushCompleted();
2433}
2434
2435void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002436 std::shared_ptr<Codec2Client::Component> comp;
2437 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002438 Mutexed<State>::Locked state(mState);
2439 if (state->get() != FLUSHED) {
2440 return UNKNOWN_ERROR;
2441 }
2442 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002443 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002444 return OK;
2445 };
2446 if (tryAndReportOnError(setResuming) != OK) {
2447 return;
2448 }
2449
Wonsik Kime75a5da2020-02-14 17:29:03 -08002450 {
2451 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2452 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002453 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002454 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002455 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002456 }
2457
Arun Johnson106fe7a2023-04-26 17:49:43 +00002458 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
Arun Johnson326166e2023-07-28 19:11:52 +00002459 status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers, true);
Arun Johnson106fe7a2023-04-26 17:49:43 +00002460 if (err != OK) {
2461 if (err == NO_MEMORY) {
2462 // NO_MEMORY happens here when all the buffers are still
2463 // with the codec. That is not an error as it is momentarily
2464 // and the buffers are send to the client as soon as the codec
2465 // releases them
2466 ALOGI("Resuming with all input buffers still with codec");
2467 } else {
2468 ALOGE("Resume request for Input Buffers failed");
2469 mCallback->onError(err, ACTION_CODE_FATAL);
2470 return;
2471 }
2472 }
2473
2474 // channel start should be called after prepareInitialBuffers
2475 // Calling before can cause a failure during prepare when
2476 // buffers are sent to the client before preparation from onWorkDone
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002477 (void)mChannel->start(nullptr, nullptr, [&]{
2478 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2479 const std::unique_ptr<Config> &config = *configLocked;
2480 return config->mBuffersBoundToCodec;
2481 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002482 {
2483 Mutexed<State>::Locked state(mState);
2484 if (state->get() != RESUMING) {
2485 state.unlock();
2486 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2487 state.lock();
2488 return;
2489 }
2490 state->set(RUNNING);
2491 }
2492
Wonsik Kim34b28b42022-05-20 15:49:32 -07002493 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002494}
2495
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002496void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002497 std::shared_ptr<Codec2Client::Component> comp;
2498 auto checkState = [this, &comp] {
2499 Mutexed<State>::Locked state(mState);
2500 if (state->get() == RELEASED) {
2501 return INVALID_OPERATION;
2502 }
2503 comp = state->comp;
2504 return OK;
2505 };
2506 if (tryAndReportOnError(checkState) != OK) {
2507 return;
2508 }
2509
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002510 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2511 // the behavior here.
2512 sp<AMessage> params = msg;
2513 int32_t bitrate;
2514 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2515 params = msg->dup();
2516 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2517 }
2518
Houxiang Dai5a97b472021-03-22 17:56:04 +08002519 int32_t syncId = 0;
2520 if (params->findInt32("audio-hw-sync", &syncId)
2521 || params->findInt32("hw-av-sync-id", &syncId)) {
2522 configureTunneledVideoPlayback(comp, nullptr, params);
2523 }
2524
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002525 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2526 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002527
2528 /**
2529 * Handle input surface parameters
2530 */
2531 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002532 && (config->mDomain & Config::IS_ENCODER)
2533 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002534 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002535
2536 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2537 config->mISConfig->mStopped = false;
2538 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2539 config->mISConfig->mStopped = true;
2540 }
2541
2542 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002543 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002544 config->mISConfig->mSuspended = value;
2545 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002546 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002547 }
2548
2549 (void)config->mInputSurface->configure(*config->mISConfig);
2550 if (config->mISConfig->mStopped) {
2551 config->mInputFormat->setInt64(
2552 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2553 }
2554 }
2555
2556 std::vector<std::unique_ptr<C2Param>> configUpdate;
2557 (void)config->getConfigUpdateFromSdkParams(
2558 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2559 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2560 // Parameter synchronization is not defined when using input surface. For now, route
2561 // these directly to the component.
2562 if (config->mInputSurface == nullptr
2563 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2564 || comp->getName().find("c2.android.") == 0)) {
2565 mChannel->setParameters(configUpdate);
2566 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002567 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002568 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002569 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002570 }
2571}
2572
2573void CCodec::signalEndOfInputStream() {
2574 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2575}
2576
2577void CCodec::signalRequestIDRFrame() {
2578 std::shared_ptr<Codec2Client::Component> comp;
2579 {
2580 Mutexed<State>::Locked state(mState);
2581 if (state->get() == RELEASED) {
2582 ALOGD("no IDR request sent since component is released");
2583 return;
2584 }
2585 comp = state->comp;
2586 }
2587 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002588 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2589 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002590 std::vector<std::unique_ptr<C2Param>> params;
2591 params.push_back(
2592 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2593 config->setParameters(comp, params, C2_MAY_BLOCK);
2594}
2595
Wonsik Kim874ad382021-03-12 09:59:36 -08002596status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2597 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2598 const std::unique_ptr<Config> &config = *configLocked;
2599 return config->querySupportedParameters(names);
2600}
2601
2602status_t CCodec::describeParameter(
2603 const std::string &name, CodecParameterDescriptor *desc) {
2604 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2605 const std::unique_ptr<Config> &config = *configLocked;
2606 return config->describe(name, desc);
2607}
2608
2609status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2610 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2611 if (!comp) {
2612 return INVALID_OPERATION;
2613 }
2614 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2615 const std::unique_ptr<Config> &config = *configLocked;
2616 return config->subscribeToVendorConfigUpdate(comp, names);
2617}
2618
2619status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2620 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2621 if (!comp) {
2622 return INVALID_OPERATION;
2623 }
2624 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2625 const std::unique_ptr<Config> &config = *configLocked;
2626 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2627}
2628
Wonsik Kimab34ed62019-01-31 15:28:46 -08002629void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002630 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002631 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002632 bool shouldPost = queue->empty();
Wonsik Kimab34ed62019-01-31 15:28:46 -08002633 queue->splice(queue->end(), workItems);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002634 if (shouldPost) {
2635 (new AMessage(kWhatWorkDone, this))->post();
2636 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002637 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002638}
2639
Wonsik Kimab34ed62019-01-31 15:28:46 -08002640void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2641 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002642 if (arrayIndex == 0) {
2643 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002644 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2645 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002646 if (config->mInputSurface) {
2647 config->mInputSurface->onInputBufferDone(frameIndex);
2648 }
2649 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002650}
2651
2652void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2653 TimePoint now = std::chrono::steady_clock::now();
2654 CCodecWatchdog::getInstance()->watch(this);
2655 switch (msg->what()) {
2656 case kWhatAllocate: {
2657 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002658 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002659 sp<RefBase> obj;
2660 CHECK(msg->findObject("codecInfo", &obj));
2661 allocate((MediaCodecInfo *)obj.get());
2662 break;
2663 }
2664 case kWhatConfigure: {
2665 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002666 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002667 sp<AMessage> format;
2668 CHECK(msg->findMessage("format", &format));
2669 configure(format);
2670 break;
2671 }
2672 case kWhatStart: {
2673 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002674 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002675 start();
2676 break;
2677 }
2678 case kWhatStop: {
2679 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002680 setDeadline(now, 1500ms, "stop");
Sungtak Lee99144332023-01-26 11:03:14 +00002681 int32_t pushBlankBuffer;
2682 if (!msg->findInt32("pushBlankBuffer", &pushBlankBuffer)) {
2683 pushBlankBuffer = 0;
2684 }
2685 stop(static_cast<bool>(pushBlankBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002686 break;
2687 }
2688 case kWhatFlush: {
2689 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002690 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002691 flush();
2692 break;
2693 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002694 case kWhatRelease: {
2695 mChannel->release();
2696 mClient.reset();
2697 mClientListener.reset();
2698 break;
2699 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002700 case kWhatCreateInputSurface: {
2701 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002702 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002703 createInputSurface();
2704 break;
2705 }
2706 case kWhatSetInputSurface: {
2707 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002708 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002709 sp<RefBase> obj;
2710 CHECK(msg->findObject("surface", &obj));
2711 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2712 setInputSurface(surface);
2713 break;
2714 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002715 case kWhatWorkDone: {
2716 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002717 bool shouldPost = false;
2718 {
2719 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2720 if (queue->empty()) {
2721 break;
2722 }
2723 work.swap(queue->front());
2724 queue->pop_front();
2725 shouldPost = !queue->empty();
2726 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002727 if (shouldPost) {
2728 (new AMessage(kWhatWorkDone, this))->post();
2729 }
2730
Pawin Vongmasa36653902018-11-15 00:10:25 -08002731 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002732 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002733 sp<AMessage> outputFormat = nullptr;
2734 {
2735 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2736 const std::unique_ptr<Config> &config = *configLocked;
2737 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2738 config->watch<C2StreamInitDataInfo::output>();
2739 if (!work->worklets.empty()
2740 && (work->worklets.front()->output.flags
2741 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002742
Wonsik Kim75e22f42021-04-14 23:34:51 -07002743 // copy buffer info to config
2744 std::vector<std::unique_ptr<C2Param>> updates;
2745 for (const std::unique_ptr<C2Param> &param
2746 : work->worklets.front()->output.configUpdate) {
2747 updates.push_back(C2Param::Copy(*param));
2748 }
2749 unsigned stream = 0;
2750 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2751 work->worklets.front()->output.buffers;
2752 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2753 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2754 // move all info into output-stream #0 domain
2755 updates.emplace_back(
2756 C2Param::CopyAsStream(*info, true /* output */, stream));
2757 }
2758
2759 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2760 // for now only do the first block
2761 if (!blocks.empty()) {
2762 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2763 // block.crop().left, block.crop().top,
2764 // block.crop().width, block.crop().height,
2765 // block.width(), block.height());
2766 const C2ConstGraphicBlock &block = blocks[0];
2767 updates.emplace_back(new C2StreamCropRectInfo::output(
2768 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002769 }
2770 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002771 }
George Burgess IVc813a592020-02-22 22:54:44 -08002772
Wonsik Kim75e22f42021-04-14 23:34:51 -07002773 sp<AMessage> oldFormat = config->mOutputFormat;
2774 config->updateConfiguration(updates, config->mOutputDomain);
2775 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002776
Wonsik Kim75e22f42021-04-14 23:34:51 -07002777 // copy standard infos to graphic buffers if not already present (otherwise, we
2778 // may overwrite the actual intermediate value with a final value)
2779 stream = 0;
2780 const static C2Param::Index stdGfxInfos[] = {
2781 C2StreamRotationInfo::output::PARAM_TYPE,
2782 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2783 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2784 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Taehwan Kim2d222b82022-05-12 14:19:26 +09002785 C2StreamHdr10PlusInfo::output::PARAM_TYPE, // will be deprecated
2786 C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE,
Wonsik Kim75e22f42021-04-14 23:34:51 -07002787 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2788 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2789 };
2790 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2791 if (buf->data().graphicBlocks().size()) {
2792 for (C2Param::Index ix : stdGfxInfos) {
2793 if (!buf->hasInfo(ix)) {
2794 const C2Param *param =
2795 config->getConfigParameterValue(ix.withStream(stream));
2796 if (param) {
2797 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2798 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2799 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002800 }
2801 }
2802 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002803 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002804 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002805 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002806 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302807 if (work->worklets.empty()
2808 || !work->worklets.back()
2809 || (work->worklets.back()->output.flags
2810 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2811 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2812 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002813 }
2814 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002815 initData = initDataWatcher.update();
2816 AmendOutputFormatWithCodecSpecificData(
2817 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2818 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002819 }
2820 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002821 }
2822 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002823 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Songyue Han1e6769b2023-08-30 18:09:27 +00002824 // log metrics to MediaCodec
2825 if (mMetrics->countEntries() == 0) {
2826 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2827 const std::unique_ptr<Config> &config = *configLocked;
2828 uint32_t pf = PIXEL_FORMAT_UNKNOWN;
2829 if (!config->mInputSurface) {
2830 pf = mChannel->getBuffersPixelFormat(config->mDomain & Config::IS_ENCODER);
Songyue Hanad01f6a2023-08-17 05:45:35 +00002831 } else {
2832 pf = config->mInputSurface->getPixelFormat();
Songyue Han1e6769b2023-08-30 18:09:27 +00002833 }
2834 if (pf != PIXEL_FORMAT_UNKNOWN) {
2835 mMetrics->setInt64(kCodecPixelFormat, pf);
2836 mCallback->onMetricsUpdated(mMetrics);
2837 }
2838 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002839 break;
2840 }
2841 case kWhatWatch: {
2842 // watch message already posted; no-op.
2843 break;
2844 }
2845 default: {
2846 ALOGE("unrecognized message");
2847 break;
2848 }
2849 }
2850 setDeadline(TimePoint::max(), 0ms, "none");
2851}
2852
2853void CCodec::setDeadline(
2854 const TimePoint &now,
2855 const std::chrono::milliseconds &timeout,
2856 const char *name) {
2857 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2858 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2859 deadline->set(now + (timeout * mult), name);
2860}
2861
ted.sun765db4d2020-06-23 14:03:41 +08002862status_t CCodec::configureTunneledVideoPlayback(
2863 std::shared_ptr<Codec2Client::Component> comp,
2864 sp<NativeHandle> *sidebandHandle,
2865 const sp<AMessage> &msg) {
2866 std::vector<std::unique_ptr<C2SettingResult>> failures;
2867
2868 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2869 C2PortTunneledModeTuning::output::AllocUnique(
2870 1,
2871 C2PortTunneledModeTuning::Struct::SIDEBAND,
2872 C2PortTunneledModeTuning::Struct::REALTIME,
2873 0);
2874 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2875 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2876 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2877 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2878 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2879 } else {
2880 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2881 tunneledPlayback->setFlexCount(0);
2882 }
2883 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2884 if (c2err != C2_OK) {
2885 return UNKNOWN_ERROR;
2886 }
2887
Houxiang Dai5a97b472021-03-22 17:56:04 +08002888 if (sidebandHandle == nullptr) {
2889 return OK;
2890 }
2891
ted.sun765db4d2020-06-23 14:03:41 +08002892 std::vector<std::unique_ptr<C2Param>> params;
2893 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2894 if (c2err == C2_OK && params.size() == 1u) {
2895 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2896 C2PortTunnelHandleTuning::output::From(params[0].get());
2897 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2898 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2899 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2900 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2901 memcpy(handle->data, videoTunnelSideband->m.values,
2902 sizeof(int32_t) * videoTunnelSideband->flexCount());
2903 return OK;
2904 } else {
2905 return NO_MEMORY;
2906 }
2907 }
2908 return UNKNOWN_ERROR;
2909}
2910
Pawin Vongmasa36653902018-11-15 00:10:25 -08002911void CCodec::initiateReleaseIfStuck() {
Shrikara B3b87a532022-08-26 14:18:14 +05302912 std::string name;
2913 bool pendingDeadline = false;
2914 {
2915 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2916 if (deadline->get() < std::chrono::steady_clock::now()) {
2917 name = deadline->getName();
2918 }
2919 if (deadline->get() != TimePoint::max()) {
2920 pendingDeadline = true;
2921 }
2922 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002923 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002924 // We're not stuck.
2925 if (pendingDeadline) {
2926 // If we are not stuck yet but still has deadline coming up,
2927 // post watch message to check back later.
2928 (new AMessage(kWhatWatch, this))->post();
2929 }
2930 return;
2931 }
2932
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002933 C2String compName;
2934 {
2935 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002936 if (!state->comp) {
2937 ALOGD("previous call to %s exceeded timeout "
2938 "and the component is already released", name.c_str());
2939 return;
2940 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002941 compName = state->comp->getName();
2942 }
2943 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2944
Pawin Vongmasa36653902018-11-15 00:10:25 -08002945 initiateRelease(false);
2946 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2947}
2948
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002949// static
2950PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002951 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002952 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002953 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002954 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2955 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002956 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002957 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
Sungtak Lee92bca442024-03-12 09:10:31 +00002958 if (Codec2Client::IsAidlSelected()) {
2959 sp<IGraphicBufferProducer> gbp;
2960 sp<AidlGraphicBufferSource> gbs = new AidlGraphicBufferSource();
2961 status_t err = gbs->initCheck();
2962 if (err != OK) {
2963 ALOGE("Failed to create persistent input surface: error %d", err);
2964 return nullptr;
2965 }
2966 ALOGD("aidl based PersistentSurface created");
2967 std::shared_ptr<WAidlGraphicBufferSource> wrapper =
2968 ::ndk::SharedRefBase::make<WAidlGraphicBufferSource>(gbs);
2969
2970 return new PersistentSurface(
2971 gbs->getIGraphicBufferProducer(), wrapper->asBinder());
2972 } else {
2973 sp<IGraphicBufferProducer> gbp;
2974 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2975 status_t err = gbs->initCheck();
2976 if (err != OK) {
2977 ALOGE("Failed to create persistent input surface: error %d", err);
2978 return nullptr;
2979 }
2980 ALOGD("hidl based PersistentSurface created");
2981 return new PersistentSurface(
2982 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002983 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002984 } else {
2985 return nullptr;
2986 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002987 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002988 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002989 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002990 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002991 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002992}
2993
Wonsik Kimffb889a2020-05-28 11:32:25 -07002994class IntfCache {
2995public:
2996 IntfCache() = default;
2997
2998 status_t init(const std::string &name) {
2999 std::shared_ptr<Codec2Client::Interface> intf{
3000 Codec2Client::CreateInterfaceByName(name.c_str())};
3001 if (!intf) {
3002 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
3003 mInitStatus = NO_INIT;
3004 return NO_INIT;
3005 }
3006 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
3007 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
3008 C2ParamField{&sUsage, &sUsage.value}));
3009 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
3010 if (err != C2_OK) {
3011 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
3012 name.c_str(), err);
3013 mFields[0].status = err;
3014 }
3015 std::vector<std::unique_ptr<C2Param>> params;
3016 err = intf->query(
3017 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09003018 {
3019 C2StreamBufferTypeSetting::input::PARAM_TYPE,
3020 C2PortAllocatorsTuning::input::PARAM_TYPE
3021 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07003022 C2_MAY_BLOCK,
3023 &params);
3024 if (err != C2_OK && err != C2_BAD_INDEX) {
3025 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
3026 name.c_str(), err);
3027 }
3028 while (!params.empty()) {
3029 C2Param *param = params.back().release();
3030 params.pop_back();
3031 if (!param) {
3032 continue;
3033 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09003034 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
3035 mInputStreamFormat.reset(
3036 C2StreamBufferTypeSetting::input::From(param));
3037 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003038 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07003039 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07003040 }
3041 }
3042 mInitStatus = OK;
3043 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003044 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003045
3046 status_t initCheck() const { return mInitStatus; }
3047
3048 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
3049 CHECK_EQ(1u, mFields.size());
3050 return mFields[0];
3051 }
3052
3053 const C2ApiFeaturesSetting &getApiFeatures() const {
3054 return mApiFeatures;
3055 }
3056
Taehwan Kim900b49c2021-12-13 11:16:22 +09003057 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
3058 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
3059 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
3060 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
3061 param->invalidate();
3062 return param;
3063 }();
3064 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
3065 }
3066
Wonsik Kimffb889a2020-05-28 11:32:25 -07003067 const C2PortAllocatorsTuning::input &getInputAllocators() const {
3068 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
3069 std::unique_ptr<C2PortAllocatorsTuning::input> param =
3070 C2PortAllocatorsTuning::input::AllocUnique(0);
3071 param->invalidate();
3072 return param;
3073 }();
3074 return mInputAllocators ? *mInputAllocators : *sInvalidated;
3075 }
3076
3077private:
3078 status_t mInitStatus{NO_INIT};
3079
3080 std::vector<C2FieldSupportedValuesQuery> mFields;
3081 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09003082 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003083 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
3084};
3085
3086static const IntfCache &GetIntfCache(const std::string &name) {
3087 static IntfCache sNullIntfCache;
3088 static std::mutex sMutex;
3089 static std::map<std::string, IntfCache> sCache;
3090 std::unique_lock<std::mutex> lock{sMutex};
3091 auto it = sCache.find(name);
3092 if (it == sCache.end()) {
3093 lock.unlock();
3094 IntfCache intfCache;
3095 status_t err = intfCache.init(name);
3096 if (err != OK) {
3097 return sNullIntfCache;
3098 }
3099 lock.lock();
3100 it = sCache.insert({name, std::move(intfCache)}).first;
3101 }
3102 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003103}
3104
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003105static status_t GetCommonAllocatorIds(
3106 const std::vector<std::string> &names,
3107 C2Allocator::type_t type,
3108 std::set<C2Allocator::id_t> *ids) {
3109 int poolMask = GetCodec2PoolMask();
3110 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
3111 C2Allocator::id_t defaultAllocatorId =
3112 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
3113
3114 ids->clear();
3115 if (names.empty()) {
3116 return OK;
3117 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003118 bool firstIteration = true;
3119 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003120 const IntfCache &intfCache = GetIntfCache(name);
3121 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003122 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003123 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09003124 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
3125 if (streamFormat) {
3126 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
3127 if (streamFormat.value == C2BufferData::GRAPHIC
3128 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
3129 allocatorType = C2Allocator::GRAPHIC;
3130 }
3131
3132 if (type != allocatorType) {
3133 // requested type is not supported at input allocators
3134 ids->clear();
3135 ids->insert(defaultAllocatorId);
3136 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
3137 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
3138 break;
3139 }
3140 }
3141
Wonsik Kimffb889a2020-05-28 11:32:25 -07003142 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003143 if (firstIteration) {
3144 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003145 if (allocators && allocators.flexCount() > 0) {
3146 ids->insert(allocators.m.values,
3147 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003148 }
3149 if (ids->empty()) {
3150 // The component does not advertise allocators. Use default.
3151 ids->insert(defaultAllocatorId);
3152 }
3153 continue;
3154 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003155 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003156 if (allocators && allocators.flexCount() > 0) {
3157 filtered = true;
3158 for (auto it = ids->begin(); it != ids->end(); ) {
3159 bool found = false;
3160 for (size_t j = 0; j < allocators.flexCount(); ++j) {
3161 if (allocators.m.values[j] == *it) {
3162 found = true;
3163 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003164 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003165 }
3166 if (found) {
3167 ++it;
3168 } else {
3169 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003170 }
3171 }
3172 }
3173 if (!filtered) {
3174 // The component does not advertise supported allocators. Use default.
3175 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
3176 if (ids->size() != (containsDefault ? 1 : 0)) {
3177 ids->clear();
3178 if (containsDefault) {
3179 ids->insert(defaultAllocatorId);
3180 }
3181 }
3182 }
3183 }
3184 // Finally, filter with pool masks
3185 for (auto it = ids->begin(); it != ids->end(); ) {
3186 if ((poolMask >> *it) & 1) {
3187 ++it;
3188 } else {
3189 it = ids->erase(it);
3190 }
3191 }
3192 return OK;
3193}
3194
3195static status_t CalculateMinMaxUsage(
3196 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
3197 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
3198 *minUsage = 0;
3199 *maxUsage = ~0ull;
3200 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003201 const IntfCache &intfCache = GetIntfCache(name);
3202 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003203 continue;
3204 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003205 const C2FieldSupportedValuesQuery &usageSupportedValues =
3206 intfCache.getUsageSupportedValues();
3207 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003208 continue;
3209 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003210 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003211 if (supported.type != C2FieldSupportedValues::FLAGS) {
3212 continue;
3213 }
3214 if (supported.values.empty()) {
3215 *maxUsage = 0;
3216 continue;
3217 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08003218 if (supported.values.size() > 1) {
3219 *minUsage |= supported.values[1].u64;
3220 } else {
3221 *minUsage |= supported.values[0].u64;
3222 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003223 int64_t currentMaxUsage = 0;
3224 for (const C2Value::Primitive &flags : supported.values) {
3225 currentMaxUsage |= flags.u64;
3226 }
3227 *maxUsage &= currentMaxUsage;
3228 }
3229 return OK;
3230}
3231
3232// static
3233status_t CCodec::CanFetchLinearBlock(
3234 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003235 for (const std::string &name : names) {
3236 const IntfCache &intfCache = GetIntfCache(name);
3237 if (intfCache.initCheck() != OK) {
3238 continue;
3239 }
3240 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
3241 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
3242 *isCompatible = false;
3243 return OK;
3244 }
3245 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003246 std::set<C2Allocator::id_t> allocators;
3247 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
3248 if (allocators.empty()) {
3249 *isCompatible = false;
3250 return OK;
3251 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003252
3253 uint64_t minUsage = 0;
3254 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003255 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003256 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003257 *isCompatible = ((maxUsage & minUsage) == minUsage);
3258 return OK;
3259}
3260
3261static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
3262 static std::mutex sMutex{};
3263 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
3264 std::unique_lock<std::mutex> lock{sMutex};
3265 std::shared_ptr<C2BlockPool> pool;
3266 auto it = sPools.find(allocId);
3267 if (it == sPools.end()) {
3268 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3269 if (err == OK) {
3270 sPools.emplace(allocId, pool);
3271 } else {
3272 pool.reset();
3273 }
3274 } else {
3275 pool = it->second;
3276 }
3277 return pool;
3278}
3279
3280// static
3281std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
3282 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003283 std::set<C2Allocator::id_t> allocators;
3284 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
3285 if (allocators.empty()) {
3286 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
3287 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003288
3289 uint64_t minUsage = 0;
3290 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003291 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003292 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003293 if ((maxUsage & minUsage) != minUsage) {
3294 allocators.clear();
3295 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
3296 }
3297 std::shared_ptr<C2LinearBlock> block;
3298 for (C2Allocator::id_t allocId : allocators) {
3299 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
3300 if (!pool) {
3301 continue;
3302 }
3303 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
3304 if (err != C2_OK || !block) {
3305 block.reset();
3306 continue;
3307 }
3308 break;
3309 }
3310 return block;
3311}
3312
3313// static
3314status_t CCodec::CanFetchGraphicBlock(
3315 const std::vector<std::string> &names, bool *isCompatible) {
3316 uint64_t minUsage = 0;
3317 uint64_t maxUsage = ~0ull;
3318 std::set<C2Allocator::id_t> allocators;
3319 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3320 if (allocators.empty()) {
3321 *isCompatible = false;
3322 return OK;
3323 }
3324 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3325 *isCompatible = ((maxUsage & minUsage) == minUsage);
3326 return OK;
3327}
3328
3329// static
3330std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
3331 int32_t width,
3332 int32_t height,
3333 int32_t format,
3334 uint64_t usage,
3335 const std::vector<std::string> &names) {
3336 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
3337 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
3338 ALOGD("Unrecognized pixel format: %d", format);
3339 return nullptr;
3340 }
3341 uint64_t minUsage = 0;
3342 uint64_t maxUsage = ~0ull;
3343 std::set<C2Allocator::id_t> allocators;
3344 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3345 if (allocators.empty()) {
3346 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3347 }
3348 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3349 minUsage |= usage;
3350 if ((maxUsage & minUsage) != minUsage) {
3351 allocators.clear();
3352 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3353 }
3354 std::shared_ptr<C2GraphicBlock> block;
3355 for (C2Allocator::id_t allocId : allocators) {
3356 std::shared_ptr<C2BlockPool> pool;
3357 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3358 if (err != C2_OK || !pool) {
3359 continue;
3360 }
3361 err = pool->fetchGraphicBlock(
3362 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
3363 if (err != C2_OK || !block) {
3364 block.reset();
3365 continue;
3366 }
3367 break;
3368 }
3369 return block;
3370}
3371
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003372} // namespace android