blob: d14068ddc28bfc9c287698ea2bd6926280d68530 [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
24#include <C2Config.h>
25#include <C2Debug.h>
26#include <C2ParamInternal.h>
27#include <C2PlatformSupport.h>
28
Sungtak Lee92bca442024-03-12 09:10:31 +000029#include <aidl/android/hardware/graphics/common/Dataspace.h>
30#include <aidl/android/media/IAidlGraphicBufferSource.h>
31#include <aidl/android/media/IAidlBufferSource.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080032#include <android/IOMXBufferSource.h>
Pawin Vongmasabf69de92019-10-29 06:21:27 -070033#include <android/hardware/media/c2/1.0/IInputSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080034#include <android/hardware/media/omx/1.0/IGraphicBufferSource.h>
35#include <android/hardware/media/omx/1.0/IOmx.h>
Wonsik Kim50811882022-04-28 15:57:27 -070036#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080037#include <android-base/stringprintf.h>
38#include <cutils/properties.h>
39#include <gui/IGraphicBufferProducer.h>
40#include <gui/Surface.h>
41#include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070042#include <media/omx/1.0/WOmxNode.h>
43#include <media/openmax/OMX_Core.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080044#include <media/openmax/OMX_IndexExt.h>
Wonsik Kim1f5063d2021-05-03 15:41:17 -070045#include <media/stagefright/foundation/avc_utils.h>
Harish Mahendrakarf6b3e5e2024-03-21 21:04:28 +000046#include <media/stagefright/foundation/AUtils.h>
Sungtak Lee92bca442024-03-12 09:10:31 +000047#include <media/stagefright/aidlpersistentsurface/AidlGraphicBufferSource.h>
48#include <media/stagefright/aidlpersistentsurface/C2NodeDef.h>
49#include <media/stagefright/aidlpersistentsurface/wrapper/Conversion.h>
50#include <media/stagefright/aidlpersistentsurface/wrapper/WAidlGraphicBufferSource.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070051#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
52#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070053#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080054#include <media/stagefright/BufferProducerWrapper.h>
55#include <media/stagefright/MediaCodecConstants.h>
Songyue Han1e6769b2023-08-30 18:09:27 +000056#include <media/stagefright/MediaCodecMetricsConstants.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080057#include <media/stagefright/PersistentSurface.h>
Brian Lindahlff74e9d2023-07-20 14:44:04 -060058#include <media/stagefright/RenderedFrameInfo.h>
ted.sun765db4d2020-06-23 14:03:41 +080059#include <utils/NativeHandle.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080060
Sungtak Lee92bca442024-03-12 09:10:31 +000061#include "C2AidlNode.h"
Sungtak Lee64c9d932024-03-26 03:46:53 +000062#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080063#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070064#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080065#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080066#include "InputSurfaceWrapper.h"
67
68extern "C" android::PersistentSurface *CreateInputSurface();
69
70namespace android {
71
72using namespace std::chrono_literals;
73using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
74using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080075using ::android::hardware::media::c2::V1_0::IInputSurface;
Sungtak Lee92bca442024-03-12 09:10:31 +000076using ::aidl::android::media::IAidlBufferSource;
77using ::aidl::android::media::IAidlNode;
78using ::android::media::AidlGraphicBufferSource;
79using ::android::media::WAidlGraphicBufferSource;
80using ::android::media::aidl_conversion::fromAidlStatus;
Pawin Vongmasa36653902018-11-15 00:10:25 -080081
Wonsik Kim9917d4a2019-10-24 12:56:38 -070082typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Sungtak Lee92bca442024-03-12 09:10:31 +000083typedef aidl::android::media::IAidlGraphicBufferSource AGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070084typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070085
Pawin Vongmasa36653902018-11-15 00:10:25 -080086namespace {
87
88class CCodecWatchdog : public AHandler {
89private:
90 enum {
91 kWhatWatch,
92 };
93 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
94
95public:
96 static sp<CCodecWatchdog> getInstance() {
97 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
98 static std::once_flag flag;
99 // Call Init() only once.
100 std::call_once(flag, Init, instance);
101 return instance;
102 }
103
104 ~CCodecWatchdog() = default;
105
106 void watch(sp<CCodec> codec) {
107 bool shouldPost = false;
108 {
109 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
110 // If a watch message is in flight, piggy-back this instance as well.
111 // Otherwise, post a new watch message.
112 shouldPost = codecs->empty();
113 codecs->emplace(codec);
114 }
115 if (shouldPost) {
116 ALOGV("posting watch message");
117 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
118 }
119 }
120
121protected:
122 void onMessageReceived(const sp<AMessage> &msg) {
123 switch (msg->what()) {
124 case kWhatWatch: {
125 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
126 ALOGV("watch for %zu codecs", codecs->size());
127 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
128 sp<CCodec> codec = it->promote();
129 if (codec == nullptr) {
130 continue;
131 }
132 codec->initiateReleaseIfStuck();
133 }
134 codecs->clear();
135 break;
136 }
137
138 default: {
139 TRESPASS("CCodecWatchdog: unrecognized message");
140 }
141 }
142 }
143
144private:
145 CCodecWatchdog() : mLooper(new ALooper) {}
146
147 static void Init(const sp<CCodecWatchdog> &thiz) {
148 ALOGV("Init");
149 thiz->mLooper->setName("CCodecWatchdog");
150 thiz->mLooper->registerHandler(thiz);
151 thiz->mLooper->start();
152 }
153
154 sp<ALooper> mLooper;
155
156 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
157};
158
159class C2InputSurfaceWrapper : public InputSurfaceWrapper {
160public:
161 explicit C2InputSurfaceWrapper(
162 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
163 mSurface(surface) {
164 }
165
166 ~C2InputSurfaceWrapper() override = default;
167
168 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
169 if (mConnection != nullptr) {
170 return ALREADY_EXISTS;
171 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800172 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800173 }
174
175 void disconnect() override {
176 if (mConnection != nullptr) {
177 mConnection->disconnect();
178 mConnection = nullptr;
179 }
180 }
181
182 status_t start() override {
183 // InputSurface does not distinguish started state
184 return OK;
185 }
186
187 status_t signalEndOfInputStream() override {
188 C2InputSurfaceEosTuning eos(true);
189 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800190 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800191 if (err != C2_OK) {
192 return UNKNOWN_ERROR;
193 }
194 return OK;
195 }
196
197 status_t configure(Config &config __unused) {
198 // TODO
199 return OK;
200 }
201
202private:
203 std::shared_ptr<Codec2Client::InputSurface> mSurface;
204 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
205};
206
Sungtak Lee92bca442024-03-12 09:10:31 +0000207class HGraphicBufferSourceWrapper : public InputSurfaceWrapper {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800208public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700209 typedef hardware::media::omx::V1_0::Status OmxStatus;
210
Sungtak Lee92bca442024-03-12 09:10:31 +0000211 HGraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700212 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800213 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700214 uint32_t height,
215 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800216 : mSource(source), mWidth(width), mHeight(height) {
217 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700218 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800219 }
Sungtak Lee92bca442024-03-12 09:10:31 +0000220 ~HGraphicBufferSourceWrapper() override = default;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800221
222 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
223 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700224 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800225 mNode->setFrameSize(mWidth, mHeight);
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700226 // Usage is queried during configure(), so setting it beforehand.
Sungtak Lee0cd4fbc2023-02-02 00:59:01 +0000227 // 64 bit set parameter is existing only in C2OMXNode.
228 OMX_U64 usage64 = mConfig.mUsage;
229 status_t res = mNode->setParameter(
230 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits64,
231 &usage64, sizeof(usage64));
232
233 if (res != OK) {
234 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
235 (void)mNode->setParameter(
236 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
237 &usage, sizeof(usage));
238 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700239
Yanqiang Fanc56f3e62021-09-28 16:54:07 +0800240 return GetStatus(mSource->configure(
241 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800242 }
243
244 void disconnect() override {
245 if (mNode == nullptr) {
246 return;
247 }
248 sp<IOMXBufferSource> source = mNode->getSource();
249 if (source == nullptr) {
250 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
251 return;
252 }
253 source->onOmxIdle();
254 source->onOmxLoaded();
255 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700256 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800257 }
258
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700259 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
260 if (status.isOk()) {
261 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
262 } else if (status.isDeadObject()) {
263 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800264 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700265 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800266 }
267
268 status_t start() override {
269 sp<IOMXBufferSource> source = mNode->getSource();
270 if (source == nullptr) {
271 return NO_INIT;
272 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900273
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800274 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800275 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900276
Wonsik Kim34d66012021-03-01 16:40:33 -0800277 OMX_PARAM_PORTDEFINITIONTYPE param;
278 param.nPortIndex = kPortIndexInput;
279 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
280 &param, sizeof(param));
281 if (err == OK) {
282 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900283 }
284
285 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800286 source->onInputBufferAdded(i);
287 }
288
289 source->onOmxExecuting();
290 return OK;
291 }
292
293 status_t signalEndOfInputStream() override {
294 return GetStatus(mSource->signalEndOfInputStream());
295 }
296
297 status_t configure(Config &config) {
298 std::stringstream status;
299 status_t err = OK;
300
301 // handle each configuration granually, in case we need to handle part of the configuration
302 // elsewhere
303
304 // TRICKY: we do not unset frame delay repeating
305 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
306 int64_t us = 1e6 / config.mMinFps + 0.5;
307 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
308 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
309 if (res != OK) {
310 status << " (=> " << asString(res) << ")";
311 err = res;
312 }
313 mConfig.mMinFps = config.mMinFps;
314 }
315
316 // pts gap
317 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
318 if (mNode != nullptr) {
319 OMX_PARAM_U32TYPE ptrGapParam = {};
320 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700321 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800322 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
323 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700324 // float -> uint32_t is undefined if the value is negative.
325 // First convert to int32_t to ensure the expected behavior.
326 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800327 (void)mNode->setParameter(
328 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
329 &ptrGapParam, sizeof(ptrGapParam));
330 }
331 }
332
333 // max fps
334 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700335 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800336 && config.mMaxFps != mConfig.mMaxFps) {
337 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
338 status << " maxFps=" << config.mMaxFps;
339 if (res != OK) {
340 status << " (=> " << asString(res) << ")";
341 err = res;
342 }
343 mConfig.mMaxFps = config.mMaxFps;
344 }
345
346 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
347 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
348 status << " timeOffset " << config.mTimeOffsetUs << "us";
349 if (res != OK) {
350 status << " (=> " << asString(res) << ")";
351 err = res;
352 }
353 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
354 }
355
356 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
357 status_t res =
358 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
359 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
360 if (res != OK) {
361 status << " (=> " << asString(res) << ")";
362 err = res;
363 }
364 mConfig.mCaptureFps = config.mCaptureFps;
365 mConfig.mCodedFps = config.mCodedFps;
366 }
367
368 if (config.mStartAtUs != mConfig.mStartAtUs
369 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
370 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
371 status << " start at " << config.mStartAtUs << "us";
372 if (res != OK) {
373 status << " (=> " << asString(res) << ")";
374 err = res;
375 }
376 mConfig.mStartAtUs = config.mStartAtUs;
377 mConfig.mStopped = config.mStopped;
378 }
379
380 // suspend-resume
381 if (config.mSuspended != mConfig.mSuspended) {
382 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
383 status << " " << (config.mSuspended ? "suspend" : "resume")
384 << " at " << config.mSuspendAtUs << "us";
385 if (res != OK) {
386 status << " (=> " << asString(res) << ")";
387 err = res;
388 }
389 mConfig.mSuspended = config.mSuspended;
390 mConfig.mSuspendAtUs = config.mSuspendAtUs;
391 }
392
393 if (config.mStopped != mConfig.mStopped && config.mStopped) {
394 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
395 status << " stop at " << config.mStopAtUs << "us";
396 if (res != OK) {
397 status << " (=> " << asString(res) << ")";
398 err = res;
399 } else {
400 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700401 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
402 [&res, &delayUs = config.mInputDelayUs](
403 auto status, auto stopTimeOffsetUs) {
404 res = static_cast<status_t>(status);
405 delayUs = stopTimeOffsetUs;
406 });
407 if (!trans.isOk()) {
408 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
409 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800410 if (res != OK) {
411 status << " (=> " << asString(res) << ")";
412 } else {
413 status << "=" << config.mInputDelayUs << "us";
414 }
415 mConfig.mInputDelayUs = config.mInputDelayUs;
416 }
417 mConfig.mStopAtUs = config.mStopAtUs;
418 mConfig.mStopped = config.mStopped;
419 }
420
421 // color aspects (android._color-aspects)
422
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700423 // consumer usage is queried earlier.
424
Wonsik Kima1335e12021-04-22 16:28:29 -0700425 // priority
426 if (mConfig.mPriority != config.mPriority) {
427 if (config.mPriority != INT_MAX) {
428 mNode->setPriority(config.mPriority);
429 }
430 mConfig.mPriority = config.mPriority;
431 }
432
Wonsik Kimbd557932019-07-02 15:51:20 -0700433 if (status.str().empty()) {
434 ALOGD("ISConfig not changed");
435 } else {
436 ALOGD("ISConfig%s", status.str().c_str());
437 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800438 return err;
439 }
440
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700441 void onInputBufferDone(c2_cntr64_t index) override {
442 mNode->onInputBufferDone(index);
443 }
444
Wonsik Kim673dd192021-01-29 14:58:12 -0800445 android_dataspace getDataspace() override {
446 return mNode->getDataspace();
447 }
448
Songyue Hanad01f6a2023-08-17 05:45:35 +0000449 uint32_t getPixelFormat() override {
450 return mNode->getPixelFormat();
451 }
452
Pawin Vongmasa36653902018-11-15 00:10:25 -0800453private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700454 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800455 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700456 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800457 uint32_t mWidth;
458 uint32_t mHeight;
459 Config mConfig;
460};
461
Sungtak Lee92bca442024-03-12 09:10:31 +0000462class AGraphicBufferSourceWrapper : public InputSurfaceWrapper {
463public:
464 AGraphicBufferSourceWrapper(
465 const std::shared_ptr<AGraphicBufferSource> &source,
466 uint32_t width,
467 uint32_t height,
468 uint64_t usage)
469 : mSource(source), mWidth(width), mHeight(height) {
470 mDataSpace = HAL_DATASPACE_BT709;
471 mConfig.mUsage = usage;
472 }
473 ~AGraphicBufferSourceWrapper() override = default;
474
475 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
476 mNode = ::ndk::SharedRefBase::make<C2AidlNode>(comp);
477 mNode->setFrameSize(mWidth, mHeight);
478 // Usage is queried during configure(), so setting it beforehand.
479 uint64_t usage = mConfig.mUsage;
480 (void)mNode->setConsumerUsage((int64_t)usage);
481
482 return fromAidlStatus(mSource->configure(
483 mNode, static_cast<::aidl::android::hardware::graphics::common::Dataspace>(
484 mDataSpace)));
485 }
486
487 void disconnect() override {
488 if (mNode == nullptr) {
489 return;
490 }
491 std::shared_ptr<IAidlBufferSource> source = mNode->getSource();
492 if (source == nullptr) {
493 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
494 return;
495 }
496 (void)source->onStop();
497 (void)source->onRelease();
498 mNode.reset();
499 }
500
501 status_t start() override {
502 std::shared_ptr<IAidlBufferSource> source = mNode->getSource();
503 if (source == nullptr) {
504 return NO_INIT;
505 }
506
507 size_t numSlots = 16;
508
509 IAidlNode::InputBufferParams param;
510 status_t err = fromAidlStatus(mNode->getInputBufferParams(&param));
511 if (err == OK) {
512 numSlots = param.bufferCountActual;
513 }
514
515 for (size_t i = 0; i < numSlots; ++i) {
516 (void)source->onInputBufferAdded(i);
517 }
518
519 (void)source->onStart();
520 return OK;
521 }
522
523 status_t signalEndOfInputStream() override {
524 return fromAidlStatus(mSource->signalEndOfInputStream());
525 }
526
527 status_t configure(Config &config) {
528 std::stringstream status;
529 status_t err = OK;
530
531 // handle each configuration granually, in case we need to handle part of the configuration
532 // elsewhere
533
534 // TRICKY: we do not unset frame delay repeating
535 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
536 int64_t us = 1e6 / config.mMinFps + 0.5;
537 status_t res = fromAidlStatus(mSource->setRepeatPreviousFrameDelayUs(us));
538 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
539 if (res != OK) {
540 status << " (=> " << asString(res) << ")";
541 err = res;
542 }
543 mConfig.mMinFps = config.mMinFps;
544 }
545
546 // pts gap
547 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
548 if (mNode != nullptr) {
549 float gap = (config.mMinAdjustedFps > 0)
550 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
551 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
552 // float -> uint32_t is undefined if the value is negative.
553 // First convert to int32_t to ensure the expected behavior.
554 int32_t gapUs = int32_t(gap);
555 (void)mNode->setAdjustTimestampGapUs(gapUs);
556 }
557 }
558
559 // max fps
560 // TRICKY: we do not unset max fps to 0 unless using fixed fps
561 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
562 && config.mMaxFps != mConfig.mMaxFps) {
563 status_t res = fromAidlStatus(mSource->setMaxFps(config.mMaxFps));
564 status << " maxFps=" << config.mMaxFps;
565 if (res != OK) {
566 status << " (=> " << asString(res) << ")";
567 err = res;
568 }
569 mConfig.mMaxFps = config.mMaxFps;
570 }
571
572 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
573 status_t res = fromAidlStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
574 status << " timeOffset " << config.mTimeOffsetUs << "us";
575 if (res != OK) {
576 status << " (=> " << asString(res) << ")";
577 err = res;
578 }
579 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
580 }
581
582 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
583 status_t res =
584 fromAidlStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
585 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
586 if (res != OK) {
587 status << " (=> " << asString(res) << ")";
588 err = res;
589 }
590 mConfig.mCaptureFps = config.mCaptureFps;
591 mConfig.mCodedFps = config.mCodedFps;
592 }
593
594 if (config.mStartAtUs != mConfig.mStartAtUs
595 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
596 status_t res = fromAidlStatus(mSource->setStartTimeUs(config.mStartAtUs));
597 status << " start at " << config.mStartAtUs << "us";
598 if (res != OK) {
599 status << " (=> " << asString(res) << ")";
600 err = res;
601 }
602 mConfig.mStartAtUs = config.mStartAtUs;
603 mConfig.mStopped = config.mStopped;
604 }
605
606 // suspend-resume
607 if (config.mSuspended != mConfig.mSuspended) {
608 status_t res = fromAidlStatus(mSource->setSuspend(
609 config.mSuspended, config.mSuspendAtUs));
610 status << " " << (config.mSuspended ? "suspend" : "resume")
611 << " at " << config.mSuspendAtUs << "us";
612 if (res != OK) {
613 status << " (=> " << asString(res) << ")";
614 err = res;
615 }
616 mConfig.mSuspended = config.mSuspended;
617 mConfig.mSuspendAtUs = config.mSuspendAtUs;
618 }
619
620 if (config.mStopped != mConfig.mStopped && config.mStopped) {
621 status_t res = fromAidlStatus(mSource->setStopTimeUs(config.mStopAtUs));
622 status << " stop at " << config.mStopAtUs << "us";
623 if (res != OK) {
624 status << " (=> " << asString(res) << ")";
625 err = res;
626 } else {
627 status << " delayUs";
628 res = fromAidlStatus(mSource->getStopTimeOffsetUs(&config.mInputDelayUs));
629 if (res != OK) {
630 status << " (=> " << asString(res) << ")";
631 } else {
632 status << "=" << config.mInputDelayUs << "us";
633 }
634 mConfig.mInputDelayUs = config.mInputDelayUs;
635 }
636 mConfig.mStopAtUs = config.mStopAtUs;
637 mConfig.mStopped = config.mStopped;
638 }
639
640 // color aspects (android._color-aspects)
641
642 // consumer usage is queried earlier.
643
644 // priority
645 if (mConfig.mPriority != config.mPriority) {
646 if (config.mPriority != INT_MAX) {
647 mNode->setPriority(config.mPriority);
648 }
649 mConfig.mPriority = config.mPriority;
650 }
651
652 if (status.str().empty()) {
653 ALOGD("ISConfig not changed");
654 } else {
655 ALOGD("ISConfig%s", status.str().c_str());
656 }
657 return err;
658 }
659
660 void onInputBufferDone(c2_cntr64_t index) override {
661 mNode->onInputBufferDone(index);
662 }
663
664 android_dataspace getDataspace() override {
665 return mNode->getDataspace();
666 }
667
668 uint32_t getPixelFormat() override {
669 return mNode->getPixelFormat();
670 }
671
672private:
673 std::shared_ptr<AGraphicBufferSource> mSource;
674 std::shared_ptr<C2AidlNode> mNode;
675 uint32_t mWidth;
676 uint32_t mHeight;
677 Config mConfig;
678};
679
Pawin Vongmasa36653902018-11-15 00:10:25 -0800680class Codec2ClientInterfaceWrapper : public C2ComponentStore {
681 std::shared_ptr<Codec2Client> mClient;
682
683public:
684 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
685 : mClient(client) { }
686
687 virtual ~Codec2ClientInterfaceWrapper() = default;
688
689 virtual c2_status_t config_sm(
690 const std::vector<C2Param *> &params,
691 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
692 return mClient->config(params, C2_MAY_BLOCK, failures);
693 };
694
695 virtual c2_status_t copyBuffer(
696 std::shared_ptr<C2GraphicBuffer>,
697 std::shared_ptr<C2GraphicBuffer>) {
698 return C2_OMITTED;
699 }
700
701 virtual c2_status_t createComponent(
702 C2String, std::shared_ptr<C2Component> *const component) {
703 component->reset();
704 return C2_OMITTED;
705 }
706
707 virtual c2_status_t createInterface(
708 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
709 interface->reset();
710 return C2_OMITTED;
711 }
712
713 virtual c2_status_t query_sm(
714 const std::vector<C2Param *> &stackParams,
715 const std::vector<C2Param::Index> &heapParamIndices,
716 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
717 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
718 }
719
720 virtual c2_status_t querySupportedParams_nb(
721 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
722 return mClient->querySupportedParams(params);
723 }
724
725 virtual c2_status_t querySupportedValues_sm(
726 std::vector<C2FieldSupportedValuesQuery> &fields) const {
727 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
728 }
729
730 virtual C2String getName() const {
731 return mClient->getName();
732 }
733
734 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
735 return mClient->getParamReflector();
736 }
737
738 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
739 return std::vector<std::shared_ptr<const C2Component::Traits>>();
740 }
741};
742
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800743void RevertOutputFormatIfNeeded(
744 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
745 // We used to not report changes to these keys to the client.
746 const static std::set<std::string> sIgnoredKeys({
747 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800748 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800749 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800750 KEY_MAX_WIDTH,
751 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800752 "csd-0",
753 "csd-1",
754 "csd-2",
755 });
756 if (currentFormat == oldFormat) {
757 return;
758 }
759 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
760 AMessage::Type type;
761 for (size_t i = diff->countEntries(); i > 0; --i) {
762 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
763 diff->removeEntryAt(i - 1);
764 }
765 }
766 if (diff->countEntries() == 0) {
767 currentFormat = oldFormat;
768 }
769}
770
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700771void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700772 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700773 const sp<AMessage> &outputFormat) {
774 if (mediaType == MIMETYPE_VIDEO_AVC) {
775 // Codec specific data should be SPS and PPS in a single buffer,
776 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
777 // We separate the two and put them into the output format
778 // under the keys "csd-0" and "csd-1".
779
780 unsigned csdIndex = 0;
781
782 const uint8_t *nalStart;
783 size_t nalSize;
784 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
785 sp<ABuffer> csd = new ABuffer(nalSize + 4);
786 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
787 memcpy(csd->data() + 4, nalStart, nalSize);
788
789 outputFormat->setBuffer(
790 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
791
792 ++csdIndex;
793 }
794
795 if (csdIndex != 2) {
796 ALOGW("Expected two NAL units from AVC codec config, but %u found",
797 csdIndex);
798 }
799 } else {
800 // For everything else we just stash the codec specific data into
801 // the output format as a single piece of csd under "csd-0".
802 sp<ABuffer> csd = new ABuffer(size);
803 memcpy(csd->data(), data, size);
804 csd->setRange(0, size);
805 outputFormat->setBuffer("csd-0", csd);
806 }
807}
808
Pawin Vongmasa36653902018-11-15 00:10:25 -0800809} // namespace
810
811// CCodec::ClientListener
812
813struct CCodec::ClientListener : public Codec2Client::Listener {
814
815 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
816
817 virtual void onWorkDone(
818 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800819 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800820 (void)component;
821 sp<CCodec> codec(mCodec.promote());
822 if (!codec) {
823 return;
824 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800825 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800826 }
827
828 virtual void onTripped(
829 const std::weak_ptr<Codec2Client::Component>& component,
830 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
831 ) override {
832 // TODO
833 (void)component;
834 (void)settingResult;
835 }
836
837 virtual void onError(
838 const std::weak_ptr<Codec2Client::Component>& component,
839 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800840 {
841 // Component is only used for reporting as we use a separate listener for each instance
842 std::shared_ptr<Codec2Client::Component> comp = component.lock();
843 if (!comp) {
844 ALOGD("Component died with error: 0x%x", errorCode);
845 } else {
846 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
847 }
848 }
849
850 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800851 // Note: for now we do not propagate the error code to MediaCodec
852 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800853 sp<CCodec> codec(mCodec.promote());
854 if (!codec || !codec->mCallback) {
855 return;
856 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800857 codec->mCallback->onError(
858 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
859 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800860 }
861
862 virtual void onDeath(
863 const std::weak_ptr<Codec2Client::Component>& component) override {
864 { // Log the death of the component.
865 std::shared_ptr<Codec2Client::Component> comp = component.lock();
866 if (!comp) {
867 ALOGE("Codec2 component died.");
868 } else {
869 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
870 }
871 }
872
873 // Report to MediaCodec.
874 sp<CCodec> codec(mCodec.promote());
875 if (!codec || !codec->mCallback) {
876 return;
877 }
878 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
879 }
880
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800881 virtual void onFrameRendered(uint64_t bufferQueueId,
882 int32_t slotId,
883 int64_t timestampNs) override {
884 // TODO: implement
885 (void)bufferQueueId;
886 (void)slotId;
887 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800888 }
889
890 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800891 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800892 sp<CCodec> codec(mCodec.promote());
893 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800894 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800895 }
896 }
897
898private:
899 wp<CCodec> mCodec;
900};
901
902// CCodecCallbackImpl
903
904class CCodecCallbackImpl : public CCodecCallback {
905public:
906 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
907 ~CCodecCallbackImpl() override = default;
908
909 void onError(status_t err, enum ActionCode actionCode) override {
910 mCodec->mCallback->onError(err, actionCode);
911 }
912
913 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
Brian Lindahlff74e9d2023-07-20 14:44:04 -0600914 mCodec->mCallback->onOutputFramesRendered({RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
Pawin Vongmasa36653902018-11-15 00:10:25 -0800915 }
916
Pawin Vongmasa36653902018-11-15 00:10:25 -0800917 void onOutputBuffersChanged() override {
918 mCodec->mCallback->onOutputBuffersChanged();
919 }
920
Guillaume Chelfi5ffbcb32021-04-12 14:23:43 +0200921 void onFirstTunnelFrameReady() override {
922 mCodec->mCallback->onFirstTunnelFrameReady();
923 }
924
Pawin Vongmasa36653902018-11-15 00:10:25 -0800925private:
926 CCodec *mCodec;
927};
928
929// CCodec
930
931CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700932 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
933 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800934}
935
936CCodec::~CCodec() {
937}
938
939std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
940 return mChannel;
941}
942
943status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
944 status_t err = job();
945 if (err != C2_OK) {
946 mCallback->onError(err, ACTION_CODE_FATAL);
947 }
948 return err;
949}
950
951void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
952 auto setAllocating = [this] {
953 Mutexed<State>::Locked state(mState);
954 if (state->get() != RELEASED) {
955 return INVALID_OPERATION;
956 }
957 state->set(ALLOCATING);
958 return OK;
959 };
960 if (tryAndReportOnError(setAllocating) != OK) {
961 return;
962 }
963
964 sp<RefBase> codecInfo;
965 CHECK(msg->findObject("codecInfo", &codecInfo));
966 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
967
968 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
969 allocMsg->setObject("codecInfo", codecInfo);
970 allocMsg->post();
971}
972
973void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
974 if (codecInfo == nullptr) {
975 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
976 return;
977 }
978 ALOGD("allocate(%s)", codecInfo->getCodecName());
979 mClientListener.reset(new ClientListener(this));
980
981 AString componentName = codecInfo->getCodecName();
982 std::shared_ptr<Codec2Client> client;
983
984 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700985 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800986 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800987 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800988 SetPreferredCodec2ComponentStore(
989 std::make_shared<Codec2ClientInterfaceWrapper>(client));
990 }
991
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900992 std::shared_ptr<Codec2Client::Component> comp;
993 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800994 componentName.c_str(),
995 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900996 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800997 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900998 if (status != C2_OK) {
999 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001000 Mutexed<State>::Locked state(mState);
1001 state->set(RELEASED);
1002 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +09001003 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001004 state.lock();
1005 return;
1006 }
1007 ALOGI("Created component [%s]", componentName.c_str());
1008 mChannel->setComponent(comp);
1009 auto setAllocated = [this, comp, client] {
1010 Mutexed<State>::Locked state(mState);
1011 if (state->get() != ALLOCATING) {
1012 state->set(RELEASED);
1013 return UNKNOWN_ERROR;
1014 }
1015 state->set(ALLOCATED);
1016 state->comp = comp;
1017 mClient = client;
1018 return OK;
1019 };
1020 if (tryAndReportOnError(setAllocated) != OK) {
1021 return;
1022 }
1023
1024 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001025 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1026 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001027 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001028 if (err != OK) {
1029 ALOGW("Failed to initialize configuration support");
1030 // TODO: report error once we complete implementation.
1031 }
1032 config->queryConfiguration(comp);
1033
1034 mCallback->onComponentAllocated(componentName.c_str());
1035}
1036
1037void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
1038 auto checkAllocated = [this] {
1039 Mutexed<State>::Locked state(mState);
1040 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
1041 };
1042 if (tryAndReportOnError(checkAllocated) != OK) {
1043 return;
1044 }
1045
1046 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
1047 msg->setMessage("format", format);
1048 msg->post();
1049}
1050
1051void CCodec::configure(const sp<AMessage> &msg) {
1052 std::shared_ptr<Codec2Client::Component> comp;
1053 auto checkAllocated = [this, &comp] {
1054 Mutexed<State>::Locked state(mState);
1055 if (state->get() != ALLOCATED) {
1056 state->set(RELEASED);
1057 return UNKNOWN_ERROR;
1058 }
1059 comp = state->comp;
1060 return OK;
1061 };
1062 if (tryAndReportOnError(checkAllocated) != OK) {
1063 return;
1064 }
1065
1066 auto doConfig = [msg, comp, this]() -> status_t {
1067 AString mime;
1068 if (!msg->findString("mime", &mime)) {
1069 return BAD_VALUE;
1070 }
1071
1072 int32_t encoder;
1073 if (!msg->findInt32("encoder", &encoder)) {
1074 encoder = false;
1075 }
1076
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001077 int32_t flags;
1078 if (!msg->findInt32("flags", &flags)) {
1079 return BAD_VALUE;
1080 }
1081
Pawin Vongmasa36653902018-11-15 00:10:25 -08001082 // TODO: read from intf()
1083 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
1084 return UNKNOWN_ERROR;
1085 }
1086
1087 int32_t storeMeta;
1088 if (encoder
1089 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
1090 && storeMeta != kMetadataBufferTypeInvalid) {
1091 if (storeMeta != kMetadataBufferTypeANWBuffer) {
1092 ALOGD("Only ANW buffers are supported for legacy metadata mode");
1093 return BAD_VALUE;
1094 }
1095 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
1096 }
1097
ted.sun765db4d2020-06-23 14:03:41 +08001098 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001099 sp<RefBase> obj;
1100 sp<Surface> surface;
1101 if (msg->findObject("native-window", &obj)) {
1102 surface = static_cast<Surface *>(obj.get());
Sungtak Lee214ce612023-11-01 10:01:13 +00001103 int32_t generation;
1104 (void)msg->findInt32("native-window-generation", &generation);
ted.sun765db4d2020-06-23 14:03:41 +08001105 // setup tunneled playback
1106 if (surface != nullptr) {
1107 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1108 const std::unique_ptr<Config> &config = *configLocked;
1109 if ((config->mDomain & Config::IS_DECODER)
1110 && (config->mDomain & Config::IS_VIDEO)) {
1111 int32_t tunneled;
1112 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
1113 ALOGI("Configuring TUNNELED video playback.");
1114
1115 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
1116 if (err != OK) {
1117 ALOGE("configureTunneledVideoPlayback failed!");
1118 return err;
1119 }
1120 config->mTunneled = true;
1121 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +01001122
1123 int32_t pushBlankBuffersOnStop = 0;
1124 if (msg->findInt32(KEY_PUSH_BLANK_BUFFERS_ON_STOP, &pushBlankBuffersOnStop)) {
1125 config->mPushBlankBuffersOnStop = pushBlankBuffersOnStop == 1;
1126 }
shuanglong.wang480a8362023-02-17 20:55:51 +08001127 // secure compoment or protected content default with
1128 // "push-blank-buffers-on-shutdown" flag
1129 if (!config->mPushBlankBuffersOnStop) {
1130 int32_t usageProtected;
1131 if (comp->getName().find(".secure") != std::string::npos) {
1132 config->mPushBlankBuffersOnStop = true;
1133 } else if (msg->findInt32("protected", &usageProtected) && usageProtected) {
1134 config->mPushBlankBuffersOnStop = true;
1135 }
1136 }
ted.sun765db4d2020-06-23 14:03:41 +08001137 }
1138 }
Sungtak Lee214ce612023-11-01 10:01:13 +00001139 setSurface(surface, (uint32_t)generation);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001140 }
1141
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001142 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1143 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001144 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001145 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
1146 ALOGD("[%s] buffers are %sbound to CCodec for this session",
1147 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001148
Wonsik Kim1114eea2019-02-25 14:35:24 -08001149 // Enforce required parameters
1150 int32_t i32;
1151 float flt;
1152 if (config->mDomain & Config::IS_AUDIO) {
1153 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
1154 ALOGD("sample rate is missing, which is required for audio components.");
1155 return BAD_VALUE;
1156 }
1157 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
1158 ALOGD("channel count is missing, which is required for audio components.");
1159 return BAD_VALUE;
1160 }
1161 if ((config->mDomain & Config::IS_ENCODER)
1162 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
1163 && !msg->findInt32(KEY_BIT_RATE, &i32)
1164 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
1165 ALOGD("bitrate is missing, which is required for audio encoders.");
1166 return BAD_VALUE;
1167 }
1168 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001169 int32_t width = 0;
1170 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -08001171 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001172 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -08001173 ALOGD("width is missing, which is required for image/video components.");
1174 return BAD_VALUE;
1175 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001176 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -08001177 ALOGD("height is missing, which is required for image/video components.");
1178 return BAD_VALUE;
1179 }
1180 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -07001181 int32_t mode = BITRATE_MODE_VBR;
1182 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -07001183 if (!msg->findInt32(KEY_QUALITY, &i32)) {
1184 ALOGD("quality is missing, which is required for video encoders in CQ.");
1185 return BAD_VALUE;
1186 }
1187 } else {
1188 if (!msg->findInt32(KEY_BIT_RATE, &i32)
1189 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
1190 ALOGD("bitrate is missing, which is required for video encoders.");
1191 return BAD_VALUE;
1192 }
Wonsik Kim1114eea2019-02-25 14:35:24 -08001193 }
1194 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
1195 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
1196 ALOGD("I frame interval is missing, which is required for video encoders.");
1197 return BAD_VALUE;
1198 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001199 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
1200 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
1201 ALOGD("frame rate is missing, which is required for video encoders.");
1202 return BAD_VALUE;
1203 }
Wonsik Kim1114eea2019-02-25 14:35:24 -08001204 }
1205 }
1206
Pawin Vongmasa36653902018-11-15 00:10:25 -08001207 /*
1208 * Handle input surface configuration
1209 */
1210 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1211 && (config->mDomain & Config::IS_ENCODER)) {
1212 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
1213 {
1214 config->mISConfig->mMinFps = 0;
1215 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001216 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001217 config->mISConfig->mMinFps = 1e6 / value;
1218 }
Wonsik Kim95ba0162019-03-19 15:51:54 -07001219 if (!msg->findFloat(
1220 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
1221 config->mISConfig->mMaxFps = -1;
1222 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001223 config->mISConfig->mMinAdjustedFps = 0;
1224 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -08001225 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001226 if (value < 0 && value >= INT32_MIN) {
1227 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -07001228 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001229 } else if (value > 0 && value <= INT32_MAX) {
1230 config->mISConfig->mMinAdjustedFps = 1e6 / value;
1231 }
1232 }
1233 }
1234
1235 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -07001236 bool captureFpsFound = false;
1237 double timeLapseFps;
1238 float captureRate;
1239 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
1240 config->mISConfig->mCaptureFps = timeLapseFps;
1241 captureFpsFound = true;
1242 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
1243 config->mISConfig->mCaptureFps = captureRate;
1244 captureFpsFound = true;
1245 }
1246 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001247 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
1248 }
1249 }
1250
1251 {
1252 config->mISConfig->mSuspended = false;
1253 config->mISConfig->mSuspendAtUs = -1;
1254 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001255 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001256 config->mISConfig->mSuspended = true;
1257 }
1258 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001259 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -07001260 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001261 }
1262
1263 /*
1264 * Handle desired color format.
1265 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001266 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001267 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001268 int32_t format = 0;
1269 // Query vendor format for Flexible YUV
1270 std::vector<std::unique_ptr<C2Param>> heapParams;
1271 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
Wonsik Kim50811882022-04-28 15:57:27 -07001272 int vendorSdkVersion = base::GetIntProperty(
1273 "ro.vendor.build.version.sdk", android_get_device_api_level());
guochuang709b48b2022-10-25 20:40:42 +08001274 if (mClient->query(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001275 {},
1276 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1277 C2_MAY_BLOCK,
1278 &heapParams) == C2_OK
1279 && heapParams.size() == 1u) {
1280 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1281 heapParams[0].get());
1282 } else {
1283 pixelFormatInfo = nullptr;
1284 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001285 // bit depth -> format
1286 std::map<uint32_t, uint32_t> flexPixelFormat;
1287 std::map<uint32_t, uint32_t> flexPlanarPixelFormat;
1288 std::map<uint32_t, uint32_t> flexSemiPlanarPixelFormat;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001289 if (pixelFormatInfo && *pixelFormatInfo) {
1290 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1291 const C2FlexiblePixelFormatDescriptorStruct &desc =
1292 pixelFormatInfo->m.values[i];
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001293 if (desc.subsampling != C2Color::YUV_420
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001294 // TODO(b/180076105): some device report wrong layout
1295 // || desc.layout == C2Color::INTERLEAVED_PACKED
1296 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1297 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1298 continue;
1299 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001300 if (flexPixelFormat.count(desc.bitDepth) == 0) {
1301 flexPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001302 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001303 if (desc.layout == C2Color::PLANAR_PACKED
1304 && flexPlanarPixelFormat.count(desc.bitDepth) == 0) {
1305 flexPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001306 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001307 if (desc.layout == C2Color::SEMIPLANAR_PACKED
1308 && flexSemiPlanarPixelFormat.count(desc.bitDepth) == 0) {
1309 flexSemiPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001310 }
1311 }
1312 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001313 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001314 // Also handle default color format (encoders require color format, so this is only
1315 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001316 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001317 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001318 const char *prefix = "";
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001319 if (flexSemiPlanarPixelFormat.count(8) != 0) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001320 format = COLOR_FormatYUV420SemiPlanar;
1321 prefix = "semi-";
1322 } else {
1323 format = COLOR_FormatYUV420Planar;
1324 }
1325 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1326 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001327 } else {
1328 format = COLOR_FormatSurface;
1329 }
1330 defaultColorFormat = format;
1331 }
1332 } else {
1333 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001334 if (vendorSdkVersion < __ANDROID_API_S__ &&
Taehwan Kim43e715d2022-09-22 12:04:59 +09001335 (format == COLOR_FormatYUV420Planar ||
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001336 format == COLOR_FormatYUV420PackedPlanar ||
1337 format == COLOR_FormatYUV420SemiPlanar ||
1338 format == COLOR_FormatYUV420PackedSemiPlanar)) {
1339 // pre-S framework used to map these color formats into YV12.
1340 // Codecs from older vendor partition may be relying on
1341 // this assumption.
1342 format = HAL_PIXEL_FORMAT_YV12;
1343 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001344 switch (format) {
1345 case COLOR_FormatYUV420Flexible:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001346 format = COLOR_FormatYUV420Planar;
1347 if (flexPixelFormat.count(8) != 0) {
1348 format = flexPixelFormat[8];
1349 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001350 break;
1351 case COLOR_FormatYUV420Planar:
1352 case COLOR_FormatYUV420PackedPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001353 if (flexPlanarPixelFormat.count(8) != 0) {
1354 format = flexPlanarPixelFormat[8];
1355 } else if (flexPixelFormat.count(8) != 0) {
1356 format = flexPixelFormat[8];
1357 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001358 break;
1359 case COLOR_FormatYUV420SemiPlanar:
1360 case COLOR_FormatYUV420PackedSemiPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001361 if (flexSemiPlanarPixelFormat.count(8) != 0) {
1362 format = flexSemiPlanarPixelFormat[8];
1363 } else if (flexPixelFormat.count(8) != 0) {
1364 format = flexPixelFormat[8];
1365 }
1366 break;
1367 case COLOR_FormatYUVP010:
1368 format = COLOR_FormatYUVP010;
1369 if (flexSemiPlanarPixelFormat.count(10) != 0) {
1370 format = flexSemiPlanarPixelFormat[10];
1371 } else if (flexPixelFormat.count(10) != 0) {
1372 format = flexPixelFormat[10];
1373 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001374 break;
1375 default:
1376 // No-op
1377 break;
1378 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001379 }
1380 }
1381
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001382 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001383 msg->setInt32("android._color-format", format);
1384 }
1385 }
1386
Wonsik Kim77e97c72021-01-20 10:33:22 -08001387 /*
1388 * Handle dataspace
1389 */
1390 int32_t usingRecorder;
1391 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1392 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1393 int32_t width, height;
1394 if (msg->findInt32("width", &width)
1395 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001396 ColorAspects aspects;
1397 getColorAspectsFromFormat(msg, aspects);
1398 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001399 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001400 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1401 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001402 }
1403 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1404 ALOGD("setting dataspace to %x", dataSpace);
1405 }
1406
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001407 int32_t subscribeToAllVendorParams;
1408 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1409 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1410 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1411 }
1412 }
1413
Pawin Vongmasa36653902018-11-15 00:10:25 -08001414 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001415 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1416 // the behavior here.
1417 sp<AMessage> sdkParams = msg;
1418 int32_t videoBitrate;
1419 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1420 sdkParams = msg->dup();
1421 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1422 }
ted.sun765db4d2020-06-23 14:03:41 +08001423 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001424 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001425 if (err != OK) {
1426 ALOGW("failed to convert configuration to c2 params");
1427 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001428
1429 int32_t maxBframes = 0;
1430 if ((config->mDomain & Config::IS_ENCODER)
1431 && (config->mDomain & Config::IS_VIDEO)
1432 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1433 && maxBframes > 0) {
1434 std::unique_ptr<C2StreamGopTuning::output> gop =
1435 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1436 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1437 gop->m.values[1] = {
1438 C2Config::picture_type_t(P_FRAME | B_FRAME),
1439 uint32_t(maxBframes)
1440 };
1441 configUpdate.push_back(std::move(gop));
1442 }
1443
Ray Essicka0ae6972021-03-10 19:40:01 -08001444 if ((config->mDomain & Config::IS_ENCODER)
1445 && (config->mDomain & Config::IS_VIDEO)) {
1446 // we may not use all 3 of these entries
1447 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1448 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1449 0u /* stream */);
1450
1451 int ix = 0;
1452
1453 int32_t iMax = INT32_MAX;
1454 int32_t iMin = INT32_MIN;
1455 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1456 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1457 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1458 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1459 }
1460
1461 int32_t pMax = INT32_MAX;
1462 int32_t pMin = INT32_MIN;
1463 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1464 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1465 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1466 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1467 }
1468
1469 int32_t bMax = INT32_MAX;
1470 int32_t bMin = INT32_MIN;
1471 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1472 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1473 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1474 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1475 }
1476
1477 // adjust to reflect actual use.
1478 qp->setFlexCount(ix);
1479
1480 configUpdate.push_back(std::move(qp));
1481 }
1482
Wonsik Kima1335e12021-04-22 16:28:29 -07001483 int32_t background = 0;
1484 if ((config->mDomain & Config::IS_VIDEO)
1485 && msg->findInt32("android._background-mode", &background)
1486 && background) {
1487 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1488 if (config->mISConfig) {
1489 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1490 }
1491 }
1492
Pawin Vongmasa36653902018-11-15 00:10:25 -08001493 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1494 if (err != OK) {
1495 ALOGW("failed to configure c2 params");
1496 return err;
1497 }
1498
1499 std::vector<std::unique_ptr<C2Param>> params;
1500 C2StreamUsageTuning::input usage(0u, 0u);
1501 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001502 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001503
Wonsik Kim3baecda2021-02-07 22:19:56 -08001504 C2Param::Index colorAspectsRequestIndex =
1505 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001506 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001507 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001508 };
Chaejung Lim86c22dc2021-12-23 00:41:05 -08001509 int32_t colorTransferRequest = 0;
1510 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1511 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1512 colorTransferRequest = 0;
1513 }
1514 c2_status_t c2err = C2_OK;
1515 if (colorTransferRequest != 0) {
1516 c2err = comp->query(
1517 { &usage, &maxInputSize, &prepend },
1518 indices,
1519 C2_DONT_BLOCK,
1520 &params);
1521 } else {
1522 c2err = comp->query(
1523 { &usage, &maxInputSize, &prepend },
1524 {},
1525 C2_DONT_BLOCK,
1526 &params);
1527 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001528 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1529 ALOGE("Failed to query component interface: %d", c2err);
1530 return UNKNOWN_ERROR;
1531 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001532 if (usage) {
1533 if (usage.value & C2MemoryUsage::CPU_READ) {
1534 config->mInputFormat->setInt32("using-sw-read-often", true);
1535 }
1536 if (config->mISConfig) {
1537 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1538 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1539 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001540 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001541 }
1542
1543 // NOTE: we don't blindly use client specified input size if specified as clients
1544 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1545 // client specified size is only used to ask for bigger buffers than component suggested
1546 // size.
1547 int32_t clientInputSize = 0;
1548 bool clientSpecifiedInputSize =
1549 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1550 // TEMP: enforce minimum buffer size of 1MB for video decoders
1551 // and 16K / 4K for audio encoders/decoders
1552 if (maxInputSize.value == 0) {
1553 if (config->mDomain & Config::IS_AUDIO) {
1554 maxInputSize.value = encoder ? 16384 : 4096;
1555 } else if (!encoder) {
1556 maxInputSize.value = 1048576u;
1557 }
1558 }
1559
1560 // verify that CSD fits into this size (if defined)
1561 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1562 sp<ABuffer> csd;
1563 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1564 if (csd && csd->size() > maxInputSize.value) {
1565 maxInputSize.value = csd->size();
1566 }
1567 }
1568 }
1569
1570 // TODO: do this based on component requiring linear allocator for input
1571 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1572 if (clientSpecifiedInputSize) {
1573 // Warn that we're overriding client's max input size if necessary.
1574 if ((uint32_t)clientInputSize < maxInputSize.value) {
1575 ALOGD("client requested max input size %d, which is smaller than "
1576 "what component recommended (%u); overriding with component "
1577 "recommendation.", clientInputSize, maxInputSize.value);
1578 ALOGW("This behavior is subject to change. It is recommended that "
1579 "app developers double check whether the requested "
1580 "max input size is in reasonable range.");
1581 } else {
1582 maxInputSize.value = clientInputSize;
1583 }
1584 }
1585 // Pass max input size on input format to the buffer channel (if supplied by the
1586 // component or by a default)
1587 if (maxInputSize.value) {
1588 config->mInputFormat->setInt32(
1589 KEY_MAX_INPUT_SIZE,
1590 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1591 }
1592 }
1593
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001594 int32_t clientPrepend;
1595 if ((config->mDomain & Config::IS_VIDEO)
1596 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001597 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001598 && clientPrepend
1599 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001600 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001601 return BAD_VALUE;
1602 }
1603
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001604 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001605 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1606 // propagate HDR static info to output format for both encoders and decoders
1607 // if component supports this info, we will update from component, but only the raw port,
1608 // so don't propagate if component already filled it in.
1609 sp<ABuffer> hdrInfo;
1610 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1611 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1612 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1613 }
1614
1615 // Set desired color format from configuration parameter
1616 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001617 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1618 format = defaultColorFormat;
1619 }
1620 if (config->mDomain & Config::IS_ENCODER) {
1621 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001622 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1623 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001624 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001625 } else {
1626 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001627 }
1628 }
1629
1630 // propagate encoder delay and padding to output format
1631 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1632 int delay = 0;
1633 if (msg->findInt32("encoder-delay", &delay)) {
1634 config->mOutputFormat->setInt32("encoder-delay", delay);
1635 }
1636 int padding = 0;
1637 if (msg->findInt32("encoder-padding", &padding)) {
1638 config->mOutputFormat->setInt32("encoder-padding", padding);
1639 }
1640 }
1641
Pawin Vongmasa36653902018-11-15 00:10:25 -08001642 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001643 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001644 int32_t mask;
1645 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1646 if (config->mDomain & Config::IS_ENCODER) {
1647 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1648 } else {
1649 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1650 }
1651 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001652
1653 // set PCM encoding
1654 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1655 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1656 if (encoder) {
1657 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1658 } else {
1659 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1660 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001661 }
1662
Wonsik Kim3baecda2021-02-07 22:19:56 -08001663 std::unique_ptr<C2Param> colorTransferRequestParam;
1664 for (std::unique_ptr<C2Param> &param : params) {
1665 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1666 ALOGI("found color transfer request param");
1667 colorTransferRequestParam = std::move(param);
1668 }
1669 }
Wonsik Kim3baecda2021-02-07 22:19:56 -08001670
1671 if (colorTransferRequest != 0) {
1672 if (colorTransferRequestParam && *colorTransferRequestParam) {
1673 C2StreamColorAspectsInfo::output *info =
1674 static_cast<C2StreamColorAspectsInfo::output *>(
1675 colorTransferRequestParam.get());
1676 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1677 colorTransferRequest = 0;
1678 }
1679 } else {
1680 colorTransferRequest = 0;
1681 }
1682 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1683 }
1684
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001685 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1686 // Need to get stride/vstride
1687 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1688 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1689 // TODO: retrieve these values without allocating a buffer.
1690 // Currently allocating a buffer is necessary to retrieve the layout.
1691 int64_t blockUsage =
1692 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1693 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
Harish Mahendrakarf6b3e5e2024-03-21 21:04:28 +00001694 align(width, 2), align(height, 2), componentColorFormat, blockUsage,
1695 {comp->getName()});
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001696 sp<GraphicBlockBuffer> buffer;
1697 if (block) {
1698 buffer = GraphicBlockBuffer::Allocate(
1699 config->mInputFormat,
1700 block,
1701 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1702 } else {
1703 ALOGD("Failed to allocate a graphic block "
1704 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1705 width, height, pixelFormat, (long long)blockUsage);
1706 // This means that byte buffer mode is not supported in this configuration
1707 // anyway. Skip setting stride/vstride to input format.
1708 }
1709 if (buffer) {
1710 sp<ABuffer> imageData = buffer->getImageData();
1711 MediaImage2 *img = nullptr;
1712 if (imageData && imageData->data()
1713 && imageData->size() >= sizeof(MediaImage2)) {
1714 img = (MediaImage2*)imageData->data();
1715 }
1716 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1717 int32_t stride = img->mPlane[0].mRowInc;
1718 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1719 if (img->mNumPlanes > 1 && stride > 0) {
1720 int64_t offsetDelta =
1721 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1722 if (offsetDelta % stride == 0) {
1723 int32_t vstride = int32_t(offsetDelta / stride);
1724 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1725 } else {
1726 ALOGD("Cannot report accurate slice height: "
1727 "offsetDelta = %lld stride = %d",
1728 (long long)offsetDelta, stride);
1729 }
1730 }
1731 }
1732 }
1733 }
1734 }
1735
Wonsik Kimec585c32021-10-01 01:11:00 -07001736 if (config->mTunneled) {
1737 config->mOutputFormat->setInt32("android._tunneled", 1);
1738 }
1739
Yushin Cho91873b52021-12-21 04:08:35 -08001740 // Convert an encoding statistics level to corresponding encoding statistics
1741 // kinds
1742 int32_t encodingStatisticsLevel = VIDEO_ENCODING_STATISTICS_LEVEL_NONE;
1743 if ((config->mDomain & Config::IS_ENCODER)
1744 && (config->mDomain & Config::IS_VIDEO)
1745 && msg->findInt32(KEY_VIDEO_ENCODING_STATISTICS_LEVEL, &encodingStatisticsLevel)) {
1746 // Higher level include all the enc stats belong to lower level.
1747 switch (encodingStatisticsLevel) {
1748 // case VIDEO_ENCODING_STATISTICS_LEVEL_2: // reserved for the future level 2
1749 // with more enc stat kinds
1750 // Future extended encoding statistics for the level 2 should be added here
1751 case VIDEO_ENCODING_STATISTICS_LEVEL_1:
Wonsik Kimeebab652022-06-02 13:01:55 -07001752 config->subscribeToConfigUpdate(
1753 comp,
1754 {
1755 C2AndroidStreamAverageBlockQuantizationInfo::output::PARAM_TYPE,
1756 C2StreamPictureTypeInfo::output::PARAM_TYPE,
1757 });
Yushin Cho91873b52021-12-21 04:08:35 -08001758 break;
1759 case VIDEO_ENCODING_STATISTICS_LEVEL_NONE:
1760 break;
1761 }
1762 }
1763 ALOGD("encoding statistics level = %d", encodingStatisticsLevel);
1764
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001765 ALOGD("setup formats input: %s",
1766 config->mInputFormat->debugString().c_str());
1767 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001768 config->mOutputFormat->debugString().c_str());
1769 return OK;
1770 };
1771 if (tryAndReportOnError(doConfig) != OK) {
1772 return;
1773 }
1774
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001775 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1776 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001777
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001778 config->queryConfiguration(comp);
1779
Songyue Han1e6769b2023-08-30 18:09:27 +00001780 mMetrics = new AMessage;
1781 mChannel->resetBuffersPixelFormat((config->mDomain & Config::IS_ENCODER) ? true : false);
1782
Pawin Vongmasa36653902018-11-15 00:10:25 -08001783 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1784}
1785
1786void CCodec::initiateCreateInputSurface() {
1787 status_t err = [this] {
1788 Mutexed<State>::Locked state(mState);
1789 if (state->get() != ALLOCATED) {
1790 return UNKNOWN_ERROR;
1791 }
1792 // TODO: read it from intf() properly.
1793 if (state->comp->getName().find("encoder") == std::string::npos) {
1794 return INVALID_OPERATION;
1795 }
1796 return OK;
1797 }();
1798 if (err != OK) {
1799 mCallback->onInputSurfaceCreationFailed(err);
1800 return;
1801 }
1802
1803 (new AMessage(kWhatCreateInputSurface, this))->post();
1804}
1805
Lajos Molnar47118272019-01-31 16:28:04 -08001806sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1807 using namespace android::hardware::media::omx::V1_0;
1808 using namespace android::hardware::media::omx::V1_0::utils;
1809 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1810 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1811 android::sp<IOmx> omx = IOmx::getService();
Sungtak Lee47dcb482022-04-15 10:47:08 -07001812 if (omx == nullptr) {
1813 return nullptr;
1814 }
Lajos Molnar47118272019-01-31 16:28:04 -08001815 typedef android::hardware::graphics::bufferqueue::V1_0::
1816 IGraphicBufferProducer HGraphicBufferProducer;
1817 typedef android::hardware::media::omx::V1_0::
1818 IGraphicBufferSource HGraphicBufferSource;
1819 OmxStatus s;
1820 android::sp<HGraphicBufferProducer> gbp;
1821 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001822
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001823 using ::android::hardware::Return;
1824 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001825 [&s, &gbp, &gbs](
1826 OmxStatus status,
1827 const android::sp<HGraphicBufferProducer>& producer,
1828 const android::sp<HGraphicBufferSource>& source) {
1829 s = status;
1830 gbp = producer;
1831 gbs = source;
1832 });
1833 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001834 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001835 }
1836
1837 return nullptr;
1838}
1839
1840sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1841 sp<PersistentSurface> surface(CreateInputSurface());
1842
1843 if (surface == nullptr) {
1844 surface = CreateOmxInputSurface();
1845 }
1846
1847 return surface;
1848}
1849
Pawin Vongmasa36653902018-11-15 00:10:25 -08001850void CCodec::createInputSurface() {
1851 status_t err;
1852 sp<IGraphicBufferProducer> bufferProducer;
1853
Pawin Vongmasa36653902018-11-15 00:10:25 -08001854 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001855 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001856 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001857 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1858 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001859 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001860 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001861 }
1862
Lajos Molnar47118272019-01-31 16:28:04 -08001863 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Sungtak Lee92bca442024-03-12 09:10:31 +00001864 if (persistentSurface->isTargetAidl()) {
1865 ::ndk::SpAIBinder aidlTarget = persistentSurface->getAidlTarget();
1866 std::shared_ptr<AGraphicBufferSource> gbs = AGraphicBufferSource::fromBinder(aidlTarget);
1867 if (gbs) {
1868 int32_t width = 0;
1869 (void)outputFormat->findInt32("width", &width);
1870 int32_t height = 0;
1871 (void)outputFormat->findInt32("height", &height);
1872 err = setupInputSurface(std::make_shared<AGraphicBufferSourceWrapper>(
1873 gbs, width, height, usage));
1874 bufferProducer = persistentSurface->getBufferProducer();
1875 } else {
1876 ALOGE("Corrupted input surface(aidl)");
1877 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1878 return;
1879 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001880 } else {
Sungtak Lee92bca442024-03-12 09:10:31 +00001881 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1882 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1883 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1884
1885 if (hidlInputSurface) {
1886 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1887 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
1888 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1889 inputSurface));
1890 bufferProducer = inputSurface->getGraphicBufferProducer();
1891 } else if (gbs) {
1892 int32_t width = 0;
1893 (void)outputFormat->findInt32("width", &width);
1894 int32_t height = 0;
1895 (void)outputFormat->findInt32("height", &height);
1896 err = setupInputSurface(std::make_shared<HGraphicBufferSourceWrapper>(
1897 gbs, width, height, usage));
1898 bufferProducer = persistentSurface->getBufferProducer();
1899 } else {
1900 ALOGE("Corrupted input surface");
1901 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1902 return;
1903 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001904 }
1905
1906 if (err != OK) {
1907 ALOGE("Failed to set up input surface: %d", err);
1908 mCallback->onInputSurfaceCreationFailed(err);
1909 return;
1910 }
1911
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001912 // Formats can change after setupInputSurface
1913 sp<AMessage> inputFormat;
1914 {
1915 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1916 const std::unique_ptr<Config> &config = *configLocked;
1917 inputFormat = config->mInputFormat;
1918 outputFormat = config->mOutputFormat;
1919 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001920 mCallback->onInputSurfaceCreated(
1921 inputFormat,
1922 outputFormat,
1923 new BufferProducerWrapper(bufferProducer));
1924}
1925
1926status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001927 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1928 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001929 config->mUsingSurface = true;
1930
1931 // we are now using surface - apply default color aspects to input format - as well as
1932 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001933 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001934
1935 // configure dataspace
1936 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
Wonsik Kim66b19552021-08-02 16:07:49 -07001937
1938 // The output format contains app-configured color aspects, and the input format
1939 // has the default color aspects. Use the default for the unspecified params.
1940 ColorAspects inputColorAspects, colorAspects;
1941 getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
1942 getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
1943 if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
1944 colorAspects.mRange = inputColorAspects.mRange;
1945 }
1946 if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
1947 colorAspects.mPrimaries = inputColorAspects.mPrimaries;
1948 }
1949 if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
1950 colorAspects.mTransfer = inputColorAspects.mTransfer;
1951 }
1952 if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
1953 colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
1954 }
1955 android_dataspace dataSpace = getDataSpaceForColorAspects(
1956 colorAspects, /* mayExtend = */ false);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001957 surface->setDataSpace(dataSpace);
Wonsik Kim66b19552021-08-02 16:07:49 -07001958 setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
1959 config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
1960
1961 ALOGD("input format %s to %s",
1962 inputFormatChanged ? "changed" : "unchanged",
1963 config->mInputFormat->debugString().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001964
1965 status_t err = mChannel->setInputSurface(surface);
1966 if (err != OK) {
1967 // undo input format update
1968 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001969 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001970 return err;
1971 }
1972 config->mInputSurface = surface;
1973
1974 if (config->mISConfig) {
1975 surface->configure(*config->mISConfig);
1976 } else {
1977 ALOGD("ISConfig: no configuration");
1978 }
1979
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001980 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001981}
1982
1983void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1984 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1985 msg->setObject("surface", surface);
1986 msg->post();
1987}
1988
1989void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001990 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001991 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001992 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001993 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1994 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001995 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001996 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001997 }
Sungtak Lee92bca442024-03-12 09:10:31 +00001998 if (surface->isTargetAidl()) {
1999 ::ndk::SpAIBinder aidlTarget = surface->getAidlTarget();
2000 std::shared_ptr<AGraphicBufferSource> gbs = AGraphicBufferSource::fromBinder(aidlTarget);
2001 if (gbs) {
2002 int32_t width = 0;
2003 (void)outputFormat->findInt32("width", &width);
2004 int32_t height = 0;
2005 (void)outputFormat->findInt32("height", &height);
2006
2007 status_t err = setupInputSurface(std::make_shared<AGraphicBufferSourceWrapper>(
2008 gbs, width, height, usage));
2009 if (err != OK) {
2010 ALOGE("Failed to set up input surface(aidl): %d", err);
2011 mCallback->onInputSurfaceDeclined(err);
2012 return;
2013 }
2014 } else {
2015 ALOGE("Failed to set input surface(aidl): Corrupted surface.");
2016 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002017 return;
2018 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002019 } else {
Sungtak Lee92bca442024-03-12 09:10:31 +00002020 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
2021 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
2022 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
2023 if (inputSurface) {
2024 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
2025 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
2026 if (err != OK) {
2027 ALOGE("Failed to set up input surface: %d", err);
2028 mCallback->onInputSurfaceDeclined(err);
2029 return;
2030 }
2031 } else if (gbs) {
2032 int32_t width = 0;
2033 (void)outputFormat->findInt32("width", &width);
2034 int32_t height = 0;
2035 (void)outputFormat->findInt32("height", &height);
2036 status_t err = setupInputSurface(std::make_shared<HGraphicBufferSourceWrapper>(
2037 gbs, width, height, usage));
2038 if (err != OK) {
2039 ALOGE("Failed to set up input surface: %d", err);
2040 mCallback->onInputSurfaceDeclined(err);
2041 return;
2042 }
2043 } else {
2044 ALOGE("Failed to set input surface: Corrupted surface.");
2045 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
2046 return;
2047 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002048 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07002049 // Formats can change after setupInputSurface
2050 sp<AMessage> inputFormat;
2051 {
2052 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2053 const std::unique_ptr<Config> &config = *configLocked;
2054 inputFormat = config->mInputFormat;
2055 outputFormat = config->mOutputFormat;
2056 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002057 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
2058}
2059
2060void CCodec::initiateStart() {
2061 auto setStarting = [this] {
2062 Mutexed<State>::Locked state(mState);
2063 if (state->get() != ALLOCATED) {
2064 return UNKNOWN_ERROR;
2065 }
2066 state->set(STARTING);
2067 return OK;
2068 };
2069 if (tryAndReportOnError(setStarting) != OK) {
2070 return;
2071 }
2072
2073 (new AMessage(kWhatStart, this))->post();
2074}
2075
2076void CCodec::start() {
2077 std::shared_ptr<Codec2Client::Component> comp;
2078 auto checkStarting = [this, &comp] {
2079 Mutexed<State>::Locked state(mState);
2080 if (state->get() != STARTING) {
2081 return UNKNOWN_ERROR;
2082 }
2083 comp = state->comp;
2084 return OK;
2085 };
2086 if (tryAndReportOnError(checkStarting) != OK) {
2087 return;
2088 }
2089
2090 c2_status_t err = comp->start();
2091 if (err != C2_OK) {
2092 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
2093 ACTION_CODE_FATAL);
2094 return;
2095 }
Wonsik Kimd55ed3b2023-06-22 14:42:17 -07002096
2097 // clear the deadline after the component starts
2098 setDeadline(TimePoint::max(), 0ms, "none");
2099
Pawin Vongmasa36653902018-11-15 00:10:25 -08002100 sp<AMessage> inputFormat;
2101 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002102 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002103 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002104 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002105 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2106 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002107 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08002108 // start triggers format dup
2109 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002110 if (config->mInputSurface) {
2111 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08002112 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002113 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002114 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002115 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002116 if (err2 != OK) {
2117 mCallback->onError(err2, ACTION_CODE_FATAL);
2118 return;
2119 }
Arun Johnson106fe7a2023-04-26 17:49:43 +00002120
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002121 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002122 if (err2 != OK) {
2123 mCallback->onError(err2, ACTION_CODE_FATAL);
2124 return;
2125 }
2126
2127 auto setRunning = [this] {
2128 Mutexed<State>::Locked state(mState);
2129 if (state->get() != STARTING) {
2130 return UNKNOWN_ERROR;
2131 }
2132 state->set(RUNNING);
2133 return OK;
2134 };
2135 if (tryAndReportOnError(setRunning) != OK) {
2136 return;
2137 }
Arun Johnson5997bb02022-04-01 19:35:44 +00002138
Wonsik Kim34b28b42022-05-20 15:49:32 -07002139 // preparation of input buffers may not succeed due to the lack of
2140 // memory; returning correct error code (NO_MEMORY) as an error allows
2141 // MediaCodec to try reclaim and restart codec gracefully.
2142 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
2143 err2 = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
2144 if (err2 != OK) {
2145 ALOGE("Initial preparation for Input Buffers failed");
2146 mCallback->onError(err2, ACTION_CODE_FATAL);
2147 return;
2148 }
2149
Pawin Vongmasa36653902018-11-15 00:10:25 -08002150 mCallback->onStartCompleted();
2151
Wonsik Kim34b28b42022-05-20 15:49:32 -07002152 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002153}
2154
2155void CCodec::initiateShutdown(bool keepComponentAllocated) {
2156 if (keepComponentAllocated) {
2157 initiateStop();
2158 } else {
2159 initiateRelease();
2160 }
2161}
2162
2163void CCodec::initiateStop() {
2164 {
2165 Mutexed<State>::Locked state(mState);
2166 if (state->get() == ALLOCATED
2167 || state->get() == RELEASED
2168 || state->get() == STOPPING
2169 || state->get() == RELEASING) {
2170 // We're already stopped, released, or doing it right now.
2171 state.unlock();
2172 mCallback->onStopCompleted();
2173 state.lock();
2174 return;
2175 }
2176 state->set(STOPPING);
2177 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002178 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00002179 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
2180 sp<AMessage> stopMessage(new AMessage(kWhatStop, this));
2181 stopMessage->setInt32("pushBlankBuffer", pushBlankBuffer);
2182 stopMessage->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002183}
2184
Sungtak Lee99144332023-01-26 11:03:14 +00002185void CCodec::stop(bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002186 std::shared_ptr<Codec2Client::Component> comp;
2187 {
2188 Mutexed<State>::Locked state(mState);
2189 if (state->get() == RELEASING) {
2190 state.unlock();
2191 // We're already stopped or release is in progress.
2192 mCallback->onStopCompleted();
2193 state.lock();
2194 return;
2195 } else if (state->get() != STOPPING) {
2196 state.unlock();
2197 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2198 state.lock();
2199 return;
2200 }
2201 comp = state->comp;
2202 }
Sungtak Leec0c05962023-10-25 08:14:13 +00002203
2204 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->stop().
2205 // But in the case some HAL implementations hang forever on comp->stop().
2206 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
2207 // completing stop()).
2208 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
2209 // prior to comp->stop().
2210 // See also b/300350761.
Sungtak Lee99144332023-01-26 11:03:14 +00002211 mChannel->stopUseOutputSurface(pushBlankBuffer);
Sungtak Leec0c05962023-10-25 08:14:13 +00002212 status_t err = comp->stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002213 if (err != C2_OK) {
2214 // TODO: convert err into status_t
2215 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2216 }
2217
2218 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002219 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2220 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002221 if (config->mInputSurface) {
2222 config->mInputSurface->disconnect();
2223 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08002224 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002225 }
2226 }
2227 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002228 Mutexed<State>::Locked state(mState);
2229 if (state->get() == STOPPING) {
2230 state->set(ALLOCATED);
2231 }
2232 }
2233 mCallback->onStopCompleted();
2234}
2235
2236void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002237 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002238 {
2239 Mutexed<State>::Locked state(mState);
2240 if (state->get() == RELEASED || state->get() == RELEASING) {
2241 // We're already released or doing it right now.
2242 if (sendCallback) {
2243 state.unlock();
2244 mCallback->onReleaseCompleted();
2245 state.lock();
2246 }
2247 return;
2248 }
2249 if (state->get() == ALLOCATING) {
2250 state->set(RELEASING);
2251 // With the altered state allocate() would fail and clean up.
2252 if (sendCallback) {
2253 state.unlock();
2254 mCallback->onReleaseCompleted();
2255 state.lock();
2256 }
2257 return;
2258 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002259 if (state->get() == STARTING
2260 || state->get() == RUNNING
2261 || state->get() == STOPPING) {
2262 // Input surface may have been started, so clean up is needed.
2263 clearInputSurfaceIfNeeded = true;
2264 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002265 state->set(RELEASING);
2266 }
2267
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002268 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002269 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2270 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002271 if (config->mInputSurface) {
2272 config->mInputSurface->disconnect();
2273 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08002274 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002275 }
2276 }
2277
Wonsik Kim936a89c2020-05-08 16:07:50 -07002278 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00002279 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002280 // thiz holds strong ref to this while the thread is running.
2281 sp<CCodec> thiz(this);
Sungtak Lee99144332023-01-26 11:03:14 +00002282 std::thread([thiz, sendCallback, pushBlankBuffer]
2283 { thiz->release(sendCallback, pushBlankBuffer); }).detach();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002284}
2285
Sungtak Lee99144332023-01-26 11:03:14 +00002286void CCodec::release(bool sendCallback, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002287 std::shared_ptr<Codec2Client::Component> comp;
2288 {
2289 Mutexed<State>::Locked state(mState);
2290 if (state->get() == RELEASED) {
2291 if (sendCallback) {
2292 state.unlock();
2293 mCallback->onReleaseCompleted();
2294 state.lock();
2295 }
2296 return;
2297 }
2298 comp = state->comp;
2299 }
Sungtak Leec0c05962023-10-25 08:14:13 +00002300 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->release().
2301 // But in the case some HAL implementations hang forever on comp->release().
2302 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
2303 // completing release()).
2304 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
2305 // prior to comp->release().
2306 // See also b/300350761.
Sungtak Lee99144332023-01-26 11:03:14 +00002307 mChannel->stopUseOutputSurface(pushBlankBuffer);
Sungtak Leec0c05962023-10-25 08:14:13 +00002308 comp->release();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002309
2310 {
2311 Mutexed<State>::Locked state(mState);
2312 state->set(RELEASED);
2313 state->comp.reset();
2314 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002315 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002316 if (sendCallback) {
2317 mCallback->onReleaseCompleted();
2318 }
2319}
2320
Sungtak Lee214ce612023-11-01 10:01:13 +00002321status_t CCodec::setSurface(const sp<Surface> &surface, uint32_t generation) {
Sungtak Lee99144332023-01-26 11:03:14 +00002322 bool pushBlankBuffer = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002323 {
2324 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2325 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002326 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
2327 status_t err = OK;
2328
Wonsik Kim75e22f42021-04-14 23:34:51 -07002329 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002330 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07002331 nativeWindow.get(),
2332 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
2333 if (err != OK) {
2334 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
2335 nativeWindow.get(), config->mSidebandHandle->handle(), err);
2336 return err;
2337 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002338 } else {
2339 // Explicitly reset the sideband handle of the window for
2340 // non-tunneled video in case the window was previously used
2341 // for a tunneled video playback.
2342 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
2343 if (err != OK) {
2344 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
2345 return err;
2346 }
ted.sun765db4d2020-06-23 14:03:41 +08002347 }
Sungtak Lee99144332023-01-26 11:03:14 +00002348 pushBlankBuffer = config->mPushBlankBuffersOnStop;
ted.sun765db4d2020-06-23 14:03:41 +08002349 }
Sungtak Lee214ce612023-11-01 10:01:13 +00002350 return mChannel->setSurface(surface, generation, pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002351}
2352
2353void CCodec::signalFlush() {
2354 status_t err = [this] {
2355 Mutexed<State>::Locked state(mState);
2356 if (state->get() == FLUSHED) {
2357 return ALREADY_EXISTS;
2358 }
2359 if (state->get() != RUNNING) {
2360 return UNKNOWN_ERROR;
2361 }
2362 state->set(FLUSHING);
2363 return OK;
2364 }();
2365 switch (err) {
2366 case ALREADY_EXISTS:
2367 mCallback->onFlushCompleted();
2368 return;
2369 case OK:
2370 break;
2371 default:
2372 mCallback->onError(err, ACTION_CODE_FATAL);
2373 return;
2374 }
2375
2376 mChannel->stop();
2377 (new AMessage(kWhatFlush, this))->post();
2378}
2379
2380void CCodec::flush() {
2381 std::shared_ptr<Codec2Client::Component> comp;
2382 auto checkFlushing = [this, &comp] {
2383 Mutexed<State>::Locked state(mState);
2384 if (state->get() != FLUSHING) {
2385 return UNKNOWN_ERROR;
2386 }
2387 comp = state->comp;
2388 return OK;
2389 };
2390 if (tryAndReportOnError(checkFlushing) != OK) {
2391 return;
2392 }
2393
2394 std::list<std::unique_ptr<C2Work>> flushedWork;
2395 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2396 {
2397 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2398 flushedWork.splice(flushedWork.end(), *queue);
2399 }
2400 if (err != C2_OK) {
2401 // TODO: convert err into status_t
2402 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2403 }
2404
2405 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002406
2407 {
2408 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002409 if (state->get() == FLUSHING) {
2410 state->set(FLUSHED);
2411 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002412 }
2413 mCallback->onFlushCompleted();
2414}
2415
2416void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002417 std::shared_ptr<Codec2Client::Component> comp;
2418 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002419 Mutexed<State>::Locked state(mState);
2420 if (state->get() != FLUSHED) {
2421 return UNKNOWN_ERROR;
2422 }
2423 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002424 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002425 return OK;
2426 };
2427 if (tryAndReportOnError(setResuming) != OK) {
2428 return;
2429 }
2430
Wonsik Kime75a5da2020-02-14 17:29:03 -08002431 {
2432 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2433 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002434 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002435 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002436 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002437 }
2438
Arun Johnson106fe7a2023-04-26 17:49:43 +00002439 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
Arun Johnson326166e2023-07-28 19:11:52 +00002440 status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers, true);
Arun Johnson106fe7a2023-04-26 17:49:43 +00002441 if (err != OK) {
2442 if (err == NO_MEMORY) {
2443 // NO_MEMORY happens here when all the buffers are still
2444 // with the codec. That is not an error as it is momentarily
2445 // and the buffers are send to the client as soon as the codec
2446 // releases them
2447 ALOGI("Resuming with all input buffers still with codec");
2448 } else {
2449 ALOGE("Resume request for Input Buffers failed");
2450 mCallback->onError(err, ACTION_CODE_FATAL);
2451 return;
2452 }
2453 }
2454
2455 // channel start should be called after prepareInitialBuffers
2456 // Calling before can cause a failure during prepare when
2457 // buffers are sent to the client before preparation from onWorkDone
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002458 (void)mChannel->start(nullptr, nullptr, [&]{
2459 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2460 const std::unique_ptr<Config> &config = *configLocked;
2461 return config->mBuffersBoundToCodec;
2462 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002463 {
2464 Mutexed<State>::Locked state(mState);
2465 if (state->get() != RESUMING) {
2466 state.unlock();
2467 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2468 state.lock();
2469 return;
2470 }
2471 state->set(RUNNING);
2472 }
2473
Wonsik Kim34b28b42022-05-20 15:49:32 -07002474 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002475}
2476
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002477void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002478 std::shared_ptr<Codec2Client::Component> comp;
2479 auto checkState = [this, &comp] {
2480 Mutexed<State>::Locked state(mState);
2481 if (state->get() == RELEASED) {
2482 return INVALID_OPERATION;
2483 }
2484 comp = state->comp;
2485 return OK;
2486 };
2487 if (tryAndReportOnError(checkState) != OK) {
2488 return;
2489 }
2490
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002491 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2492 // the behavior here.
2493 sp<AMessage> params = msg;
2494 int32_t bitrate;
2495 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2496 params = msg->dup();
2497 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2498 }
2499
Houxiang Dai5a97b472021-03-22 17:56:04 +08002500 int32_t syncId = 0;
2501 if (params->findInt32("audio-hw-sync", &syncId)
2502 || params->findInt32("hw-av-sync-id", &syncId)) {
2503 configureTunneledVideoPlayback(comp, nullptr, params);
2504 }
2505
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002506 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2507 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002508
2509 /**
2510 * Handle input surface parameters
2511 */
2512 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002513 && (config->mDomain & Config::IS_ENCODER)
2514 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002515 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002516
2517 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2518 config->mISConfig->mStopped = false;
2519 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2520 config->mISConfig->mStopped = true;
2521 }
2522
2523 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002524 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002525 config->mISConfig->mSuspended = value;
2526 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002527 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002528 }
2529
2530 (void)config->mInputSurface->configure(*config->mISConfig);
2531 if (config->mISConfig->mStopped) {
2532 config->mInputFormat->setInt64(
2533 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2534 }
2535 }
2536
2537 std::vector<std::unique_ptr<C2Param>> configUpdate;
2538 (void)config->getConfigUpdateFromSdkParams(
2539 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2540 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2541 // Parameter synchronization is not defined when using input surface. For now, route
2542 // these directly to the component.
2543 if (config->mInputSurface == nullptr
2544 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2545 || comp->getName().find("c2.android.") == 0)) {
2546 mChannel->setParameters(configUpdate);
2547 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002548 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002549 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002550 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002551 }
2552}
2553
2554void CCodec::signalEndOfInputStream() {
2555 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2556}
2557
2558void CCodec::signalRequestIDRFrame() {
2559 std::shared_ptr<Codec2Client::Component> comp;
2560 {
2561 Mutexed<State>::Locked state(mState);
2562 if (state->get() == RELEASED) {
2563 ALOGD("no IDR request sent since component is released");
2564 return;
2565 }
2566 comp = state->comp;
2567 }
2568 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002569 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2570 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002571 std::vector<std::unique_ptr<C2Param>> params;
2572 params.push_back(
2573 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2574 config->setParameters(comp, params, C2_MAY_BLOCK);
2575}
2576
Wonsik Kim874ad382021-03-12 09:59:36 -08002577status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2578 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2579 const std::unique_ptr<Config> &config = *configLocked;
2580 return config->querySupportedParameters(names);
2581}
2582
2583status_t CCodec::describeParameter(
2584 const std::string &name, CodecParameterDescriptor *desc) {
2585 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2586 const std::unique_ptr<Config> &config = *configLocked;
2587 return config->describe(name, desc);
2588}
2589
2590status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2591 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2592 if (!comp) {
2593 return INVALID_OPERATION;
2594 }
2595 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2596 const std::unique_ptr<Config> &config = *configLocked;
2597 return config->subscribeToVendorConfigUpdate(comp, names);
2598}
2599
2600status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2601 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2602 if (!comp) {
2603 return INVALID_OPERATION;
2604 }
2605 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2606 const std::unique_ptr<Config> &config = *configLocked;
2607 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2608}
2609
Wonsik Kimab34ed62019-01-31 15:28:46 -08002610void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002611 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002612 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002613 bool shouldPost = queue->empty();
Wonsik Kimab34ed62019-01-31 15:28:46 -08002614 queue->splice(queue->end(), workItems);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002615 if (shouldPost) {
2616 (new AMessage(kWhatWorkDone, this))->post();
2617 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002618 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002619}
2620
Wonsik Kimab34ed62019-01-31 15:28:46 -08002621void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2622 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002623 if (arrayIndex == 0) {
2624 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002625 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2626 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002627 if (config->mInputSurface) {
2628 config->mInputSurface->onInputBufferDone(frameIndex);
2629 }
2630 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002631}
2632
2633void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2634 TimePoint now = std::chrono::steady_clock::now();
2635 CCodecWatchdog::getInstance()->watch(this);
2636 switch (msg->what()) {
2637 case kWhatAllocate: {
2638 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002639 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002640 sp<RefBase> obj;
2641 CHECK(msg->findObject("codecInfo", &obj));
2642 allocate((MediaCodecInfo *)obj.get());
2643 break;
2644 }
2645 case kWhatConfigure: {
2646 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002647 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002648 sp<AMessage> format;
2649 CHECK(msg->findMessage("format", &format));
2650 configure(format);
2651 break;
2652 }
2653 case kWhatStart: {
2654 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002655 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002656 start();
2657 break;
2658 }
2659 case kWhatStop: {
2660 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002661 setDeadline(now, 1500ms, "stop");
Sungtak Lee99144332023-01-26 11:03:14 +00002662 int32_t pushBlankBuffer;
2663 if (!msg->findInt32("pushBlankBuffer", &pushBlankBuffer)) {
2664 pushBlankBuffer = 0;
2665 }
2666 stop(static_cast<bool>(pushBlankBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002667 break;
2668 }
2669 case kWhatFlush: {
2670 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002671 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002672 flush();
2673 break;
2674 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002675 case kWhatRelease: {
2676 mChannel->release();
2677 mClient.reset();
2678 mClientListener.reset();
2679 break;
2680 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002681 case kWhatCreateInputSurface: {
2682 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002683 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002684 createInputSurface();
2685 break;
2686 }
2687 case kWhatSetInputSurface: {
2688 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002689 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002690 sp<RefBase> obj;
2691 CHECK(msg->findObject("surface", &obj));
2692 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2693 setInputSurface(surface);
2694 break;
2695 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002696 case kWhatWorkDone: {
2697 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002698 bool shouldPost = false;
2699 {
2700 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2701 if (queue->empty()) {
2702 break;
2703 }
2704 work.swap(queue->front());
2705 queue->pop_front();
2706 shouldPost = !queue->empty();
2707 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002708 if (shouldPost) {
2709 (new AMessage(kWhatWorkDone, this))->post();
2710 }
2711
Pawin Vongmasa36653902018-11-15 00:10:25 -08002712 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002713 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002714 sp<AMessage> outputFormat = nullptr;
2715 {
2716 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2717 const std::unique_ptr<Config> &config = *configLocked;
2718 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2719 config->watch<C2StreamInitDataInfo::output>();
2720 if (!work->worklets.empty()
2721 && (work->worklets.front()->output.flags
2722 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002723
Wonsik Kim75e22f42021-04-14 23:34:51 -07002724 // copy buffer info to config
2725 std::vector<std::unique_ptr<C2Param>> updates;
2726 for (const std::unique_ptr<C2Param> &param
2727 : work->worklets.front()->output.configUpdate) {
2728 updates.push_back(C2Param::Copy(*param));
2729 }
2730 unsigned stream = 0;
2731 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2732 work->worklets.front()->output.buffers;
2733 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2734 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2735 // move all info into output-stream #0 domain
2736 updates.emplace_back(
2737 C2Param::CopyAsStream(*info, true /* output */, stream));
2738 }
2739
2740 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2741 // for now only do the first block
2742 if (!blocks.empty()) {
2743 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2744 // block.crop().left, block.crop().top,
2745 // block.crop().width, block.crop().height,
2746 // block.width(), block.height());
2747 const C2ConstGraphicBlock &block = blocks[0];
2748 updates.emplace_back(new C2StreamCropRectInfo::output(
2749 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002750 }
2751 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002752 }
George Burgess IVc813a592020-02-22 22:54:44 -08002753
Wonsik Kim75e22f42021-04-14 23:34:51 -07002754 sp<AMessage> oldFormat = config->mOutputFormat;
2755 config->updateConfiguration(updates, config->mOutputDomain);
2756 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002757
Wonsik Kim75e22f42021-04-14 23:34:51 -07002758 // copy standard infos to graphic buffers if not already present (otherwise, we
2759 // may overwrite the actual intermediate value with a final value)
2760 stream = 0;
2761 const static C2Param::Index stdGfxInfos[] = {
2762 C2StreamRotationInfo::output::PARAM_TYPE,
2763 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2764 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2765 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Taehwan Kim2d222b82022-05-12 14:19:26 +09002766 C2StreamHdr10PlusInfo::output::PARAM_TYPE, // will be deprecated
2767 C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE,
Wonsik Kim75e22f42021-04-14 23:34:51 -07002768 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2769 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2770 };
2771 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2772 if (buf->data().graphicBlocks().size()) {
2773 for (C2Param::Index ix : stdGfxInfos) {
2774 if (!buf->hasInfo(ix)) {
2775 const C2Param *param =
2776 config->getConfigParameterValue(ix.withStream(stream));
2777 if (param) {
2778 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2779 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2780 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002781 }
2782 }
2783 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002784 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002785 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002786 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002787 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302788 if (work->worklets.empty()
2789 || !work->worklets.back()
2790 || (work->worklets.back()->output.flags
2791 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2792 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2793 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002794 }
2795 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002796 initData = initDataWatcher.update();
2797 AmendOutputFormatWithCodecSpecificData(
2798 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2799 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002800 }
2801 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002802 }
2803 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002804 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Songyue Han1e6769b2023-08-30 18:09:27 +00002805 // log metrics to MediaCodec
2806 if (mMetrics->countEntries() == 0) {
2807 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2808 const std::unique_ptr<Config> &config = *configLocked;
2809 uint32_t pf = PIXEL_FORMAT_UNKNOWN;
2810 if (!config->mInputSurface) {
2811 pf = mChannel->getBuffersPixelFormat(config->mDomain & Config::IS_ENCODER);
Songyue Hanad01f6a2023-08-17 05:45:35 +00002812 } else {
2813 pf = config->mInputSurface->getPixelFormat();
Songyue Han1e6769b2023-08-30 18:09:27 +00002814 }
2815 if (pf != PIXEL_FORMAT_UNKNOWN) {
2816 mMetrics->setInt64(kCodecPixelFormat, pf);
2817 mCallback->onMetricsUpdated(mMetrics);
2818 }
2819 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002820 break;
2821 }
2822 case kWhatWatch: {
2823 // watch message already posted; no-op.
2824 break;
2825 }
2826 default: {
2827 ALOGE("unrecognized message");
2828 break;
2829 }
2830 }
2831 setDeadline(TimePoint::max(), 0ms, "none");
2832}
2833
2834void CCodec::setDeadline(
2835 const TimePoint &now,
2836 const std::chrono::milliseconds &timeout,
2837 const char *name) {
2838 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2839 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2840 deadline->set(now + (timeout * mult), name);
2841}
2842
ted.sun765db4d2020-06-23 14:03:41 +08002843status_t CCodec::configureTunneledVideoPlayback(
2844 std::shared_ptr<Codec2Client::Component> comp,
2845 sp<NativeHandle> *sidebandHandle,
2846 const sp<AMessage> &msg) {
2847 std::vector<std::unique_ptr<C2SettingResult>> failures;
2848
2849 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2850 C2PortTunneledModeTuning::output::AllocUnique(
2851 1,
2852 C2PortTunneledModeTuning::Struct::SIDEBAND,
2853 C2PortTunneledModeTuning::Struct::REALTIME,
2854 0);
2855 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2856 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2857 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2858 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2859 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2860 } else {
2861 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2862 tunneledPlayback->setFlexCount(0);
2863 }
2864 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2865 if (c2err != C2_OK) {
2866 return UNKNOWN_ERROR;
2867 }
2868
Houxiang Dai5a97b472021-03-22 17:56:04 +08002869 if (sidebandHandle == nullptr) {
2870 return OK;
2871 }
2872
ted.sun765db4d2020-06-23 14:03:41 +08002873 std::vector<std::unique_ptr<C2Param>> params;
2874 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2875 if (c2err == C2_OK && params.size() == 1u) {
2876 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2877 C2PortTunnelHandleTuning::output::From(params[0].get());
2878 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2879 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2880 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2881 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2882 memcpy(handle->data, videoTunnelSideband->m.values,
2883 sizeof(int32_t) * videoTunnelSideband->flexCount());
2884 return OK;
2885 } else {
2886 return NO_MEMORY;
2887 }
2888 }
2889 return UNKNOWN_ERROR;
2890}
2891
Pawin Vongmasa36653902018-11-15 00:10:25 -08002892void CCodec::initiateReleaseIfStuck() {
Shrikara B3b87a532022-08-26 14:18:14 +05302893 std::string name;
2894 bool pendingDeadline = false;
2895 {
2896 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2897 if (deadline->get() < std::chrono::steady_clock::now()) {
2898 name = deadline->getName();
2899 }
2900 if (deadline->get() != TimePoint::max()) {
2901 pendingDeadline = true;
2902 }
2903 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002904 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002905 // We're not stuck.
2906 if (pendingDeadline) {
2907 // If we are not stuck yet but still has deadline coming up,
2908 // post watch message to check back later.
2909 (new AMessage(kWhatWatch, this))->post();
2910 }
2911 return;
2912 }
2913
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002914 C2String compName;
2915 {
2916 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002917 if (!state->comp) {
2918 ALOGD("previous call to %s exceeded timeout "
2919 "and the component is already released", name.c_str());
2920 return;
2921 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002922 compName = state->comp->getName();
2923 }
2924 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2925
Pawin Vongmasa36653902018-11-15 00:10:25 -08002926 initiateRelease(false);
2927 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2928}
2929
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002930// static
2931PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002932 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002933 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002934 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002935 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2936 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002937 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002938 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
Sungtak Lee92bca442024-03-12 09:10:31 +00002939 if (Codec2Client::IsAidlSelected()) {
2940 sp<IGraphicBufferProducer> gbp;
2941 sp<AidlGraphicBufferSource> gbs = new AidlGraphicBufferSource();
2942 status_t err = gbs->initCheck();
2943 if (err != OK) {
2944 ALOGE("Failed to create persistent input surface: error %d", err);
2945 return nullptr;
2946 }
2947 ALOGD("aidl based PersistentSurface created");
2948 std::shared_ptr<WAidlGraphicBufferSource> wrapper =
2949 ::ndk::SharedRefBase::make<WAidlGraphicBufferSource>(gbs);
2950
2951 return new PersistentSurface(
2952 gbs->getIGraphicBufferProducer(), wrapper->asBinder());
2953 } else {
2954 sp<IGraphicBufferProducer> gbp;
2955 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2956 status_t err = gbs->initCheck();
2957 if (err != OK) {
2958 ALOGE("Failed to create persistent input surface: error %d", err);
2959 return nullptr;
2960 }
2961 ALOGD("hidl based PersistentSurface created");
2962 return new PersistentSurface(
2963 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002964 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002965 } else {
2966 return nullptr;
2967 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002968 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002969 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002970 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002971 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002972 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002973}
2974
Wonsik Kimffb889a2020-05-28 11:32:25 -07002975class IntfCache {
2976public:
2977 IntfCache() = default;
2978
2979 status_t init(const std::string &name) {
2980 std::shared_ptr<Codec2Client::Interface> intf{
2981 Codec2Client::CreateInterfaceByName(name.c_str())};
2982 if (!intf) {
2983 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2984 mInitStatus = NO_INIT;
2985 return NO_INIT;
2986 }
2987 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2988 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2989 C2ParamField{&sUsage, &sUsage.value}));
2990 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2991 if (err != C2_OK) {
2992 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2993 name.c_str(), err);
2994 mFields[0].status = err;
2995 }
2996 std::vector<std::unique_ptr<C2Param>> params;
2997 err = intf->query(
2998 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09002999 {
3000 C2StreamBufferTypeSetting::input::PARAM_TYPE,
3001 C2PortAllocatorsTuning::input::PARAM_TYPE
3002 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07003003 C2_MAY_BLOCK,
3004 &params);
3005 if (err != C2_OK && err != C2_BAD_INDEX) {
3006 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
3007 name.c_str(), err);
3008 }
3009 while (!params.empty()) {
3010 C2Param *param = params.back().release();
3011 params.pop_back();
3012 if (!param) {
3013 continue;
3014 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09003015 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
3016 mInputStreamFormat.reset(
3017 C2StreamBufferTypeSetting::input::From(param));
3018 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003019 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07003020 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07003021 }
3022 }
3023 mInitStatus = OK;
3024 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003025 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003026
3027 status_t initCheck() const { return mInitStatus; }
3028
3029 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
3030 CHECK_EQ(1u, mFields.size());
3031 return mFields[0];
3032 }
3033
3034 const C2ApiFeaturesSetting &getApiFeatures() const {
3035 return mApiFeatures;
3036 }
3037
Taehwan Kim900b49c2021-12-13 11:16:22 +09003038 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
3039 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
3040 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
3041 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
3042 param->invalidate();
3043 return param;
3044 }();
3045 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
3046 }
3047
Wonsik Kimffb889a2020-05-28 11:32:25 -07003048 const C2PortAllocatorsTuning::input &getInputAllocators() const {
3049 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
3050 std::unique_ptr<C2PortAllocatorsTuning::input> param =
3051 C2PortAllocatorsTuning::input::AllocUnique(0);
3052 param->invalidate();
3053 return param;
3054 }();
3055 return mInputAllocators ? *mInputAllocators : *sInvalidated;
3056 }
3057
3058private:
3059 status_t mInitStatus{NO_INIT};
3060
3061 std::vector<C2FieldSupportedValuesQuery> mFields;
3062 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09003063 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003064 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
3065};
3066
3067static const IntfCache &GetIntfCache(const std::string &name) {
3068 static IntfCache sNullIntfCache;
3069 static std::mutex sMutex;
3070 static std::map<std::string, IntfCache> sCache;
3071 std::unique_lock<std::mutex> lock{sMutex};
3072 auto it = sCache.find(name);
3073 if (it == sCache.end()) {
3074 lock.unlock();
3075 IntfCache intfCache;
3076 status_t err = intfCache.init(name);
3077 if (err != OK) {
3078 return sNullIntfCache;
3079 }
3080 lock.lock();
3081 it = sCache.insert({name, std::move(intfCache)}).first;
3082 }
3083 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003084}
3085
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003086static status_t GetCommonAllocatorIds(
3087 const std::vector<std::string> &names,
3088 C2Allocator::type_t type,
3089 std::set<C2Allocator::id_t> *ids) {
3090 int poolMask = GetCodec2PoolMask();
3091 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
3092 C2Allocator::id_t defaultAllocatorId =
3093 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
3094
3095 ids->clear();
3096 if (names.empty()) {
3097 return OK;
3098 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003099 bool firstIteration = true;
3100 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003101 const IntfCache &intfCache = GetIntfCache(name);
3102 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003103 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003104 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09003105 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
3106 if (streamFormat) {
3107 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
3108 if (streamFormat.value == C2BufferData::GRAPHIC
3109 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
3110 allocatorType = C2Allocator::GRAPHIC;
3111 }
3112
3113 if (type != allocatorType) {
3114 // requested type is not supported at input allocators
3115 ids->clear();
3116 ids->insert(defaultAllocatorId);
3117 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
3118 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
3119 break;
3120 }
3121 }
3122
Wonsik Kimffb889a2020-05-28 11:32:25 -07003123 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003124 if (firstIteration) {
3125 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003126 if (allocators && allocators.flexCount() > 0) {
3127 ids->insert(allocators.m.values,
3128 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003129 }
3130 if (ids->empty()) {
3131 // The component does not advertise allocators. Use default.
3132 ids->insert(defaultAllocatorId);
3133 }
3134 continue;
3135 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003136 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07003137 if (allocators && allocators.flexCount() > 0) {
3138 filtered = true;
3139 for (auto it = ids->begin(); it != ids->end(); ) {
3140 bool found = false;
3141 for (size_t j = 0; j < allocators.flexCount(); ++j) {
3142 if (allocators.m.values[j] == *it) {
3143 found = true;
3144 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003145 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003146 }
3147 if (found) {
3148 ++it;
3149 } else {
3150 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003151 }
3152 }
3153 }
3154 if (!filtered) {
3155 // The component does not advertise supported allocators. Use default.
3156 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
3157 if (ids->size() != (containsDefault ? 1 : 0)) {
3158 ids->clear();
3159 if (containsDefault) {
3160 ids->insert(defaultAllocatorId);
3161 }
3162 }
3163 }
3164 }
3165 // Finally, filter with pool masks
3166 for (auto it = ids->begin(); it != ids->end(); ) {
3167 if ((poolMask >> *it) & 1) {
3168 ++it;
3169 } else {
3170 it = ids->erase(it);
3171 }
3172 }
3173 return OK;
3174}
3175
3176static status_t CalculateMinMaxUsage(
3177 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
3178 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
3179 *minUsage = 0;
3180 *maxUsage = ~0ull;
3181 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003182 const IntfCache &intfCache = GetIntfCache(name);
3183 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07003184 continue;
3185 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003186 const C2FieldSupportedValuesQuery &usageSupportedValues =
3187 intfCache.getUsageSupportedValues();
3188 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003189 continue;
3190 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07003191 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003192 if (supported.type != C2FieldSupportedValues::FLAGS) {
3193 continue;
3194 }
3195 if (supported.values.empty()) {
3196 *maxUsage = 0;
3197 continue;
3198 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08003199 if (supported.values.size() > 1) {
3200 *minUsage |= supported.values[1].u64;
3201 } else {
3202 *minUsage |= supported.values[0].u64;
3203 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003204 int64_t currentMaxUsage = 0;
3205 for (const C2Value::Primitive &flags : supported.values) {
3206 currentMaxUsage |= flags.u64;
3207 }
3208 *maxUsage &= currentMaxUsage;
3209 }
3210 return OK;
3211}
3212
3213// static
3214status_t CCodec::CanFetchLinearBlock(
3215 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07003216 for (const std::string &name : names) {
3217 const IntfCache &intfCache = GetIntfCache(name);
3218 if (intfCache.initCheck() != OK) {
3219 continue;
3220 }
3221 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
3222 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
3223 *isCompatible = false;
3224 return OK;
3225 }
3226 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003227 std::set<C2Allocator::id_t> allocators;
3228 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
3229 if (allocators.empty()) {
3230 *isCompatible = false;
3231 return OK;
3232 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003233
3234 uint64_t minUsage = 0;
3235 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003236 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003237 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003238 *isCompatible = ((maxUsage & minUsage) == minUsage);
3239 return OK;
3240}
3241
3242static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
3243 static std::mutex sMutex{};
3244 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
3245 std::unique_lock<std::mutex> lock{sMutex};
3246 std::shared_ptr<C2BlockPool> pool;
3247 auto it = sPools.find(allocId);
3248 if (it == sPools.end()) {
3249 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3250 if (err == OK) {
3251 sPools.emplace(allocId, pool);
3252 } else {
3253 pool.reset();
3254 }
3255 } else {
3256 pool = it->second;
3257 }
3258 return pool;
3259}
3260
3261// static
3262std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
3263 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003264 std::set<C2Allocator::id_t> allocators;
3265 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
3266 if (allocators.empty()) {
3267 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
3268 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003269
3270 uint64_t minUsage = 0;
3271 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003272 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09003273 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08003274 if ((maxUsage & minUsage) != minUsage) {
3275 allocators.clear();
3276 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
3277 }
3278 std::shared_ptr<C2LinearBlock> block;
3279 for (C2Allocator::id_t allocId : allocators) {
3280 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
3281 if (!pool) {
3282 continue;
3283 }
3284 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
3285 if (err != C2_OK || !block) {
3286 block.reset();
3287 continue;
3288 }
3289 break;
3290 }
3291 return block;
3292}
3293
3294// static
3295status_t CCodec::CanFetchGraphicBlock(
3296 const std::vector<std::string> &names, bool *isCompatible) {
3297 uint64_t minUsage = 0;
3298 uint64_t maxUsage = ~0ull;
3299 std::set<C2Allocator::id_t> allocators;
3300 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3301 if (allocators.empty()) {
3302 *isCompatible = false;
3303 return OK;
3304 }
3305 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3306 *isCompatible = ((maxUsage & minUsage) == minUsage);
3307 return OK;
3308}
3309
3310// static
3311std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
3312 int32_t width,
3313 int32_t height,
3314 int32_t format,
3315 uint64_t usage,
3316 const std::vector<std::string> &names) {
3317 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
3318 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
3319 ALOGD("Unrecognized pixel format: %d", format);
3320 return nullptr;
3321 }
3322 uint64_t minUsage = 0;
3323 uint64_t maxUsage = ~0ull;
3324 std::set<C2Allocator::id_t> allocators;
3325 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3326 if (allocators.empty()) {
3327 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3328 }
3329 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3330 minUsage |= usage;
3331 if ((maxUsage & minUsage) != minUsage) {
3332 allocators.clear();
3333 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3334 }
3335 std::shared_ptr<C2GraphicBlock> block;
3336 for (C2Allocator::id_t allocId : allocators) {
3337 std::shared_ptr<C2BlockPool> pool;
3338 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3339 if (err != C2_OK || !pool) {
3340 continue;
3341 }
3342 err = pool->fetchGraphicBlock(
3343 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
3344 if (err != C2_OK || !block) {
3345 block.reset();
3346 continue;
3347 }
3348 break;
3349 }
3350 return block;
3351}
3352
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003353} // namespace android