blob: a897fa0f84cd5f1d2f9135944a560334b6fb792c [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,
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05301427 AStringPrintf("%d,%d-%d,%d=%d;", 0, 0, height, width, 0));
Ram Mohan16511072023-12-11 19:41:31 +05301428 }
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 Lee34402ae2024-05-07 19:51:28 +00002230 //
2231 // The workaround is no longer needed with fetchGraphicBlock & C2Fence changes.
Sungtak Leeb7b1cf42024-05-14 22:45:35 +00002232 // so we are reverting back to the logical sequence of the operations when
2233 // AIDL HALs are selected.
2234 // When the HIDL HALs are selected, we retained workaround(the reversed
2235 // order) as default in order to keep legacy behavior.
2236 bool stopHalBeforeSurface =
2237 Codec2Client::IsAidlSelected() ||
2238 property_get_bool("debug.codec2.stop_hal_before_surface", false);
Sungtak Lee34402ae2024-05-07 19:51:28 +00002239 status_t err = C2_OK;
Sungtak Leeb7b1cf42024-05-14 22:45:35 +00002240 if (stopHalBeforeSurface && android::media::codec::provider_->stop_hal_before_surface()) {
Sungtak Lee34402ae2024-05-07 19:51:28 +00002241 err = comp->stop();
2242 mChannel->stopUseOutputSurface(pushBlankBuffer);
2243 } else {
2244 mChannel->stopUseOutputSurface(pushBlankBuffer);
2245 err = comp->stop();
2246 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002247 if (err != C2_OK) {
2248 // TODO: convert err into status_t
2249 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2250 }
2251
2252 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002253 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2254 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002255 if (config->mInputSurface) {
2256 config->mInputSurface->disconnect();
2257 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08002258 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002259 }
2260 }
2261 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002262 Mutexed<State>::Locked state(mState);
2263 if (state->get() == STOPPING) {
2264 state->set(ALLOCATED);
2265 }
2266 }
2267 mCallback->onStopCompleted();
2268}
2269
2270void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002271 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002272 {
2273 Mutexed<State>::Locked state(mState);
2274 if (state->get() == RELEASED || state->get() == RELEASING) {
2275 // We're already released or doing it right now.
2276 if (sendCallback) {
2277 state.unlock();
2278 mCallback->onReleaseCompleted();
2279 state.lock();
2280 }
2281 return;
2282 }
2283 if (state->get() == ALLOCATING) {
2284 state->set(RELEASING);
2285 // With the altered state allocate() would fail and clean up.
2286 if (sendCallback) {
2287 state.unlock();
2288 mCallback->onReleaseCompleted();
2289 state.lock();
2290 }
2291 return;
2292 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002293 if (state->get() == STARTING
2294 || state->get() == RUNNING
2295 || state->get() == STOPPING) {
2296 // Input surface may have been started, so clean up is needed.
2297 clearInputSurfaceIfNeeded = true;
2298 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002299 state->set(RELEASING);
2300 }
2301
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002302 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002303 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2304 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002305 if (config->mInputSurface) {
2306 config->mInputSurface->disconnect();
2307 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08002308 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002309 }
2310 }
2311
Wonsik Kim936a89c2020-05-08 16:07:50 -07002312 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00002313 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002314 // thiz holds strong ref to this while the thread is running.
2315 sp<CCodec> thiz(this);
Sungtak Lee99144332023-01-26 11:03:14 +00002316 std::thread([thiz, sendCallback, pushBlankBuffer]
2317 { thiz->release(sendCallback, pushBlankBuffer); }).detach();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002318}
2319
Sungtak Lee99144332023-01-26 11:03:14 +00002320void CCodec::release(bool sendCallback, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002321 std::shared_ptr<Codec2Client::Component> comp;
2322 {
2323 Mutexed<State>::Locked state(mState);
2324 if (state->get() == RELEASED) {
2325 if (sendCallback) {
2326 state.unlock();
2327 mCallback->onReleaseCompleted();
2328 state.lock();
2329 }
2330 return;
2331 }
2332 comp = state->comp;
2333 }
Sungtak Leec0c05962023-10-25 08:14:13 +00002334 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->release().
2335 // But in the case some HAL implementations hang forever on comp->release().
2336 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
2337 // completing release()).
2338 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
2339 // prior to comp->release().
2340 // See also b/300350761.
Sungtak Lee34402ae2024-05-07 19:51:28 +00002341 //
2342 // The workaround is no longer needed with fetchGraphicBlock & C2Fence changes.
Sungtak Leeb7b1cf42024-05-14 22:45:35 +00002343 // so we are reverting back to the logical sequence of the operations when
2344 // AIDL HALs are selected.
2345 // When the HIDL HALs are selected, we retained workaround(the reversed
2346 // order) as default in order to keep legacy behavior.
2347 bool stopHalBeforeSurface =
2348 Codec2Client::IsAidlSelected() ||
2349 property_get_bool("debug.codec2.stop_hal_before_surface", false);
2350 if (stopHalBeforeSurface && android::media::codec::provider_->stop_hal_before_surface()) {
Sungtak Lee34402ae2024-05-07 19:51:28 +00002351 comp->release();
2352 mChannel->stopUseOutputSurface(pushBlankBuffer);
2353 } else {
2354 mChannel->stopUseOutputSurface(pushBlankBuffer);
2355 comp->release();
2356 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002357
2358 {
2359 Mutexed<State>::Locked state(mState);
2360 state->set(RELEASED);
2361 state->comp.reset();
2362 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002363 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002364 if (sendCallback) {
2365 mCallback->onReleaseCompleted();
2366 }
2367}
2368
Sungtak Lee214ce612023-11-01 10:01:13 +00002369status_t CCodec::setSurface(const sp<Surface> &surface, uint32_t generation) {
Sungtak Lee99144332023-01-26 11:03:14 +00002370 bool pushBlankBuffer = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002371 {
2372 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2373 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002374 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
2375 status_t err = OK;
2376
Wonsik Kim75e22f42021-04-14 23:34:51 -07002377 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002378 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07002379 nativeWindow.get(),
2380 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
2381 if (err != OK) {
2382 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
2383 nativeWindow.get(), config->mSidebandHandle->handle(), err);
2384 return err;
2385 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002386 } else {
2387 // Explicitly reset the sideband handle of the window for
2388 // non-tunneled video in case the window was previously used
2389 // for a tunneled video playback.
2390 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
2391 if (err != OK) {
2392 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
2393 return err;
2394 }
ted.sun765db4d2020-06-23 14:03:41 +08002395 }
Sungtak Lee99144332023-01-26 11:03:14 +00002396 pushBlankBuffer = config->mPushBlankBuffersOnStop;
ted.sun765db4d2020-06-23 14:03:41 +08002397 }
Sungtak Lee214ce612023-11-01 10:01:13 +00002398 return mChannel->setSurface(surface, generation, pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002399}
2400
2401void CCodec::signalFlush() {
2402 status_t err = [this] {
2403 Mutexed<State>::Locked state(mState);
2404 if (state->get() == FLUSHED) {
2405 return ALREADY_EXISTS;
2406 }
2407 if (state->get() != RUNNING) {
2408 return UNKNOWN_ERROR;
2409 }
2410 state->set(FLUSHING);
2411 return OK;
2412 }();
2413 switch (err) {
2414 case ALREADY_EXISTS:
2415 mCallback->onFlushCompleted();
2416 return;
2417 case OK:
2418 break;
2419 default:
2420 mCallback->onError(err, ACTION_CODE_FATAL);
2421 return;
2422 }
2423
2424 mChannel->stop();
2425 (new AMessage(kWhatFlush, this))->post();
2426}
2427
2428void CCodec::flush() {
2429 std::shared_ptr<Codec2Client::Component> comp;
2430 auto checkFlushing = [this, &comp] {
2431 Mutexed<State>::Locked state(mState);
2432 if (state->get() != FLUSHING) {
2433 return UNKNOWN_ERROR;
2434 }
2435 comp = state->comp;
2436 return OK;
2437 };
2438 if (tryAndReportOnError(checkFlushing) != OK) {
2439 return;
2440 }
2441
2442 std::list<std::unique_ptr<C2Work>> flushedWork;
2443 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2444 {
2445 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2446 flushedWork.splice(flushedWork.end(), *queue);
2447 }
2448 if (err != C2_OK) {
2449 // TODO: convert err into status_t
2450 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2451 }
2452
2453 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002454
2455 {
2456 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002457 if (state->get() == FLUSHING) {
2458 state->set(FLUSHED);
2459 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002460 }
2461 mCallback->onFlushCompleted();
2462}
2463
2464void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002465 std::shared_ptr<Codec2Client::Component> comp;
2466 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002467 Mutexed<State>::Locked state(mState);
2468 if (state->get() != FLUSHED) {
2469 return UNKNOWN_ERROR;
2470 }
2471 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002472 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002473 return OK;
2474 };
2475 if (tryAndReportOnError(setResuming) != OK) {
2476 return;
2477 }
2478
Wonsik Kime75a5da2020-02-14 17:29:03 -08002479 {
2480 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2481 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002482 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002483 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002484 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002485 }
2486
Arun Johnson106fe7a2023-04-26 17:49:43 +00002487 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
Arun Johnson326166e2023-07-28 19:11:52 +00002488 status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers, true);
Arun Johnson106fe7a2023-04-26 17:49:43 +00002489 if (err != OK) {
2490 if (err == NO_MEMORY) {
2491 // NO_MEMORY happens here when all the buffers are still
2492 // with the codec. That is not an error as it is momentarily
2493 // and the buffers are send to the client as soon as the codec
2494 // releases them
2495 ALOGI("Resuming with all input buffers still with codec");
2496 } else {
2497 ALOGE("Resume request for Input Buffers failed");
2498 mCallback->onError(err, ACTION_CODE_FATAL);
2499 return;
2500 }
2501 }
2502
2503 // channel start should be called after prepareInitialBuffers
2504 // Calling before can cause a failure during prepare when
2505 // buffers are sent to the client before preparation from onWorkDone
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002506 (void)mChannel->start(nullptr, nullptr, [&]{
2507 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2508 const std::unique_ptr<Config> &config = *configLocked;
2509 return config->mBuffersBoundToCodec;
2510 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002511 {
2512 Mutexed<State>::Locked state(mState);
2513 if (state->get() != RESUMING) {
2514 state.unlock();
2515 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2516 state.lock();
2517 return;
2518 }
2519 state->set(RUNNING);
2520 }
2521
Wonsik Kim34b28b42022-05-20 15:49:32 -07002522 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002523}
2524
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002525void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002526 std::shared_ptr<Codec2Client::Component> comp;
2527 auto checkState = [this, &comp] {
2528 Mutexed<State>::Locked state(mState);
2529 if (state->get() == RELEASED) {
2530 return INVALID_OPERATION;
2531 }
2532 comp = state->comp;
2533 return OK;
2534 };
2535 if (tryAndReportOnError(checkState) != OK) {
2536 return;
2537 }
2538
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002539 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2540 // the behavior here.
2541 sp<AMessage> params = msg;
2542 int32_t bitrate;
2543 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2544 params = msg->dup();
2545 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2546 }
2547
Houxiang Dai5a97b472021-03-22 17:56:04 +08002548 int32_t syncId = 0;
2549 if (params->findInt32("audio-hw-sync", &syncId)
2550 || params->findInt32("hw-av-sync-id", &syncId)) {
2551 configureTunneledVideoPlayback(comp, nullptr, params);
2552 }
2553
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002554 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2555 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002556
2557 /**
2558 * Handle input surface parameters
2559 */
2560 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002561 && (config->mDomain & Config::IS_ENCODER)
2562 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002563 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002564
2565 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2566 config->mISConfig->mStopped = false;
2567 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2568 config->mISConfig->mStopped = true;
2569 }
2570
2571 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002572 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002573 config->mISConfig->mSuspended = value;
2574 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002575 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002576 }
2577
2578 (void)config->mInputSurface->configure(*config->mISConfig);
2579 if (config->mISConfig->mStopped) {
2580 config->mInputFormat->setInt64(
2581 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2582 }
2583 }
2584
Harish Mahendrakar38a99c22024-02-26 20:28:05 +05302585 /**
2586 * Handle ROI QP map configuration. Recover the QP map configuration from AMessage as an
2587 * ABuffer and configure to CCodecBufferChannel as a C2InfoBuffer
2588 */
2589 if (android::media::codec::provider_->region_of_interest()
2590 && android::media::codec::provider_->region_of_interest_support()) {
2591 sp<ABuffer> qpOffsetMap;
2592 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
2593 && (config->mDomain & Config::IS_ENCODER)
2594 && params->findBuffer(PARAMETER_KEY_QP_OFFSET_MAP, &qpOffsetMap)) {
2595 std::shared_ptr<C2BlockPool> pool;
2596 // TODO(b/331443865) Use pooled block pool to improve efficiency
2597 c2_status_t status = GetCodec2BlockPool(C2BlockPool::BASIC_LINEAR, nullptr, &pool);
2598
2599 if (status == C2_OK) {
2600 size_t mapSize = qpOffsetMap->size();
2601 std::shared_ptr<C2LinearBlock> block;
2602 status = pool->fetchLinearBlock(mapSize,
2603 C2MemoryUsage{C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE}, &block);
2604 if (status == C2_OK && !block->map().get().error()) {
2605 C2WriteView wView = block->map().get();
2606 uint8_t* outData = wView.data();
2607 memcpy(outData, qpOffsetMap->data(), mapSize);
2608 C2InfoBuffer info = C2InfoBuffer::CreateLinearBuffer(
2609 kParamIndexQpOffsetMapBuffer,
2610 block->share(0, mapSize, C2Fence()));
2611 mChannel->setInfoBuffer(std::make_shared<C2InfoBuffer>(info));
2612 }
2613 }
2614 params->removeEntryByName(PARAMETER_KEY_QP_OFFSET_MAP);
2615 }
2616 }
2617
2618
Pawin Vongmasa36653902018-11-15 00:10:25 -08002619 std::vector<std::unique_ptr<C2Param>> configUpdate;
2620 (void)config->getConfigUpdateFromSdkParams(
2621 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2622 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2623 // Parameter synchronization is not defined when using input surface. For now, route
2624 // these directly to the component.
2625 if (config->mInputSurface == nullptr
2626 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2627 || comp->getName().find("c2.android.") == 0)) {
2628 mChannel->setParameters(configUpdate);
2629 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002630 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002631 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002632 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002633 }
2634}
2635
2636void CCodec::signalEndOfInputStream() {
2637 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2638}
2639
2640void CCodec::signalRequestIDRFrame() {
2641 std::shared_ptr<Codec2Client::Component> comp;
2642 {
2643 Mutexed<State>::Locked state(mState);
2644 if (state->get() == RELEASED) {
2645 ALOGD("no IDR request sent since component is released");
2646 return;
2647 }
2648 comp = state->comp;
2649 }
2650 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002651 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2652 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002653 std::vector<std::unique_ptr<C2Param>> params;
2654 params.push_back(
2655 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2656 config->setParameters(comp, params, C2_MAY_BLOCK);
2657}
2658
Wonsik Kim874ad382021-03-12 09:59:36 -08002659status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2660 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2661 const std::unique_ptr<Config> &config = *configLocked;
2662 return config->querySupportedParameters(names);
2663}
2664
2665status_t CCodec::describeParameter(
2666 const std::string &name, CodecParameterDescriptor *desc) {
2667 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2668 const std::unique_ptr<Config> &config = *configLocked;
2669 return config->describe(name, desc);
2670}
2671
2672status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2673 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2674 if (!comp) {
2675 return INVALID_OPERATION;
2676 }
2677 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2678 const std::unique_ptr<Config> &config = *configLocked;
2679 return config->subscribeToVendorConfigUpdate(comp, names);
2680}
2681
2682status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2683 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2684 if (!comp) {
2685 return INVALID_OPERATION;
2686 }
2687 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2688 const std::unique_ptr<Config> &config = *configLocked;
2689 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2690}
2691
Wonsik Kimab34ed62019-01-31 15:28:46 -08002692void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002693 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002694 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002695 bool shouldPost = queue->empty();
Wonsik Kimab34ed62019-01-31 15:28:46 -08002696 queue->splice(queue->end(), workItems);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002697 if (shouldPost) {
2698 (new AMessage(kWhatWorkDone, this))->post();
2699 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002700 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002701}
2702
Wonsik Kimab34ed62019-01-31 15:28:46 -08002703void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2704 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002705 if (arrayIndex == 0) {
2706 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002707 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2708 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002709 if (config->mInputSurface) {
2710 config->mInputSurface->onInputBufferDone(frameIndex);
2711 }
2712 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002713}
2714
2715void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2716 TimePoint now = std::chrono::steady_clock::now();
2717 CCodecWatchdog::getInstance()->watch(this);
2718 switch (msg->what()) {
2719 case kWhatAllocate: {
2720 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002721 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002722 sp<RefBase> obj;
2723 CHECK(msg->findObject("codecInfo", &obj));
2724 allocate((MediaCodecInfo *)obj.get());
2725 break;
2726 }
2727 case kWhatConfigure: {
2728 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002729 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002730 sp<AMessage> format;
2731 CHECK(msg->findMessage("format", &format));
2732 configure(format);
2733 break;
2734 }
2735 case kWhatStart: {
2736 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002737 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002738 start();
2739 break;
2740 }
2741 case kWhatStop: {
2742 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002743 setDeadline(now, 1500ms, "stop");
Sungtak Lee99144332023-01-26 11:03:14 +00002744 int32_t pushBlankBuffer;
2745 if (!msg->findInt32("pushBlankBuffer", &pushBlankBuffer)) {
2746 pushBlankBuffer = 0;
2747 }
2748 stop(static_cast<bool>(pushBlankBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002749 break;
2750 }
2751 case kWhatFlush: {
2752 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002753 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002754 flush();
2755 break;
2756 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002757 case kWhatRelease: {
2758 mChannel->release();
2759 mClient.reset();
2760 mClientListener.reset();
2761 break;
2762 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002763 case kWhatCreateInputSurface: {
2764 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002765 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002766 createInputSurface();
2767 break;
2768 }
2769 case kWhatSetInputSurface: {
2770 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002771 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002772 sp<RefBase> obj;
2773 CHECK(msg->findObject("surface", &obj));
2774 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2775 setInputSurface(surface);
2776 break;
2777 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002778 case kWhatWorkDone: {
2779 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002780 bool shouldPost = false;
2781 {
2782 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2783 if (queue->empty()) {
2784 break;
2785 }
2786 work.swap(queue->front());
2787 queue->pop_front();
2788 shouldPost = !queue->empty();
2789 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002790 if (shouldPost) {
2791 (new AMessage(kWhatWorkDone, this))->post();
2792 }
2793
Pawin Vongmasa36653902018-11-15 00:10:25 -08002794 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002795 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002796 sp<AMessage> outputFormat = nullptr;
2797 {
2798 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2799 const std::unique_ptr<Config> &config = *configLocked;
2800 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2801 config->watch<C2StreamInitDataInfo::output>();
2802 if (!work->worklets.empty()
2803 && (work->worklets.front()->output.flags
2804 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002805
Wonsik Kim75e22f42021-04-14 23:34:51 -07002806 // copy buffer info to config
2807 std::vector<std::unique_ptr<C2Param>> updates;
2808 for (const std::unique_ptr<C2Param> &param
2809 : work->worklets.front()->output.configUpdate) {
2810 updates.push_back(C2Param::Copy(*param));
2811 }
2812 unsigned stream = 0;
2813 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2814 work->worklets.front()->output.buffers;
2815 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2816 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2817 // move all info into output-stream #0 domain
2818 updates.emplace_back(
2819 C2Param::CopyAsStream(*info, true /* output */, stream));
2820 }
2821
2822 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2823 // for now only do the first block
2824 if (!blocks.empty()) {
2825 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2826 // block.crop().left, block.crop().top,
2827 // block.crop().width, block.crop().height,
2828 // block.width(), block.height());
2829 const C2ConstGraphicBlock &block = blocks[0];
2830 updates.emplace_back(new C2StreamCropRectInfo::output(
2831 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002832 }
2833 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002834 }
George Burgess IVc813a592020-02-22 22:54:44 -08002835
Wonsik Kim75e22f42021-04-14 23:34:51 -07002836 sp<AMessage> oldFormat = config->mOutputFormat;
2837 config->updateConfiguration(updates, config->mOutputDomain);
2838 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002839
Wonsik Kim75e22f42021-04-14 23:34:51 -07002840 // copy standard infos to graphic buffers if not already present (otherwise, we
2841 // may overwrite the actual intermediate value with a final value)
2842 stream = 0;
2843 const static C2Param::Index stdGfxInfos[] = {
2844 C2StreamRotationInfo::output::PARAM_TYPE,
2845 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2846 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2847 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Taehwan Kim2d222b82022-05-12 14:19:26 +09002848 C2StreamHdr10PlusInfo::output::PARAM_TYPE, // will be deprecated
2849 C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE,
Wonsik Kim75e22f42021-04-14 23:34:51 -07002850 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2851 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2852 };
2853 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2854 if (buf->data().graphicBlocks().size()) {
2855 for (C2Param::Index ix : stdGfxInfos) {
2856 if (!buf->hasInfo(ix)) {
2857 const C2Param *param =
2858 config->getConfigParameterValue(ix.withStream(stream));
2859 if (param) {
2860 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2861 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2862 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002863 }
2864 }
2865 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002866 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002867 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002868 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002869 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302870 if (work->worklets.empty()
2871 || !work->worklets.back()
2872 || (work->worklets.back()->output.flags
2873 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2874 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2875 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002876 }
2877 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002878 initData = initDataWatcher.update();
2879 AmendOutputFormatWithCodecSpecificData(
2880 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2881 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002882 }
2883 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002884 }
2885 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002886 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Songyue Han1e6769b2023-08-30 18:09:27 +00002887 // log metrics to MediaCodec
2888 if (mMetrics->countEntries() == 0) {
2889 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2890 const std::unique_ptr<Config> &config = *configLocked;
2891 uint32_t pf = PIXEL_FORMAT_UNKNOWN;
2892 if (!config->mInputSurface) {
2893 pf = mChannel->getBuffersPixelFormat(config->mDomain & Config::IS_ENCODER);
Songyue Hanad01f6a2023-08-17 05:45:35 +00002894 } else {
2895 pf = config->mInputSurface->getPixelFormat();
Songyue Han1e6769b2023-08-30 18:09:27 +00002896 }
2897 if (pf != PIXEL_FORMAT_UNKNOWN) {
2898 mMetrics->setInt64(kCodecPixelFormat, pf);
2899 mCallback->onMetricsUpdated(mMetrics);
2900 }
2901 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002902 break;
2903 }
2904 case kWhatWatch: {
2905 // watch message already posted; no-op.
2906 break;
2907 }
2908 default: {
2909 ALOGE("unrecognized message");
2910 break;
2911 }
2912 }
2913 setDeadline(TimePoint::max(), 0ms, "none");
2914}
2915
2916void CCodec::setDeadline(
2917 const TimePoint &now,
2918 const std::chrono::milliseconds &timeout,
2919 const char *name) {
2920 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2921 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2922 deadline->set(now + (timeout * mult), name);
2923}
2924
ted.sun765db4d2020-06-23 14:03:41 +08002925status_t CCodec::configureTunneledVideoPlayback(
2926 std::shared_ptr<Codec2Client::Component> comp,
2927 sp<NativeHandle> *sidebandHandle,
2928 const sp<AMessage> &msg) {
2929 std::vector<std::unique_ptr<C2SettingResult>> failures;
2930
2931 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2932 C2PortTunneledModeTuning::output::AllocUnique(
2933 1,
2934 C2PortTunneledModeTuning::Struct::SIDEBAND,
2935 C2PortTunneledModeTuning::Struct::REALTIME,
2936 0);
2937 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2938 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2939 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2940 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2941 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2942 } else {
2943 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2944 tunneledPlayback->setFlexCount(0);
2945 }
2946 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2947 if (c2err != C2_OK) {
2948 return UNKNOWN_ERROR;
2949 }
2950
Houxiang Dai5a97b472021-03-22 17:56:04 +08002951 if (sidebandHandle == nullptr) {
2952 return OK;
2953 }
2954
ted.sun765db4d2020-06-23 14:03:41 +08002955 std::vector<std::unique_ptr<C2Param>> params;
2956 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2957 if (c2err == C2_OK && params.size() == 1u) {
2958 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2959 C2PortTunnelHandleTuning::output::From(params[0].get());
2960 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2961 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2962 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2963 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2964 memcpy(handle->data, videoTunnelSideband->m.values,
2965 sizeof(int32_t) * videoTunnelSideband->flexCount());
2966 return OK;
2967 } else {
2968 return NO_MEMORY;
2969 }
2970 }
2971 return UNKNOWN_ERROR;
2972}
2973
Pawin Vongmasa36653902018-11-15 00:10:25 -08002974void CCodec::initiateReleaseIfStuck() {
Shrikara B3b87a532022-08-26 14:18:14 +05302975 std::string name;
2976 bool pendingDeadline = false;
2977 {
2978 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2979 if (deadline->get() < std::chrono::steady_clock::now()) {
2980 name = deadline->getName();
2981 }
2982 if (deadline->get() != TimePoint::max()) {
2983 pendingDeadline = true;
2984 }
2985 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002986 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002987 // We're not stuck.
2988 if (pendingDeadline) {
2989 // If we are not stuck yet but still has deadline coming up,
2990 // post watch message to check back later.
2991 (new AMessage(kWhatWatch, this))->post();
2992 }
2993 return;
2994 }
2995
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002996 C2String compName;
2997 {
2998 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002999 if (!state->comp) {
3000 ALOGD("previous call to %s exceeded timeout "
3001 "and the component is already released", name.c_str());
3002 return;
3003 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09003004 compName = state->comp->getName();
3005 }
3006 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
3007
Pawin Vongmasa36653902018-11-15 00:10:25 -08003008 initiateRelease(false);
3009 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
3010}
3011
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003012// static
3013PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07003014 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07003015 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08003016 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07003017 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
3018 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08003019 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07003020 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
Sungtak Lee92bca442024-03-12 09:10:31 +00003021 if (Codec2Client::IsAidlSelected()) {
3022 sp<IGraphicBufferProducer> gbp;
3023 sp<AidlGraphicBufferSource> gbs = new AidlGraphicBufferSource();
3024 status_t err = gbs->initCheck();
3025 if (err != OK) {
3026 ALOGE("Failed to create persistent input surface: error %d", err);
3027 return nullptr;
3028 }
3029 ALOGD("aidl based PersistentSurface created");
3030 std::shared_ptr<WAidlGraphicBufferSource> wrapper =
3031 ::ndk::SharedRefBase::make<WAidlGraphicBufferSource>(gbs);
3032
3033 return new PersistentSurface(
3034 gbs->getIGraphicBufferProducer(), wrapper->asBinder());
3035 } else {
3036 sp<IGraphicBufferProducer> gbp;
3037 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
3038 status_t err = gbs->initCheck();
3039 if (err != OK) {
3040 ALOGE("Failed to create persistent input surface: error %d", err);
3041 return nullptr;
3042 }
3043 ALOGD("hidl based PersistentSurface created");
3044 return new PersistentSurface(
3045 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07003046 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07003047 } else {
3048 return nullptr;
3049 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08003050 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07003051 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08003052 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07003053 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08003054 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08003055}
3056
Wonsik Kimffb889a2020-05-28 11:32:25 -07003057class IntfCache {
3058public:
3059 IntfCache() = default;
3060
3061 status_t init(const std::string &name) {
3062 std::shared_ptr<Codec2Client::Interface> intf{
3063 Codec2Client::CreateInterfaceByName(name.c_str())};
3064 if (!intf) {
3065 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
3066 mInitStatus = NO_INIT;
3067 return NO_INIT;
3068 }
3069 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
3070 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
3071 C2ParamField{&sUsage, &sUsage.value}));
3072 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
3073 if (err != C2_OK) {
3074 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
3075 name.c_str(), err);
3076 mFields[0].status = err;
3077 }
3078 std::vector<std::unique_ptr<C2Param>> params;
3079 err = intf->query(
3080 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09003081 {
3082 C2StreamBufferTypeSetting::input::PARAM_TYPE,
3083 C2PortAllocatorsTuning::input::PARAM_TYPE
3084 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07003085 C2_MAY_BLOCK,
3086 &params);
3087 if (err != C2_OK && err != C2_BAD_INDEX) {
3088 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
3089 name.c_str(), err);
3090 }
3091 while (!params.empty()) {
3092 C2Param *param = params.back().release();
3093 params.pop_back();
3094 if (!param) {
3095 continue;
3096 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09003097 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
3098 mInputStreamFormat.reset(
3099 C2StreamBufferTypeSetting::input::From(param));
3100 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003101 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07003102 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07003103 }
3104 }
3105 mInitStatus = OK;
3106 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003107 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003108
3109 status_t initCheck() const { return mInitStatus; }
3110
3111 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
3112 CHECK_EQ(1u, mFields.size());
3113 return mFields[0];
3114 }
3115
3116 const C2ApiFeaturesSetting &getApiFeatures() const {
3117 return mApiFeatures;
3118 }
3119
Taehwan Kim900b49c2021-12-13 11:16:22 +09003120 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
3121 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
3122 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
3123 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
3124 param->invalidate();
3125 return param;
3126 }();
3127 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
3128 }
3129
Wonsik Kimffb889a2020-05-28 11:32:25 -07003130 const C2PortAllocatorsTuning::input &getInputAllocators() const {
3131 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
3132 std::unique_ptr<C2PortAllocatorsTuning::input> param =
3133 C2PortAllocatorsTuning::input::AllocUnique(0);
3134 param->invalidate();
3135 return param;
3136 }();
3137 return mInputAllocators ? *mInputAllocators : *sInvalidated;
3138 }
3139
3140private:
3141 status_t mInitStatus{NO_INIT};
3142
3143 std::vector<C2FieldSupportedValuesQuery> mFields;
3144 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09003145 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003146 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
3147};
3148
3149static const IntfCache &GetIntfCache(const std::string &name) {
3150 static IntfCache sNullIntfCache;
3151 static std::mutex sMutex;
3152 static std::map<std::string, IntfCache> sCache;
3153 std::unique_lock<std::mutex> lock{sMutex};
3154 auto it = sCache.find(name);
3155 if (it == sCache.end()) {
3156 lock.unlock();
3157 IntfCache intfCache;
3158 status_t err = intfCache.init(name);
3159 if (err != OK) {
3160 return sNullIntfCache;
3161 }
3162 lock.lock();
3163 it = sCache.insert({name, std::move(intfCache)}).first;
3164 }
3165 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003166}
3167
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003168static status_t GetCommonAllocatorIds(
3169 const std::vector<std::string> &names,
3170 C2Allocator::type_t type,
3171 std::set<C2Allocator::id_t> *ids) {
3172 int poolMask = GetCodec2PoolMask();
3173 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
3174 C2Allocator::id_t defaultAllocatorId =
3175 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
3176
3177 ids->clear();
3178 if (names.empty()) {
3179 return OK;
3180 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003181 bool firstIteration = true;
3182 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003183 const IntfCache &intfCache = GetIntfCache(name);
3184 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003185 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003186 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09003187 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
3188 if (streamFormat) {
3189 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
3190 if (streamFormat.value == C2BufferData::GRAPHIC
3191 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
3192 allocatorType = C2Allocator::GRAPHIC;
3193 }
3194
3195 if (type != allocatorType) {
3196 // requested type is not supported at input allocators
3197 ids->clear();
3198 ids->insert(defaultAllocatorId);
3199 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
3200 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
3201 break;
3202 }
3203 }
3204
Wonsik Kimffb889a2020-05-28 11:32:25 -07003205 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003206 if (firstIteration) {
3207 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003208 if (allocators && allocators.flexCount() > 0) {
3209 ids->insert(allocators.m.values,
3210 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003211 }
3212 if (ids->empty()) {
3213 // The component does not advertise allocators. Use default.
3214 ids->insert(defaultAllocatorId);
3215 }
3216 continue;
3217 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003218 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003219 if (allocators && allocators.flexCount() > 0) {
3220 filtered = true;
3221 for (auto it = ids->begin(); it != ids->end(); ) {
3222 bool found = false;
3223 for (size_t j = 0; j < allocators.flexCount(); ++j) {
3224 if (allocators.m.values[j] == *it) {
3225 found = true;
3226 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003227 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003228 }
3229 if (found) {
3230 ++it;
3231 } else {
3232 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003233 }
3234 }
3235 }
3236 if (!filtered) {
3237 // The component does not advertise supported allocators. Use default.
3238 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
3239 if (ids->size() != (containsDefault ? 1 : 0)) {
3240 ids->clear();
3241 if (containsDefault) {
3242 ids->insert(defaultAllocatorId);
3243 }
3244 }
3245 }
3246 }
3247 // Finally, filter with pool masks
3248 for (auto it = ids->begin(); it != ids->end(); ) {
3249 if ((poolMask >> *it) & 1) {
3250 ++it;
3251 } else {
3252 it = ids->erase(it);
3253 }
3254 }
3255 return OK;
3256}
3257
3258static status_t CalculateMinMaxUsage(
3259 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
3260 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
3261 *minUsage = 0;
3262 *maxUsage = ~0ull;
3263 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003264 const IntfCache &intfCache = GetIntfCache(name);
3265 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003266 continue;
3267 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003268 const C2FieldSupportedValuesQuery &usageSupportedValues =
3269 intfCache.getUsageSupportedValues();
3270 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003271 continue;
3272 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003273 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003274 if (supported.type != C2FieldSupportedValues::FLAGS) {
3275 continue;
3276 }
3277 if (supported.values.empty()) {
3278 *maxUsage = 0;
3279 continue;
3280 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08003281 if (supported.values.size() > 1) {
3282 *minUsage |= supported.values[1].u64;
3283 } else {
3284 *minUsage |= supported.values[0].u64;
3285 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003286 int64_t currentMaxUsage = 0;
3287 for (const C2Value::Primitive &flags : supported.values) {
3288 currentMaxUsage |= flags.u64;
3289 }
3290 *maxUsage &= currentMaxUsage;
3291 }
3292 return OK;
3293}
3294
3295// static
3296status_t CCodec::CanFetchLinearBlock(
3297 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003298 for (const std::string &name : names) {
3299 const IntfCache &intfCache = GetIntfCache(name);
3300 if (intfCache.initCheck() != OK) {
3301 continue;
3302 }
3303 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
3304 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
3305 *isCompatible = false;
3306 return OK;
3307 }
3308 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003309 std::set<C2Allocator::id_t> allocators;
3310 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
3311 if (allocators.empty()) {
3312 *isCompatible = false;
3313 return OK;
3314 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003315
3316 uint64_t minUsage = 0;
3317 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003318 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003319 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003320 *isCompatible = ((maxUsage & minUsage) == minUsage);
3321 return OK;
3322}
3323
3324static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
3325 static std::mutex sMutex{};
3326 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
3327 std::unique_lock<std::mutex> lock{sMutex};
3328 std::shared_ptr<C2BlockPool> pool;
3329 auto it = sPools.find(allocId);
3330 if (it == sPools.end()) {
3331 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3332 if (err == OK) {
3333 sPools.emplace(allocId, pool);
3334 } else {
3335 pool.reset();
3336 }
3337 } else {
3338 pool = it->second;
3339 }
3340 return pool;
3341}
3342
3343// static
3344std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
3345 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003346 std::set<C2Allocator::id_t> allocators;
3347 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
3348 if (allocators.empty()) {
3349 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
3350 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003351
3352 uint64_t minUsage = 0;
3353 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003354 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003355 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003356 if ((maxUsage & minUsage) != minUsage) {
3357 allocators.clear();
3358 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
3359 }
3360 std::shared_ptr<C2LinearBlock> block;
3361 for (C2Allocator::id_t allocId : allocators) {
3362 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
3363 if (!pool) {
3364 continue;
3365 }
3366 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
3367 if (err != C2_OK || !block) {
3368 block.reset();
3369 continue;
3370 }
3371 break;
3372 }
3373 return block;
3374}
3375
3376// static
3377status_t CCodec::CanFetchGraphicBlock(
3378 const std::vector<std::string> &names, bool *isCompatible) {
3379 uint64_t minUsage = 0;
3380 uint64_t maxUsage = ~0ull;
3381 std::set<C2Allocator::id_t> allocators;
3382 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3383 if (allocators.empty()) {
3384 *isCompatible = false;
3385 return OK;
3386 }
3387 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3388 *isCompatible = ((maxUsage & minUsage) == minUsage);
3389 return OK;
3390}
3391
3392// static
3393std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
3394 int32_t width,
3395 int32_t height,
3396 int32_t format,
3397 uint64_t usage,
3398 const std::vector<std::string> &names) {
3399 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
3400 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
3401 ALOGD("Unrecognized pixel format: %d", format);
3402 return nullptr;
3403 }
3404 uint64_t minUsage = 0;
3405 uint64_t maxUsage = ~0ull;
3406 std::set<C2Allocator::id_t> allocators;
3407 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3408 if (allocators.empty()) {
3409 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3410 }
3411 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3412 minUsage |= usage;
3413 if ((maxUsage & minUsage) != minUsage) {
3414 allocators.clear();
3415 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3416 }
3417 std::shared_ptr<C2GraphicBlock> block;
3418 for (C2Allocator::id_t allocId : allocators) {
3419 std::shared_ptr<C2BlockPool> pool;
3420 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3421 if (err != C2_OK || !pool) {
3422 continue;
3423 }
3424 err = pool->fetchGraphicBlock(
3425 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
3426 if (err != C2_OK || !block) {
3427 block.reset();
3428 continue;
3429 }
3430 break;
3431 }
3432 return block;
3433}
3434
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003435} // namespace android