blob: 6295b06437d8b1879ab403a2a5b4d50e26e61a78 [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
Pawin Vongmasa36653902018-11-15 00:10:25 -080029#include <android/IOMXBufferSource.h>
Pawin Vongmasabf69de92019-10-29 06:21:27 -070030#include <android/hardware/media/c2/1.0/IInputSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080031#include <android/hardware/media/omx/1.0/IGraphicBufferSource.h>
32#include <android/hardware/media/omx/1.0/IOmx.h>
Wonsik Kim50811882022-04-28 15:57:27 -070033#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080034#include <android-base/stringprintf.h>
35#include <cutils/properties.h>
36#include <gui/IGraphicBufferProducer.h>
37#include <gui/Surface.h>
38#include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070039#include <media/omx/1.0/WOmxNode.h>
40#include <media/openmax/OMX_Core.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080041#include <media/openmax/OMX_IndexExt.h>
Wonsik Kim1f5063d2021-05-03 15:41:17 -070042#include <media/stagefright/foundation/avc_utils.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070043#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
44#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070045#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080046#include <media/stagefright/BufferProducerWrapper.h>
47#include <media/stagefright/MediaCodecConstants.h>
48#include <media/stagefright/PersistentSurface.h>
ted.sun765db4d2020-06-23 14:03:41 +080049#include <utils/NativeHandle.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080050
51#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080052#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070053#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080054#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080055#include "InputSurfaceWrapper.h"
56
57extern "C" android::PersistentSurface *CreateInputSurface();
58
59namespace android {
60
61using namespace std::chrono_literals;
62using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
63using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080064using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080065
Wonsik Kim9917d4a2019-10-24 12:56:38 -070066typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070067typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070068
Pawin Vongmasa36653902018-11-15 00:10:25 -080069namespace {
70
71class CCodecWatchdog : public AHandler {
72private:
73 enum {
74 kWhatWatch,
75 };
76 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
77
78public:
79 static sp<CCodecWatchdog> getInstance() {
80 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
81 static std::once_flag flag;
82 // Call Init() only once.
83 std::call_once(flag, Init, instance);
84 return instance;
85 }
86
87 ~CCodecWatchdog() = default;
88
89 void watch(sp<CCodec> codec) {
90 bool shouldPost = false;
91 {
92 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
93 // If a watch message is in flight, piggy-back this instance as well.
94 // Otherwise, post a new watch message.
95 shouldPost = codecs->empty();
96 codecs->emplace(codec);
97 }
98 if (shouldPost) {
99 ALOGV("posting watch message");
100 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
101 }
102 }
103
104protected:
105 void onMessageReceived(const sp<AMessage> &msg) {
106 switch (msg->what()) {
107 case kWhatWatch: {
108 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
109 ALOGV("watch for %zu codecs", codecs->size());
110 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
111 sp<CCodec> codec = it->promote();
112 if (codec == nullptr) {
113 continue;
114 }
115 codec->initiateReleaseIfStuck();
116 }
117 codecs->clear();
118 break;
119 }
120
121 default: {
122 TRESPASS("CCodecWatchdog: unrecognized message");
123 }
124 }
125 }
126
127private:
128 CCodecWatchdog() : mLooper(new ALooper) {}
129
130 static void Init(const sp<CCodecWatchdog> &thiz) {
131 ALOGV("Init");
132 thiz->mLooper->setName("CCodecWatchdog");
133 thiz->mLooper->registerHandler(thiz);
134 thiz->mLooper->start();
135 }
136
137 sp<ALooper> mLooper;
138
139 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
140};
141
142class C2InputSurfaceWrapper : public InputSurfaceWrapper {
143public:
144 explicit C2InputSurfaceWrapper(
145 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
146 mSurface(surface) {
147 }
148
149 ~C2InputSurfaceWrapper() override = default;
150
151 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
152 if (mConnection != nullptr) {
153 return ALREADY_EXISTS;
154 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800155 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800156 }
157
158 void disconnect() override {
159 if (mConnection != nullptr) {
160 mConnection->disconnect();
161 mConnection = nullptr;
162 }
163 }
164
165 status_t start() override {
166 // InputSurface does not distinguish started state
167 return OK;
168 }
169
170 status_t signalEndOfInputStream() override {
171 C2InputSurfaceEosTuning eos(true);
172 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800173 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800174 if (err != C2_OK) {
175 return UNKNOWN_ERROR;
176 }
177 return OK;
178 }
179
180 status_t configure(Config &config __unused) {
181 // TODO
182 return OK;
183 }
184
185private:
186 std::shared_ptr<Codec2Client::InputSurface> mSurface;
187 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
188};
189
190class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
191public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700192 typedef hardware::media::omx::V1_0::Status OmxStatus;
193
Pawin Vongmasa36653902018-11-15 00:10:25 -0800194 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700195 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800196 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700197 uint32_t height,
198 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800199 : mSource(source), mWidth(width), mHeight(height) {
200 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700201 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800202 }
203 ~GraphicBufferSourceWrapper() override = default;
204
205 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
206 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700207 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800208 mNode->setFrameSize(mWidth, mHeight);
Sungtak Leeb6caaf82023-02-02 00:59:01 +0000209
Ian Kasprzak50990272023-08-11 16:31:50 +0000210 // Usage is queried during configure(), so setting it beforehand.
211 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
212 (void)mNode->setParameter(
213 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
214 &usage, sizeof(usage));
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700215
Yanqiang Fanc56f3e62021-09-28 16:54:07 +0800216 return GetStatus(mSource->configure(
217 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800218 }
219
220 void disconnect() override {
221 if (mNode == nullptr) {
222 return;
223 }
224 sp<IOMXBufferSource> source = mNode->getSource();
225 if (source == nullptr) {
226 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
227 return;
228 }
229 source->onOmxIdle();
230 source->onOmxLoaded();
231 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700232 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800233 }
234
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700235 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
236 if (status.isOk()) {
237 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
238 } else if (status.isDeadObject()) {
239 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800240 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700241 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800242 }
243
244 status_t start() override {
245 sp<IOMXBufferSource> source = mNode->getSource();
246 if (source == nullptr) {
247 return NO_INIT;
248 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900249
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800250 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800251 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900252
Wonsik Kim34d66012021-03-01 16:40:33 -0800253 OMX_PARAM_PORTDEFINITIONTYPE param;
254 param.nPortIndex = kPortIndexInput;
255 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
256 &param, sizeof(param));
257 if (err == OK) {
258 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900259 }
260
261 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800262 source->onInputBufferAdded(i);
263 }
264
265 source->onOmxExecuting();
266 return OK;
267 }
268
269 status_t signalEndOfInputStream() override {
270 return GetStatus(mSource->signalEndOfInputStream());
271 }
272
273 status_t configure(Config &config) {
274 std::stringstream status;
275 status_t err = OK;
276
277 // handle each configuration granually, in case we need to handle part of the configuration
278 // elsewhere
279
280 // TRICKY: we do not unset frame delay repeating
281 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
282 int64_t us = 1e6 / config.mMinFps + 0.5;
283 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
284 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
285 if (res != OK) {
286 status << " (=> " << asString(res) << ")";
287 err = res;
288 }
289 mConfig.mMinFps = config.mMinFps;
290 }
291
292 // pts gap
293 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
294 if (mNode != nullptr) {
295 OMX_PARAM_U32TYPE ptrGapParam = {};
296 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700297 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800298 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
299 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700300 // float -> uint32_t is undefined if the value is negative.
301 // First convert to int32_t to ensure the expected behavior.
302 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800303 (void)mNode->setParameter(
304 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
305 &ptrGapParam, sizeof(ptrGapParam));
306 }
307 }
308
309 // max fps
310 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700311 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800312 && config.mMaxFps != mConfig.mMaxFps) {
313 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
314 status << " maxFps=" << config.mMaxFps;
315 if (res != OK) {
316 status << " (=> " << asString(res) << ")";
317 err = res;
318 }
319 mConfig.mMaxFps = config.mMaxFps;
320 }
321
322 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
323 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
324 status << " timeOffset " << config.mTimeOffsetUs << "us";
325 if (res != OK) {
326 status << " (=> " << asString(res) << ")";
327 err = res;
328 }
329 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
330 }
331
332 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
333 status_t res =
334 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
335 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
336 if (res != OK) {
337 status << " (=> " << asString(res) << ")";
338 err = res;
339 }
340 mConfig.mCaptureFps = config.mCaptureFps;
341 mConfig.mCodedFps = config.mCodedFps;
342 }
343
344 if (config.mStartAtUs != mConfig.mStartAtUs
345 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
346 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
347 status << " start at " << config.mStartAtUs << "us";
348 if (res != OK) {
349 status << " (=> " << asString(res) << ")";
350 err = res;
351 }
352 mConfig.mStartAtUs = config.mStartAtUs;
353 mConfig.mStopped = config.mStopped;
354 }
355
356 // suspend-resume
357 if (config.mSuspended != mConfig.mSuspended) {
358 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
359 status << " " << (config.mSuspended ? "suspend" : "resume")
360 << " at " << config.mSuspendAtUs << "us";
361 if (res != OK) {
362 status << " (=> " << asString(res) << ")";
363 err = res;
364 }
365 mConfig.mSuspended = config.mSuspended;
366 mConfig.mSuspendAtUs = config.mSuspendAtUs;
367 }
368
369 if (config.mStopped != mConfig.mStopped && config.mStopped) {
370 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
371 status << " stop at " << config.mStopAtUs << "us";
372 if (res != OK) {
373 status << " (=> " << asString(res) << ")";
374 err = res;
375 } else {
376 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700377 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
378 [&res, &delayUs = config.mInputDelayUs](
379 auto status, auto stopTimeOffsetUs) {
380 res = static_cast<status_t>(status);
381 delayUs = stopTimeOffsetUs;
382 });
383 if (!trans.isOk()) {
384 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
385 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800386 if (res != OK) {
387 status << " (=> " << asString(res) << ")";
388 } else {
389 status << "=" << config.mInputDelayUs << "us";
390 }
391 mConfig.mInputDelayUs = config.mInputDelayUs;
392 }
393 mConfig.mStopAtUs = config.mStopAtUs;
394 mConfig.mStopped = config.mStopped;
395 }
396
397 // color aspects (android._color-aspects)
398
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700399 // consumer usage is queried earlier.
400
Wonsik Kima1335e12021-04-22 16:28:29 -0700401 // priority
402 if (mConfig.mPriority != config.mPriority) {
403 if (config.mPriority != INT_MAX) {
404 mNode->setPriority(config.mPriority);
405 }
406 mConfig.mPriority = config.mPriority;
407 }
408
Wonsik Kimbd557932019-07-02 15:51:20 -0700409 if (status.str().empty()) {
410 ALOGD("ISConfig not changed");
411 } else {
412 ALOGD("ISConfig%s", status.str().c_str());
413 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800414 return err;
415 }
416
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700417 void onInputBufferDone(c2_cntr64_t index) override {
418 mNode->onInputBufferDone(index);
419 }
420
Wonsik Kim673dd192021-01-29 14:58:12 -0800421 android_dataspace getDataspace() override {
422 return mNode->getDataspace();
423 }
424
Pawin Vongmasa36653902018-11-15 00:10:25 -0800425private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700426 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800427 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700428 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800429 uint32_t mWidth;
430 uint32_t mHeight;
431 Config mConfig;
432};
433
434class Codec2ClientInterfaceWrapper : public C2ComponentStore {
435 std::shared_ptr<Codec2Client> mClient;
436
437public:
438 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
439 : mClient(client) { }
440
441 virtual ~Codec2ClientInterfaceWrapper() = default;
442
443 virtual c2_status_t config_sm(
444 const std::vector<C2Param *> &params,
445 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
446 return mClient->config(params, C2_MAY_BLOCK, failures);
447 };
448
449 virtual c2_status_t copyBuffer(
450 std::shared_ptr<C2GraphicBuffer>,
451 std::shared_ptr<C2GraphicBuffer>) {
452 return C2_OMITTED;
453 }
454
455 virtual c2_status_t createComponent(
456 C2String, std::shared_ptr<C2Component> *const component) {
457 component->reset();
458 return C2_OMITTED;
459 }
460
461 virtual c2_status_t createInterface(
462 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
463 interface->reset();
464 return C2_OMITTED;
465 }
466
467 virtual c2_status_t query_sm(
468 const std::vector<C2Param *> &stackParams,
469 const std::vector<C2Param::Index> &heapParamIndices,
470 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
471 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
472 }
473
474 virtual c2_status_t querySupportedParams_nb(
475 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
476 return mClient->querySupportedParams(params);
477 }
478
479 virtual c2_status_t querySupportedValues_sm(
480 std::vector<C2FieldSupportedValuesQuery> &fields) const {
481 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
482 }
483
484 virtual C2String getName() const {
485 return mClient->getName();
486 }
487
488 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
489 return mClient->getParamReflector();
490 }
491
492 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
493 return std::vector<std::shared_ptr<const C2Component::Traits>>();
494 }
495};
496
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800497void RevertOutputFormatIfNeeded(
498 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
499 // We used to not report changes to these keys to the client.
500 const static std::set<std::string> sIgnoredKeys({
501 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800502 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800503 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800504 KEY_MAX_WIDTH,
505 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800506 "csd-0",
507 "csd-1",
508 "csd-2",
509 });
510 if (currentFormat == oldFormat) {
511 return;
512 }
513 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
514 AMessage::Type type;
515 for (size_t i = diff->countEntries(); i > 0; --i) {
516 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
517 diff->removeEntryAt(i - 1);
518 }
519 }
520 if (diff->countEntries() == 0) {
521 currentFormat = oldFormat;
522 }
523}
524
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700525void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700526 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700527 const sp<AMessage> &outputFormat) {
528 if (mediaType == MIMETYPE_VIDEO_AVC) {
529 // Codec specific data should be SPS and PPS in a single buffer,
530 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
531 // We separate the two and put them into the output format
532 // under the keys "csd-0" and "csd-1".
533
534 unsigned csdIndex = 0;
535
536 const uint8_t *nalStart;
537 size_t nalSize;
538 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
539 sp<ABuffer> csd = new ABuffer(nalSize + 4);
540 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
541 memcpy(csd->data() + 4, nalStart, nalSize);
542
543 outputFormat->setBuffer(
544 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
545
546 ++csdIndex;
547 }
548
549 if (csdIndex != 2) {
550 ALOGW("Expected two NAL units from AVC codec config, but %u found",
551 csdIndex);
552 }
553 } else {
554 // For everything else we just stash the codec specific data into
555 // the output format as a single piece of csd under "csd-0".
556 sp<ABuffer> csd = new ABuffer(size);
557 memcpy(csd->data(), data, size);
558 csd->setRange(0, size);
559 outputFormat->setBuffer("csd-0", csd);
560 }
561}
562
Pawin Vongmasa36653902018-11-15 00:10:25 -0800563} // namespace
564
565// CCodec::ClientListener
566
567struct CCodec::ClientListener : public Codec2Client::Listener {
568
569 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
570
571 virtual void onWorkDone(
572 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800573 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800574 (void)component;
575 sp<CCodec> codec(mCodec.promote());
576 if (!codec) {
577 return;
578 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800579 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800580 }
581
582 virtual void onTripped(
583 const std::weak_ptr<Codec2Client::Component>& component,
584 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
585 ) override {
586 // TODO
587 (void)component;
588 (void)settingResult;
589 }
590
591 virtual void onError(
592 const std::weak_ptr<Codec2Client::Component>& component,
593 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800594 {
595 // Component is only used for reporting as we use a separate listener for each instance
596 std::shared_ptr<Codec2Client::Component> comp = component.lock();
597 if (!comp) {
598 ALOGD("Component died with error: 0x%x", errorCode);
599 } else {
600 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
601 }
602 }
603
604 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800605 // Note: for now we do not propagate the error code to MediaCodec
606 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800607 sp<CCodec> codec(mCodec.promote());
608 if (!codec || !codec->mCallback) {
609 return;
610 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800611 codec->mCallback->onError(
612 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
613 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800614 }
615
616 virtual void onDeath(
617 const std::weak_ptr<Codec2Client::Component>& component) override {
618 { // Log the death of the component.
619 std::shared_ptr<Codec2Client::Component> comp = component.lock();
620 if (!comp) {
621 ALOGE("Codec2 component died.");
622 } else {
623 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
624 }
625 }
626
627 // Report to MediaCodec.
628 sp<CCodec> codec(mCodec.promote());
629 if (!codec || !codec->mCallback) {
630 return;
631 }
632 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
633 }
634
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800635 virtual void onFrameRendered(uint64_t bufferQueueId,
636 int32_t slotId,
637 int64_t timestampNs) override {
638 // TODO: implement
639 (void)bufferQueueId;
640 (void)slotId;
641 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800642 }
643
644 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800645 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800646 sp<CCodec> codec(mCodec.promote());
647 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800648 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800649 }
650 }
651
652private:
653 wp<CCodec> mCodec;
654};
655
656// CCodecCallbackImpl
657
658class CCodecCallbackImpl : public CCodecCallback {
659public:
660 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
661 ~CCodecCallbackImpl() override = default;
662
663 void onError(status_t err, enum ActionCode actionCode) override {
664 mCodec->mCallback->onError(err, actionCode);
665 }
666
667 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
668 mCodec->mCallback->onOutputFramesRendered(
669 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
670 }
671
Pawin Vongmasa36653902018-11-15 00:10:25 -0800672 void onOutputBuffersChanged() override {
673 mCodec->mCallback->onOutputBuffersChanged();
674 }
675
Guillaume Chelfi5ffbcb32021-04-12 14:23:43 +0200676 void onFirstTunnelFrameReady() override {
677 mCodec->mCallback->onFirstTunnelFrameReady();
678 }
679
Pawin Vongmasa36653902018-11-15 00:10:25 -0800680private:
681 CCodec *mCodec;
682};
683
684// CCodec
685
686CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700687 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
688 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800689}
690
691CCodec::~CCodec() {
692}
693
694std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
695 return mChannel;
696}
697
698status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
699 status_t err = job();
700 if (err != C2_OK) {
701 mCallback->onError(err, ACTION_CODE_FATAL);
702 }
703 return err;
704}
705
706void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
707 auto setAllocating = [this] {
708 Mutexed<State>::Locked state(mState);
709 if (state->get() != RELEASED) {
710 return INVALID_OPERATION;
711 }
712 state->set(ALLOCATING);
713 return OK;
714 };
715 if (tryAndReportOnError(setAllocating) != OK) {
716 return;
717 }
718
719 sp<RefBase> codecInfo;
720 CHECK(msg->findObject("codecInfo", &codecInfo));
721 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
722
723 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
724 allocMsg->setObject("codecInfo", codecInfo);
725 allocMsg->post();
726}
727
728void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
729 if (codecInfo == nullptr) {
730 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
731 return;
732 }
733 ALOGD("allocate(%s)", codecInfo->getCodecName());
734 mClientListener.reset(new ClientListener(this));
735
736 AString componentName = codecInfo->getCodecName();
737 std::shared_ptr<Codec2Client> client;
738
739 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700740 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800741 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800742 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800743 SetPreferredCodec2ComponentStore(
744 std::make_shared<Codec2ClientInterfaceWrapper>(client));
745 }
746
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900747 std::shared_ptr<Codec2Client::Component> comp;
748 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800749 componentName.c_str(),
750 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900751 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800752 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900753 if (status != C2_OK) {
754 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800755 Mutexed<State>::Locked state(mState);
756 state->set(RELEASED);
757 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900758 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759 state.lock();
760 return;
761 }
762 ALOGI("Created component [%s]", componentName.c_str());
763 mChannel->setComponent(comp);
764 auto setAllocated = [this, comp, client] {
765 Mutexed<State>::Locked state(mState);
766 if (state->get() != ALLOCATING) {
767 state->set(RELEASED);
768 return UNKNOWN_ERROR;
769 }
770 state->set(ALLOCATED);
771 state->comp = comp;
772 mClient = client;
773 return OK;
774 };
775 if (tryAndReportOnError(setAllocated) != OK) {
776 return;
777 }
778
779 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700780 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
781 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800782 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800783 if (err != OK) {
784 ALOGW("Failed to initialize configuration support");
785 // TODO: report error once we complete implementation.
786 }
787 config->queryConfiguration(comp);
788
789 mCallback->onComponentAllocated(componentName.c_str());
790}
791
792void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
793 auto checkAllocated = [this] {
794 Mutexed<State>::Locked state(mState);
795 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
796 };
797 if (tryAndReportOnError(checkAllocated) != OK) {
798 return;
799 }
800
801 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
802 msg->setMessage("format", format);
803 msg->post();
804}
805
806void CCodec::configure(const sp<AMessage> &msg) {
807 std::shared_ptr<Codec2Client::Component> comp;
808 auto checkAllocated = [this, &comp] {
809 Mutexed<State>::Locked state(mState);
810 if (state->get() != ALLOCATED) {
811 state->set(RELEASED);
812 return UNKNOWN_ERROR;
813 }
814 comp = state->comp;
815 return OK;
816 };
817 if (tryAndReportOnError(checkAllocated) != OK) {
818 return;
819 }
820
821 auto doConfig = [msg, comp, this]() -> status_t {
822 AString mime;
823 if (!msg->findString("mime", &mime)) {
824 return BAD_VALUE;
825 }
826
827 int32_t encoder;
828 if (!msg->findInt32("encoder", &encoder)) {
829 encoder = false;
830 }
831
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800832 int32_t flags;
833 if (!msg->findInt32("flags", &flags)) {
834 return BAD_VALUE;
835 }
836
Pawin Vongmasa36653902018-11-15 00:10:25 -0800837 // TODO: read from intf()
838 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
839 return UNKNOWN_ERROR;
840 }
841
842 int32_t storeMeta;
843 if (encoder
844 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
845 && storeMeta != kMetadataBufferTypeInvalid) {
846 if (storeMeta != kMetadataBufferTypeANWBuffer) {
847 ALOGD("Only ANW buffers are supported for legacy metadata mode");
848 return BAD_VALUE;
849 }
850 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
851 }
852
ted.sun765db4d2020-06-23 14:03:41 +0800853 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800854 sp<RefBase> obj;
855 sp<Surface> surface;
856 if (msg->findObject("native-window", &obj)) {
857 surface = static_cast<Surface *>(obj.get());
ted.sun765db4d2020-06-23 14:03:41 +0800858 // setup tunneled playback
859 if (surface != nullptr) {
860 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
861 const std::unique_ptr<Config> &config = *configLocked;
862 if ((config->mDomain & Config::IS_DECODER)
863 && (config->mDomain & Config::IS_VIDEO)) {
864 int32_t tunneled;
865 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
866 ALOGI("Configuring TUNNELED video playback.");
867
868 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
869 if (err != OK) {
870 ALOGE("configureTunneledVideoPlayback failed!");
871 return err;
872 }
873 config->mTunneled = true;
874 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +0100875
876 int32_t pushBlankBuffersOnStop = 0;
877 if (msg->findInt32(KEY_PUSH_BLANK_BUFFERS_ON_STOP, &pushBlankBuffersOnStop)) {
878 config->mPushBlankBuffersOnStop = pushBlankBuffersOnStop == 1;
879 }
shuanglong.wang480a8362023-02-17 20:55:51 +0800880 // secure compoment or protected content default with
881 // "push-blank-buffers-on-shutdown" flag
882 if (!config->mPushBlankBuffersOnStop) {
883 int32_t usageProtected;
884 if (comp->getName().find(".secure") != std::string::npos) {
885 config->mPushBlankBuffersOnStop = true;
886 } else if (msg->findInt32("protected", &usageProtected) && usageProtected) {
887 config->mPushBlankBuffersOnStop = true;
888 }
889 }
ted.sun765db4d2020-06-23 14:03:41 +0800890 }
891 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800892 setSurface(surface);
893 }
894
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700895 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
896 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800897 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800898 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
899 ALOGD("[%s] buffers are %sbound to CCodec for this session",
900 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800901
Wonsik Kim1114eea2019-02-25 14:35:24 -0800902 // Enforce required parameters
903 int32_t i32;
904 float flt;
905 if (config->mDomain & Config::IS_AUDIO) {
906 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
907 ALOGD("sample rate is missing, which is required for audio components.");
908 return BAD_VALUE;
909 }
910 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
911 ALOGD("channel count is missing, which is required for audio components.");
912 return BAD_VALUE;
913 }
914 if ((config->mDomain & Config::IS_ENCODER)
915 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
916 && !msg->findInt32(KEY_BIT_RATE, &i32)
917 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
918 ALOGD("bitrate is missing, which is required for audio encoders.");
919 return BAD_VALUE;
920 }
921 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800922 int32_t width = 0;
923 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800924 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800925 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800926 ALOGD("width is missing, which is required for image/video components.");
927 return BAD_VALUE;
928 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800929 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800930 ALOGD("height is missing, which is required for image/video components.");
931 return BAD_VALUE;
932 }
933 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700934 int32_t mode = BITRATE_MODE_VBR;
935 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700936 if (!msg->findInt32(KEY_QUALITY, &i32)) {
937 ALOGD("quality is missing, which is required for video encoders in CQ.");
938 return BAD_VALUE;
939 }
940 } else {
941 if (!msg->findInt32(KEY_BIT_RATE, &i32)
942 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
943 ALOGD("bitrate is missing, which is required for video encoders.");
944 return BAD_VALUE;
945 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800946 }
947 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
948 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
949 ALOGD("I frame interval is missing, which is required for video encoders.");
950 return BAD_VALUE;
951 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700952 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
953 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
954 ALOGD("frame rate is missing, which is required for video encoders.");
955 return BAD_VALUE;
956 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800957 }
958 }
959
Pawin Vongmasa36653902018-11-15 00:10:25 -0800960 /*
961 * Handle input surface configuration
962 */
963 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
964 && (config->mDomain & Config::IS_ENCODER)) {
965 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
966 {
967 config->mISConfig->mMinFps = 0;
968 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800969 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800970 config->mISConfig->mMinFps = 1e6 / value;
971 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700972 if (!msg->findFloat(
973 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
974 config->mISConfig->mMaxFps = -1;
975 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800976 config->mISConfig->mMinAdjustedFps = 0;
977 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800978 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800979 if (value < 0 && value >= INT32_MIN) {
980 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700981 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800982 } else if (value > 0 && value <= INT32_MAX) {
983 config->mISConfig->mMinAdjustedFps = 1e6 / value;
984 }
985 }
986 }
987
988 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700989 bool captureFpsFound = false;
990 double timeLapseFps;
991 float captureRate;
992 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
993 config->mISConfig->mCaptureFps = timeLapseFps;
994 captureFpsFound = true;
995 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
996 config->mISConfig->mCaptureFps = captureRate;
997 captureFpsFound = true;
998 }
999 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001000 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
1001 }
1002 }
1003
1004 {
1005 config->mISConfig->mSuspended = false;
1006 config->mISConfig->mSuspendAtUs = -1;
1007 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001008 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001009 config->mISConfig->mSuspended = true;
1010 }
1011 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001012 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -07001013 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001014 }
1015
1016 /*
1017 * Handle desired color format.
1018 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001019 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001020 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001021 int32_t format = 0;
1022 // Query vendor format for Flexible YUV
1023 std::vector<std::unique_ptr<C2Param>> heapParams;
1024 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
Wonsik Kim50811882022-04-28 15:57:27 -07001025 int vendorSdkVersion = base::GetIntProperty(
1026 "ro.vendor.build.version.sdk", android_get_device_api_level());
guochuang709b48b2022-10-25 20:40:42 +08001027 if (mClient->query(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001028 {},
1029 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1030 C2_MAY_BLOCK,
1031 &heapParams) == C2_OK
1032 && heapParams.size() == 1u) {
1033 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1034 heapParams[0].get());
1035 } else {
1036 pixelFormatInfo = nullptr;
1037 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001038 // bit depth -> format
1039 std::map<uint32_t, uint32_t> flexPixelFormat;
1040 std::map<uint32_t, uint32_t> flexPlanarPixelFormat;
1041 std::map<uint32_t, uint32_t> flexSemiPlanarPixelFormat;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001042 if (pixelFormatInfo && *pixelFormatInfo) {
1043 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1044 const C2FlexiblePixelFormatDescriptorStruct &desc =
1045 pixelFormatInfo->m.values[i];
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001046 if (desc.subsampling != C2Color::YUV_420
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001047 // TODO(b/180076105): some device report wrong layout
1048 // || desc.layout == C2Color::INTERLEAVED_PACKED
1049 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1050 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1051 continue;
1052 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001053 if (flexPixelFormat.count(desc.bitDepth) == 0) {
1054 flexPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001055 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001056 if (desc.layout == C2Color::PLANAR_PACKED
1057 && flexPlanarPixelFormat.count(desc.bitDepth) == 0) {
1058 flexPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001059 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001060 if (desc.layout == C2Color::SEMIPLANAR_PACKED
1061 && flexSemiPlanarPixelFormat.count(desc.bitDepth) == 0) {
1062 flexSemiPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001063 }
1064 }
1065 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001066 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001067 // Also handle default color format (encoders require color format, so this is only
1068 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001069 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001070 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001071 const char *prefix = "";
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001072 if (flexSemiPlanarPixelFormat.count(8) != 0) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001073 format = COLOR_FormatYUV420SemiPlanar;
1074 prefix = "semi-";
1075 } else {
1076 format = COLOR_FormatYUV420Planar;
1077 }
1078 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1079 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001080 } else {
1081 format = COLOR_FormatSurface;
1082 }
1083 defaultColorFormat = format;
1084 }
1085 } else {
1086 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001087 if (vendorSdkVersion < __ANDROID_API_S__ &&
Taehwan Kim43e715d2022-09-22 12:04:59 +09001088 (format == COLOR_FormatYUV420Planar ||
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001089 format == COLOR_FormatYUV420PackedPlanar ||
1090 format == COLOR_FormatYUV420SemiPlanar ||
1091 format == COLOR_FormatYUV420PackedSemiPlanar)) {
1092 // pre-S framework used to map these color formats into YV12.
1093 // Codecs from older vendor partition may be relying on
1094 // this assumption.
1095 format = HAL_PIXEL_FORMAT_YV12;
1096 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001097 switch (format) {
1098 case COLOR_FormatYUV420Flexible:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001099 format = COLOR_FormatYUV420Planar;
1100 if (flexPixelFormat.count(8) != 0) {
1101 format = flexPixelFormat[8];
1102 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001103 break;
1104 case COLOR_FormatYUV420Planar:
1105 case COLOR_FormatYUV420PackedPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001106 if (flexPlanarPixelFormat.count(8) != 0) {
1107 format = flexPlanarPixelFormat[8];
1108 } else if (flexPixelFormat.count(8) != 0) {
1109 format = flexPixelFormat[8];
1110 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001111 break;
1112 case COLOR_FormatYUV420SemiPlanar:
1113 case COLOR_FormatYUV420PackedSemiPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001114 if (flexSemiPlanarPixelFormat.count(8) != 0) {
1115 format = flexSemiPlanarPixelFormat[8];
1116 } else if (flexPixelFormat.count(8) != 0) {
1117 format = flexPixelFormat[8];
1118 }
1119 break;
1120 case COLOR_FormatYUVP010:
1121 format = COLOR_FormatYUVP010;
1122 if (flexSemiPlanarPixelFormat.count(10) != 0) {
1123 format = flexSemiPlanarPixelFormat[10];
1124 } else if (flexPixelFormat.count(10) != 0) {
1125 format = flexPixelFormat[10];
1126 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001127 break;
1128 default:
1129 // No-op
1130 break;
1131 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001132 }
1133 }
1134
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001135 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001136 msg->setInt32("android._color-format", format);
1137 }
1138 }
1139
Wonsik Kim77e97c72021-01-20 10:33:22 -08001140 /*
1141 * Handle dataspace
1142 */
1143 int32_t usingRecorder;
1144 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1145 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1146 int32_t width, height;
1147 if (msg->findInt32("width", &width)
1148 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001149 ColorAspects aspects;
1150 getColorAspectsFromFormat(msg, aspects);
1151 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001152 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001153 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1154 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001155 }
1156 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1157 ALOGD("setting dataspace to %x", dataSpace);
1158 }
1159
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001160 int32_t subscribeToAllVendorParams;
1161 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1162 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1163 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1164 }
1165 }
1166
Pawin Vongmasa36653902018-11-15 00:10:25 -08001167 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001168 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1169 // the behavior here.
1170 sp<AMessage> sdkParams = msg;
1171 int32_t videoBitrate;
1172 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1173 sdkParams = msg->dup();
1174 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1175 }
ted.sun765db4d2020-06-23 14:03:41 +08001176 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001177 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001178 if (err != OK) {
1179 ALOGW("failed to convert configuration to c2 params");
1180 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001181
1182 int32_t maxBframes = 0;
1183 if ((config->mDomain & Config::IS_ENCODER)
1184 && (config->mDomain & Config::IS_VIDEO)
1185 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1186 && maxBframes > 0) {
1187 std::unique_ptr<C2StreamGopTuning::output> gop =
1188 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1189 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1190 gop->m.values[1] = {
1191 C2Config::picture_type_t(P_FRAME | B_FRAME),
1192 uint32_t(maxBframes)
1193 };
1194 configUpdate.push_back(std::move(gop));
1195 }
1196
Ray Essicka0ae6972021-03-10 19:40:01 -08001197 if ((config->mDomain & Config::IS_ENCODER)
1198 && (config->mDomain & Config::IS_VIDEO)) {
1199 // we may not use all 3 of these entries
1200 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1201 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1202 0u /* stream */);
1203
1204 int ix = 0;
1205
1206 int32_t iMax = INT32_MAX;
1207 int32_t iMin = INT32_MIN;
1208 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1209 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1210 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1211 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1212 }
1213
1214 int32_t pMax = INT32_MAX;
1215 int32_t pMin = INT32_MIN;
1216 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1217 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1218 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1219 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1220 }
1221
1222 int32_t bMax = INT32_MAX;
1223 int32_t bMin = INT32_MIN;
1224 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1225 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1226 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1227 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1228 }
1229
1230 // adjust to reflect actual use.
1231 qp->setFlexCount(ix);
1232
1233 configUpdate.push_back(std::move(qp));
1234 }
1235
Wonsik Kima1335e12021-04-22 16:28:29 -07001236 int32_t background = 0;
1237 if ((config->mDomain & Config::IS_VIDEO)
1238 && msg->findInt32("android._background-mode", &background)
1239 && background) {
1240 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1241 if (config->mISConfig) {
1242 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1243 }
1244 }
1245
Pawin Vongmasa36653902018-11-15 00:10:25 -08001246 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1247 if (err != OK) {
1248 ALOGW("failed to configure c2 params");
1249 return err;
1250 }
1251
1252 std::vector<std::unique_ptr<C2Param>> params;
1253 C2StreamUsageTuning::input usage(0u, 0u);
1254 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001255 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001256
Wonsik Kim3baecda2021-02-07 22:19:56 -08001257 C2Param::Index colorAspectsRequestIndex =
1258 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001259 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001260 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001261 };
Chaejung Lim86c22dc2021-12-23 00:41:05 -08001262 int32_t colorTransferRequest = 0;
1263 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1264 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1265 colorTransferRequest = 0;
1266 }
1267 c2_status_t c2err = C2_OK;
1268 if (colorTransferRequest != 0) {
1269 c2err = comp->query(
1270 { &usage, &maxInputSize, &prepend },
1271 indices,
1272 C2_DONT_BLOCK,
1273 &params);
1274 } else {
1275 c2err = comp->query(
1276 { &usage, &maxInputSize, &prepend },
1277 {},
1278 C2_DONT_BLOCK,
1279 &params);
1280 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001281 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1282 ALOGE("Failed to query component interface: %d", c2err);
1283 return UNKNOWN_ERROR;
1284 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001285 if (usage) {
1286 if (usage.value & C2MemoryUsage::CPU_READ) {
1287 config->mInputFormat->setInt32("using-sw-read-often", true);
1288 }
1289 if (config->mISConfig) {
1290 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1291 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1292 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001293 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001294 }
1295
1296 // NOTE: we don't blindly use client specified input size if specified as clients
1297 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1298 // client specified size is only used to ask for bigger buffers than component suggested
1299 // size.
1300 int32_t clientInputSize = 0;
1301 bool clientSpecifiedInputSize =
1302 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1303 // TEMP: enforce minimum buffer size of 1MB for video decoders
1304 // and 16K / 4K for audio encoders/decoders
1305 if (maxInputSize.value == 0) {
1306 if (config->mDomain & Config::IS_AUDIO) {
1307 maxInputSize.value = encoder ? 16384 : 4096;
1308 } else if (!encoder) {
1309 maxInputSize.value = 1048576u;
1310 }
1311 }
1312
1313 // verify that CSD fits into this size (if defined)
1314 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1315 sp<ABuffer> csd;
1316 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1317 if (csd && csd->size() > maxInputSize.value) {
1318 maxInputSize.value = csd->size();
1319 }
1320 }
1321 }
1322
1323 // TODO: do this based on component requiring linear allocator for input
1324 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1325 if (clientSpecifiedInputSize) {
1326 // Warn that we're overriding client's max input size if necessary.
1327 if ((uint32_t)clientInputSize < maxInputSize.value) {
1328 ALOGD("client requested max input size %d, which is smaller than "
1329 "what component recommended (%u); overriding with component "
1330 "recommendation.", clientInputSize, maxInputSize.value);
1331 ALOGW("This behavior is subject to change. It is recommended that "
1332 "app developers double check whether the requested "
1333 "max input size is in reasonable range.");
1334 } else {
1335 maxInputSize.value = clientInputSize;
1336 }
1337 }
1338 // Pass max input size on input format to the buffer channel (if supplied by the
1339 // component or by a default)
1340 if (maxInputSize.value) {
1341 config->mInputFormat->setInt32(
1342 KEY_MAX_INPUT_SIZE,
1343 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1344 }
1345 }
1346
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001347 int32_t clientPrepend;
1348 if ((config->mDomain & Config::IS_VIDEO)
1349 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001350 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001351 && clientPrepend
1352 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001353 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001354 return BAD_VALUE;
1355 }
1356
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001357 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001358 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1359 // propagate HDR static info to output format for both encoders and decoders
1360 // if component supports this info, we will update from component, but only the raw port,
1361 // so don't propagate if component already filled it in.
1362 sp<ABuffer> hdrInfo;
1363 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1364 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1365 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1366 }
1367
1368 // Set desired color format from configuration parameter
1369 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001370 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1371 format = defaultColorFormat;
1372 }
1373 if (config->mDomain & Config::IS_ENCODER) {
1374 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001375 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1376 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001377 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001378 } else {
1379 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001380 }
1381 }
1382
1383 // propagate encoder delay and padding to output format
1384 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1385 int delay = 0;
1386 if (msg->findInt32("encoder-delay", &delay)) {
1387 config->mOutputFormat->setInt32("encoder-delay", delay);
1388 }
1389 int padding = 0;
1390 if (msg->findInt32("encoder-padding", &padding)) {
1391 config->mOutputFormat->setInt32("encoder-padding", padding);
1392 }
1393 }
1394
Pawin Vongmasa36653902018-11-15 00:10:25 -08001395 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001396 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001397 int32_t mask;
1398 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1399 if (config->mDomain & Config::IS_ENCODER) {
1400 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1401 } else {
1402 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1403 }
1404 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001405
1406 // set PCM encoding
1407 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1408 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1409 if (encoder) {
1410 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1411 } else {
1412 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1413 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001414 }
1415
Wonsik Kim3baecda2021-02-07 22:19:56 -08001416 std::unique_ptr<C2Param> colorTransferRequestParam;
1417 for (std::unique_ptr<C2Param> &param : params) {
1418 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1419 ALOGI("found color transfer request param");
1420 colorTransferRequestParam = std::move(param);
1421 }
1422 }
Wonsik Kim3baecda2021-02-07 22:19:56 -08001423
1424 if (colorTransferRequest != 0) {
1425 if (colorTransferRequestParam && *colorTransferRequestParam) {
1426 C2StreamColorAspectsInfo::output *info =
1427 static_cast<C2StreamColorAspectsInfo::output *>(
1428 colorTransferRequestParam.get());
1429 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1430 colorTransferRequest = 0;
1431 }
1432 } else {
1433 colorTransferRequest = 0;
1434 }
1435 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1436 }
1437
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001438 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1439 // Need to get stride/vstride
1440 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1441 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1442 // TODO: retrieve these values without allocating a buffer.
1443 // Currently allocating a buffer is necessary to retrieve the layout.
1444 int64_t blockUsage =
1445 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1446 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
Taehwan Kim2772e1c2022-03-31 17:15:08 +09001447 width, height, componentColorFormat, blockUsage, {comp->getName()});
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001448 sp<GraphicBlockBuffer> buffer;
1449 if (block) {
1450 buffer = GraphicBlockBuffer::Allocate(
1451 config->mInputFormat,
1452 block,
1453 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1454 } else {
1455 ALOGD("Failed to allocate a graphic block "
1456 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1457 width, height, pixelFormat, (long long)blockUsage);
1458 // This means that byte buffer mode is not supported in this configuration
1459 // anyway. Skip setting stride/vstride to input format.
1460 }
1461 if (buffer) {
1462 sp<ABuffer> imageData = buffer->getImageData();
1463 MediaImage2 *img = nullptr;
1464 if (imageData && imageData->data()
1465 && imageData->size() >= sizeof(MediaImage2)) {
1466 img = (MediaImage2*)imageData->data();
1467 }
1468 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1469 int32_t stride = img->mPlane[0].mRowInc;
1470 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1471 if (img->mNumPlanes > 1 && stride > 0) {
1472 int64_t offsetDelta =
1473 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1474 if (offsetDelta % stride == 0) {
1475 int32_t vstride = int32_t(offsetDelta / stride);
1476 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1477 } else {
1478 ALOGD("Cannot report accurate slice height: "
1479 "offsetDelta = %lld stride = %d",
1480 (long long)offsetDelta, stride);
1481 }
1482 }
1483 }
1484 }
1485 }
1486 }
1487
Wonsik Kimec585c32021-10-01 01:11:00 -07001488 if (config->mTunneled) {
1489 config->mOutputFormat->setInt32("android._tunneled", 1);
1490 }
1491
Yushin Cho91873b52021-12-21 04:08:35 -08001492 // Convert an encoding statistics level to corresponding encoding statistics
1493 // kinds
1494 int32_t encodingStatisticsLevel = VIDEO_ENCODING_STATISTICS_LEVEL_NONE;
1495 if ((config->mDomain & Config::IS_ENCODER)
1496 && (config->mDomain & Config::IS_VIDEO)
1497 && msg->findInt32(KEY_VIDEO_ENCODING_STATISTICS_LEVEL, &encodingStatisticsLevel)) {
1498 // Higher level include all the enc stats belong to lower level.
1499 switch (encodingStatisticsLevel) {
1500 // case VIDEO_ENCODING_STATISTICS_LEVEL_2: // reserved for the future level 2
1501 // with more enc stat kinds
1502 // Future extended encoding statistics for the level 2 should be added here
1503 case VIDEO_ENCODING_STATISTICS_LEVEL_1:
Wonsik Kimeebab652022-06-02 13:01:55 -07001504 config->subscribeToConfigUpdate(
1505 comp,
1506 {
1507 C2AndroidStreamAverageBlockQuantizationInfo::output::PARAM_TYPE,
1508 C2StreamPictureTypeInfo::output::PARAM_TYPE,
1509 });
Yushin Cho91873b52021-12-21 04:08:35 -08001510 break;
1511 case VIDEO_ENCODING_STATISTICS_LEVEL_NONE:
1512 break;
1513 }
1514 }
1515 ALOGD("encoding statistics level = %d", encodingStatisticsLevel);
1516
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001517 ALOGD("setup formats input: %s",
1518 config->mInputFormat->debugString().c_str());
1519 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001520 config->mOutputFormat->debugString().c_str());
1521 return OK;
1522 };
1523 if (tryAndReportOnError(doConfig) != OK) {
1524 return;
1525 }
1526
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001527 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1528 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001529
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001530 config->queryConfiguration(comp);
1531
Pawin Vongmasa36653902018-11-15 00:10:25 -08001532 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1533}
1534
1535void CCodec::initiateCreateInputSurface() {
1536 status_t err = [this] {
1537 Mutexed<State>::Locked state(mState);
1538 if (state->get() != ALLOCATED) {
1539 return UNKNOWN_ERROR;
1540 }
1541 // TODO: read it from intf() properly.
1542 if (state->comp->getName().find("encoder") == std::string::npos) {
1543 return INVALID_OPERATION;
1544 }
1545 return OK;
1546 }();
1547 if (err != OK) {
1548 mCallback->onInputSurfaceCreationFailed(err);
1549 return;
1550 }
1551
1552 (new AMessage(kWhatCreateInputSurface, this))->post();
1553}
1554
Lajos Molnar47118272019-01-31 16:28:04 -08001555sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1556 using namespace android::hardware::media::omx::V1_0;
1557 using namespace android::hardware::media::omx::V1_0::utils;
1558 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1559 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1560 android::sp<IOmx> omx = IOmx::getService();
Sungtak Lee47dcb482022-04-15 10:47:08 -07001561 if (omx == nullptr) {
1562 return nullptr;
1563 }
Lajos Molnar47118272019-01-31 16:28:04 -08001564 typedef android::hardware::graphics::bufferqueue::V1_0::
1565 IGraphicBufferProducer HGraphicBufferProducer;
1566 typedef android::hardware::media::omx::V1_0::
1567 IGraphicBufferSource HGraphicBufferSource;
1568 OmxStatus s;
1569 android::sp<HGraphicBufferProducer> gbp;
1570 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001571
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001572 using ::android::hardware::Return;
1573 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001574 [&s, &gbp, &gbs](
1575 OmxStatus status,
1576 const android::sp<HGraphicBufferProducer>& producer,
1577 const android::sp<HGraphicBufferSource>& source) {
1578 s = status;
1579 gbp = producer;
1580 gbs = source;
1581 });
1582 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001583 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001584 }
1585
1586 return nullptr;
1587}
1588
1589sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1590 sp<PersistentSurface> surface(CreateInputSurface());
1591
1592 if (surface == nullptr) {
1593 surface = CreateOmxInputSurface();
1594 }
1595
1596 return surface;
1597}
1598
Pawin Vongmasa36653902018-11-15 00:10:25 -08001599void CCodec::createInputSurface() {
1600 status_t err;
1601 sp<IGraphicBufferProducer> bufferProducer;
1602
Pawin Vongmasa36653902018-11-15 00:10:25 -08001603 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001604 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001605 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001606 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1607 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001608 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001609 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001610 }
1611
Lajos Molnar47118272019-01-31 16:28:04 -08001612 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001613 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1614 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1615 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001616
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001617 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001618 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1619 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001620 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001621 inputSurface));
1622 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001623 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001624 int32_t width = 0;
1625 (void)outputFormat->findInt32("width", &width);
1626 int32_t height = 0;
1627 (void)outputFormat->findInt32("height", &height);
1628 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001629 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001630 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001631 } else {
1632 ALOGE("Corrupted input surface");
1633 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1634 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001635 }
1636
1637 if (err != OK) {
1638 ALOGE("Failed to set up input surface: %d", err);
1639 mCallback->onInputSurfaceCreationFailed(err);
1640 return;
1641 }
1642
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001643 // Formats can change after setupInputSurface
1644 sp<AMessage> inputFormat;
1645 {
1646 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1647 const std::unique_ptr<Config> &config = *configLocked;
1648 inputFormat = config->mInputFormat;
1649 outputFormat = config->mOutputFormat;
1650 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001651 mCallback->onInputSurfaceCreated(
1652 inputFormat,
1653 outputFormat,
1654 new BufferProducerWrapper(bufferProducer));
1655}
1656
1657status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001658 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1659 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001660 config->mUsingSurface = true;
1661
1662 // we are now using surface - apply default color aspects to input format - as well as
1663 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001664 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001665
1666 // configure dataspace
1667 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
Wonsik Kim66b19552021-08-02 16:07:49 -07001668
1669 // The output format contains app-configured color aspects, and the input format
1670 // has the default color aspects. Use the default for the unspecified params.
1671 ColorAspects inputColorAspects, colorAspects;
1672 getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
1673 getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
1674 if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
1675 colorAspects.mRange = inputColorAspects.mRange;
1676 }
1677 if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
1678 colorAspects.mPrimaries = inputColorAspects.mPrimaries;
1679 }
1680 if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
1681 colorAspects.mTransfer = inputColorAspects.mTransfer;
1682 }
1683 if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
1684 colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
1685 }
1686 android_dataspace dataSpace = getDataSpaceForColorAspects(
1687 colorAspects, /* mayExtend = */ false);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001688 surface->setDataSpace(dataSpace);
Wonsik Kim66b19552021-08-02 16:07:49 -07001689 setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
1690 config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
1691
1692 ALOGD("input format %s to %s",
1693 inputFormatChanged ? "changed" : "unchanged",
1694 config->mInputFormat->debugString().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001695
1696 status_t err = mChannel->setInputSurface(surface);
1697 if (err != OK) {
1698 // undo input format update
1699 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001700 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001701 return err;
1702 }
1703 config->mInputSurface = surface;
1704
1705 if (config->mISConfig) {
1706 surface->configure(*config->mISConfig);
1707 } else {
1708 ALOGD("ISConfig: no configuration");
1709 }
1710
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001711 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001712}
1713
1714void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1715 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1716 msg->setObject("surface", surface);
1717 msg->post();
1718}
1719
1720void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001721 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001722 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001723 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001724 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1725 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001726 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001727 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001728 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001729 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1730 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1731 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1732 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001733 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1734 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1735 if (err != OK) {
1736 ALOGE("Failed to set up input surface: %d", err);
1737 mCallback->onInputSurfaceDeclined(err);
1738 return;
1739 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001740 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001741 int32_t width = 0;
1742 (void)outputFormat->findInt32("width", &width);
1743 int32_t height = 0;
1744 (void)outputFormat->findInt32("height", &height);
1745 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001746 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001747 if (err != OK) {
1748 ALOGE("Failed to set up input surface: %d", err);
1749 mCallback->onInputSurfaceDeclined(err);
1750 return;
1751 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001752 } else {
1753 ALOGE("Failed to set input surface: Corrupted surface.");
1754 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1755 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001756 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001757 // Formats can change after setupInputSurface
1758 sp<AMessage> inputFormat;
1759 {
1760 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1761 const std::unique_ptr<Config> &config = *configLocked;
1762 inputFormat = config->mInputFormat;
1763 outputFormat = config->mOutputFormat;
1764 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001765 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1766}
1767
1768void CCodec::initiateStart() {
1769 auto setStarting = [this] {
1770 Mutexed<State>::Locked state(mState);
1771 if (state->get() != ALLOCATED) {
1772 return UNKNOWN_ERROR;
1773 }
1774 state->set(STARTING);
1775 return OK;
1776 };
1777 if (tryAndReportOnError(setStarting) != OK) {
1778 return;
1779 }
1780
1781 (new AMessage(kWhatStart, this))->post();
1782}
1783
1784void CCodec::start() {
1785 std::shared_ptr<Codec2Client::Component> comp;
1786 auto checkStarting = [this, &comp] {
1787 Mutexed<State>::Locked state(mState);
1788 if (state->get() != STARTING) {
1789 return UNKNOWN_ERROR;
1790 }
1791 comp = state->comp;
1792 return OK;
1793 };
1794 if (tryAndReportOnError(checkStarting) != OK) {
1795 return;
1796 }
1797
1798 c2_status_t err = comp->start();
1799 if (err != C2_OK) {
1800 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1801 ACTION_CODE_FATAL);
1802 return;
1803 }
Wonsik Kimd86c96b2023-06-22 14:42:17 -07001804
1805 // clear the deadline after the component starts
1806 setDeadline(TimePoint::max(), 0ms, "none");
1807
Pawin Vongmasa36653902018-11-15 00:10:25 -08001808 sp<AMessage> inputFormat;
1809 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001810 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001811 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001812 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001813 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1814 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001815 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001816 // start triggers format dup
1817 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001818 if (config->mInputSurface) {
1819 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001820 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001821 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001822 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001823 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001824 if (err2 != OK) {
1825 mCallback->onError(err2, ACTION_CODE_FATAL);
1826 return;
1827 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001828 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001829 if (err2 != OK) {
1830 mCallback->onError(err2, ACTION_CODE_FATAL);
1831 return;
1832 }
1833
1834 auto setRunning = [this] {
1835 Mutexed<State>::Locked state(mState);
1836 if (state->get() != STARTING) {
1837 return UNKNOWN_ERROR;
1838 }
1839 state->set(RUNNING);
1840 return OK;
1841 };
1842 if (tryAndReportOnError(setRunning) != OK) {
1843 return;
1844 }
Arun Johnson5997bb02022-04-01 19:35:44 +00001845
Wonsik Kim34b28b42022-05-20 15:49:32 -07001846 // preparation of input buffers may not succeed due to the lack of
1847 // memory; returning correct error code (NO_MEMORY) as an error allows
1848 // MediaCodec to try reclaim and restart codec gracefully.
1849 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
1850 err2 = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
1851 if (err2 != OK) {
1852 ALOGE("Initial preparation for Input Buffers failed");
1853 mCallback->onError(err2, ACTION_CODE_FATAL);
1854 return;
1855 }
1856
Pawin Vongmasa36653902018-11-15 00:10:25 -08001857 mCallback->onStartCompleted();
1858
Wonsik Kim34b28b42022-05-20 15:49:32 -07001859 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001860}
1861
1862void CCodec::initiateShutdown(bool keepComponentAllocated) {
1863 if (keepComponentAllocated) {
1864 initiateStop();
1865 } else {
1866 initiateRelease();
1867 }
1868}
1869
1870void CCodec::initiateStop() {
1871 {
1872 Mutexed<State>::Locked state(mState);
1873 if (state->get() == ALLOCATED
1874 || state->get() == RELEASED
1875 || state->get() == STOPPING
1876 || state->get() == RELEASING) {
1877 // We're already stopped, released, or doing it right now.
1878 state.unlock();
1879 mCallback->onStopCompleted();
1880 state.lock();
1881 return;
1882 }
1883 state->set(STOPPING);
1884 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001885 mChannel->reset();
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001886 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
1887 sp<AMessage> stopMessage(new AMessage(kWhatStop, this));
1888 stopMessage->setInt32("pushBlankBuffer", pushBlankBuffer);
1889 stopMessage->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001890}
1891
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001892void CCodec::stop(bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001893 std::shared_ptr<Codec2Client::Component> comp;
1894 {
1895 Mutexed<State>::Locked state(mState);
1896 if (state->get() == RELEASING) {
1897 state.unlock();
1898 // We're already stopped or release is in progress.
1899 mCallback->onStopCompleted();
1900 state.lock();
1901 return;
1902 } else if (state->get() != STOPPING) {
1903 state.unlock();
1904 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1905 state.lock();
1906 return;
1907 }
1908 comp = state->comp;
1909 }
1910 status_t err = comp->stop();
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001911 mChannel->stopUseOutputSurface(pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001912 if (err != C2_OK) {
1913 // TODO: convert err into status_t
1914 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1915 }
1916
1917 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001918 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1919 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001920 if (config->mInputSurface) {
1921 config->mInputSurface->disconnect();
1922 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001923 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001924 }
1925 }
1926 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001927 Mutexed<State>::Locked state(mState);
1928 if (state->get() == STOPPING) {
1929 state->set(ALLOCATED);
1930 }
1931 }
1932 mCallback->onStopCompleted();
1933}
1934
1935void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001936 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001937 {
1938 Mutexed<State>::Locked state(mState);
1939 if (state->get() == RELEASED || state->get() == RELEASING) {
1940 // We're already released or doing it right now.
1941 if (sendCallback) {
1942 state.unlock();
1943 mCallback->onReleaseCompleted();
1944 state.lock();
1945 }
1946 return;
1947 }
1948 if (state->get() == ALLOCATING) {
1949 state->set(RELEASING);
1950 // With the altered state allocate() would fail and clean up.
1951 if (sendCallback) {
1952 state.unlock();
1953 mCallback->onReleaseCompleted();
1954 state.lock();
1955 }
1956 return;
1957 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001958 if (state->get() == STARTING
1959 || state->get() == RUNNING
1960 || state->get() == STOPPING) {
1961 // Input surface may have been started, so clean up is needed.
1962 clearInputSurfaceIfNeeded = true;
1963 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001964 state->set(RELEASING);
1965 }
1966
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001967 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001968 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1969 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001970 if (config->mInputSurface) {
1971 config->mInputSurface->disconnect();
1972 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001973 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001974 }
1975 }
1976
Wonsik Kim936a89c2020-05-08 16:07:50 -07001977 mChannel->reset();
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001978 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001979 // thiz holds strong ref to this while the thread is running.
1980 sp<CCodec> thiz(this);
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001981 std::thread([thiz, sendCallback, pushBlankBuffer]
1982 { thiz->release(sendCallback, pushBlankBuffer); }).detach();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001983}
1984
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001985void CCodec::release(bool sendCallback, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001986 std::shared_ptr<Codec2Client::Component> comp;
1987 {
1988 Mutexed<State>::Locked state(mState);
1989 if (state->get() == RELEASED) {
1990 if (sendCallback) {
1991 state.unlock();
1992 mCallback->onReleaseCompleted();
1993 state.lock();
1994 }
1995 return;
1996 }
1997 comp = state->comp;
1998 }
1999 comp->release();
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002000 mChannel->stopUseOutputSurface(pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002001
2002 {
2003 Mutexed<State>::Locked state(mState);
2004 state->set(RELEASED);
2005 state->comp.reset();
2006 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002007 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002008 if (sendCallback) {
2009 mCallback->onReleaseCompleted();
2010 }
2011}
2012
2013status_t CCodec::setSurface(const sp<Surface> &surface) {
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002014 bool pushBlankBuffer = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002015 {
2016 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2017 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002018 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
2019 status_t err = OK;
2020
Wonsik Kim75e22f42021-04-14 23:34:51 -07002021 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002022 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07002023 nativeWindow.get(),
2024 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
2025 if (err != OK) {
2026 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
2027 nativeWindow.get(), config->mSidebandHandle->handle(), err);
2028 return err;
2029 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002030 } else {
2031 // Explicitly reset the sideband handle of the window for
2032 // non-tunneled video in case the window was previously used
2033 // for a tunneled video playback.
2034 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
2035 if (err != OK) {
2036 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
2037 return err;
2038 }
ted.sun765db4d2020-06-23 14:03:41 +08002039 }
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002040 pushBlankBuffer = config->mPushBlankBuffersOnStop;
ted.sun765db4d2020-06-23 14:03:41 +08002041 }
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002042 return mChannel->setSurface(surface, pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002043}
2044
2045void CCodec::signalFlush() {
2046 status_t err = [this] {
2047 Mutexed<State>::Locked state(mState);
2048 if (state->get() == FLUSHED) {
2049 return ALREADY_EXISTS;
2050 }
2051 if (state->get() != RUNNING) {
2052 return UNKNOWN_ERROR;
2053 }
2054 state->set(FLUSHING);
2055 return OK;
2056 }();
2057 switch (err) {
2058 case ALREADY_EXISTS:
2059 mCallback->onFlushCompleted();
2060 return;
2061 case OK:
2062 break;
2063 default:
2064 mCallback->onError(err, ACTION_CODE_FATAL);
2065 return;
2066 }
2067
2068 mChannel->stop();
2069 (new AMessage(kWhatFlush, this))->post();
2070}
2071
2072void CCodec::flush() {
2073 std::shared_ptr<Codec2Client::Component> comp;
2074 auto checkFlushing = [this, &comp] {
2075 Mutexed<State>::Locked state(mState);
2076 if (state->get() != FLUSHING) {
2077 return UNKNOWN_ERROR;
2078 }
2079 comp = state->comp;
2080 return OK;
2081 };
2082 if (tryAndReportOnError(checkFlushing) != OK) {
2083 return;
2084 }
2085
2086 std::list<std::unique_ptr<C2Work>> flushedWork;
2087 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2088 {
2089 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2090 flushedWork.splice(flushedWork.end(), *queue);
2091 }
2092 if (err != C2_OK) {
2093 // TODO: convert err into status_t
2094 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2095 }
2096
2097 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002098
2099 {
2100 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002101 if (state->get() == FLUSHING) {
2102 state->set(FLUSHED);
2103 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002104 }
2105 mCallback->onFlushCompleted();
2106}
2107
2108void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002109 std::shared_ptr<Codec2Client::Component> comp;
2110 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002111 Mutexed<State>::Locked state(mState);
2112 if (state->get() != FLUSHED) {
2113 return UNKNOWN_ERROR;
2114 }
2115 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002116 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002117 return OK;
2118 };
2119 if (tryAndReportOnError(setResuming) != OK) {
2120 return;
2121 }
2122
Wonsik Kime75a5da2020-02-14 17:29:03 -08002123 {
2124 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2125 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002126 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002127 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002128 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002129 }
2130
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002131 (void)mChannel->start(nullptr, nullptr, [&]{
2132 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2133 const std::unique_ptr<Config> &config = *configLocked;
2134 return config->mBuffersBoundToCodec;
2135 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002136
2137 {
2138 Mutexed<State>::Locked state(mState);
2139 if (state->get() != RESUMING) {
2140 state.unlock();
2141 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2142 state.lock();
2143 return;
2144 }
2145 state->set(RUNNING);
2146 }
2147
Wonsik Kim34b28b42022-05-20 15:49:32 -07002148 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
2149 status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
Wonsik Kim944b0a52022-08-18 17:06:33 -07002150 // FIXME(b/237656746)
2151 if (err != OK && err != NO_MEMORY) {
Wonsik Kima027bf72022-05-09 19:45:57 -07002152 ALOGE("Resume request for Input Buffers failed");
2153 mCallback->onError(err, ACTION_CODE_FATAL);
Wonsik Kim34b28b42022-05-20 15:49:32 -07002154 return;
Wonsik Kima027bf72022-05-09 19:45:57 -07002155 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07002156 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002157}
2158
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002159void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002160 std::shared_ptr<Codec2Client::Component> comp;
2161 auto checkState = [this, &comp] {
2162 Mutexed<State>::Locked state(mState);
2163 if (state->get() == RELEASED) {
2164 return INVALID_OPERATION;
2165 }
2166 comp = state->comp;
2167 return OK;
2168 };
2169 if (tryAndReportOnError(checkState) != OK) {
2170 return;
2171 }
2172
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002173 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2174 // the behavior here.
2175 sp<AMessage> params = msg;
2176 int32_t bitrate;
2177 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2178 params = msg->dup();
2179 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2180 }
2181
Houxiang Dai5a97b472021-03-22 17:56:04 +08002182 int32_t syncId = 0;
2183 if (params->findInt32("audio-hw-sync", &syncId)
2184 || params->findInt32("hw-av-sync-id", &syncId)) {
2185 configureTunneledVideoPlayback(comp, nullptr, params);
2186 }
2187
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002188 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2189 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002190
2191 /**
2192 * Handle input surface parameters
2193 */
2194 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002195 && (config->mDomain & Config::IS_ENCODER)
2196 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002197 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002198
2199 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2200 config->mISConfig->mStopped = false;
2201 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2202 config->mISConfig->mStopped = true;
2203 }
2204
2205 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002206 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002207 config->mISConfig->mSuspended = value;
2208 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002209 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002210 }
2211
2212 (void)config->mInputSurface->configure(*config->mISConfig);
2213 if (config->mISConfig->mStopped) {
2214 config->mInputFormat->setInt64(
2215 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2216 }
2217 }
2218
2219 std::vector<std::unique_ptr<C2Param>> configUpdate;
2220 (void)config->getConfigUpdateFromSdkParams(
2221 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2222 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2223 // Parameter synchronization is not defined when using input surface. For now, route
2224 // these directly to the component.
2225 if (config->mInputSurface == nullptr
2226 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2227 || comp->getName().find("c2.android.") == 0)) {
2228 mChannel->setParameters(configUpdate);
2229 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002230 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002231 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002232 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002233 }
2234}
2235
2236void CCodec::signalEndOfInputStream() {
2237 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2238}
2239
2240void CCodec::signalRequestIDRFrame() {
2241 std::shared_ptr<Codec2Client::Component> comp;
2242 {
2243 Mutexed<State>::Locked state(mState);
2244 if (state->get() == RELEASED) {
2245 ALOGD("no IDR request sent since component is released");
2246 return;
2247 }
2248 comp = state->comp;
2249 }
2250 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002251 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2252 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002253 std::vector<std::unique_ptr<C2Param>> params;
2254 params.push_back(
2255 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2256 config->setParameters(comp, params, C2_MAY_BLOCK);
2257}
2258
Wonsik Kim874ad382021-03-12 09:59:36 -08002259status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2260 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2261 const std::unique_ptr<Config> &config = *configLocked;
2262 return config->querySupportedParameters(names);
2263}
2264
2265status_t CCodec::describeParameter(
2266 const std::string &name, CodecParameterDescriptor *desc) {
2267 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2268 const std::unique_ptr<Config> &config = *configLocked;
2269 return config->describe(name, desc);
2270}
2271
2272status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2273 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2274 if (!comp) {
2275 return INVALID_OPERATION;
2276 }
2277 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2278 const std::unique_ptr<Config> &config = *configLocked;
2279 return config->subscribeToVendorConfigUpdate(comp, names);
2280}
2281
2282status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2283 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2284 if (!comp) {
2285 return INVALID_OPERATION;
2286 }
2287 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2288 const std::unique_ptr<Config> &config = *configLocked;
2289 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2290}
2291
Wonsik Kimab34ed62019-01-31 15:28:46 -08002292void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002293 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002294 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2295 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002296 }
2297 (new AMessage(kWhatWorkDone, this))->post();
2298}
2299
Wonsik Kimab34ed62019-01-31 15:28:46 -08002300void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2301 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002302 if (arrayIndex == 0) {
2303 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002304 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2305 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002306 if (config->mInputSurface) {
2307 config->mInputSurface->onInputBufferDone(frameIndex);
2308 }
2309 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002310}
2311
2312void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2313 TimePoint now = std::chrono::steady_clock::now();
2314 CCodecWatchdog::getInstance()->watch(this);
2315 switch (msg->what()) {
2316 case kWhatAllocate: {
2317 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002318 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002319 sp<RefBase> obj;
2320 CHECK(msg->findObject("codecInfo", &obj));
2321 allocate((MediaCodecInfo *)obj.get());
2322 break;
2323 }
2324 case kWhatConfigure: {
2325 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002326 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002327 sp<AMessage> format;
2328 CHECK(msg->findMessage("format", &format));
2329 configure(format);
2330 break;
2331 }
2332 case kWhatStart: {
2333 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002334 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002335 start();
2336 break;
2337 }
2338 case kWhatStop: {
2339 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002340 setDeadline(now, 1500ms, "stop");
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002341 int32_t pushBlankBuffer;
2342 if (!msg->findInt32("pushBlankBuffer", &pushBlankBuffer)) {
2343 pushBlankBuffer = 0;
2344 }
2345 stop(static_cast<bool>(pushBlankBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002346 break;
2347 }
2348 case kWhatFlush: {
2349 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002350 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002351 flush();
2352 break;
2353 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002354 case kWhatRelease: {
2355 mChannel->release();
2356 mClient.reset();
2357 mClientListener.reset();
2358 break;
2359 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002360 case kWhatCreateInputSurface: {
2361 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002362 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002363 createInputSurface();
2364 break;
2365 }
2366 case kWhatSetInputSurface: {
2367 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002368 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002369 sp<RefBase> obj;
2370 CHECK(msg->findObject("surface", &obj));
2371 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2372 setInputSurface(surface);
2373 break;
2374 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002375 case kWhatWorkDone: {
2376 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002377 bool shouldPost = false;
2378 {
2379 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2380 if (queue->empty()) {
2381 break;
2382 }
2383 work.swap(queue->front());
2384 queue->pop_front();
2385 shouldPost = !queue->empty();
2386 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002387 if (shouldPost) {
2388 (new AMessage(kWhatWorkDone, this))->post();
2389 }
2390
Pawin Vongmasa36653902018-11-15 00:10:25 -08002391 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002392 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002393 sp<AMessage> outputFormat = nullptr;
2394 {
2395 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2396 const std::unique_ptr<Config> &config = *configLocked;
2397 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2398 config->watch<C2StreamInitDataInfo::output>();
2399 if (!work->worklets.empty()
2400 && (work->worklets.front()->output.flags
2401 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002402
Wonsik Kim75e22f42021-04-14 23:34:51 -07002403 // copy buffer info to config
2404 std::vector<std::unique_ptr<C2Param>> updates;
2405 for (const std::unique_ptr<C2Param> &param
2406 : work->worklets.front()->output.configUpdate) {
2407 updates.push_back(C2Param::Copy(*param));
2408 }
2409 unsigned stream = 0;
2410 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2411 work->worklets.front()->output.buffers;
2412 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2413 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2414 // move all info into output-stream #0 domain
2415 updates.emplace_back(
2416 C2Param::CopyAsStream(*info, true /* output */, stream));
2417 }
2418
2419 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2420 // for now only do the first block
2421 if (!blocks.empty()) {
2422 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2423 // block.crop().left, block.crop().top,
2424 // block.crop().width, block.crop().height,
2425 // block.width(), block.height());
2426 const C2ConstGraphicBlock &block = blocks[0];
2427 updates.emplace_back(new C2StreamCropRectInfo::output(
2428 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002429 }
2430 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002431 }
George Burgess IVc813a592020-02-22 22:54:44 -08002432
Wonsik Kim75e22f42021-04-14 23:34:51 -07002433 sp<AMessage> oldFormat = config->mOutputFormat;
2434 config->updateConfiguration(updates, config->mOutputDomain);
2435 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002436
Wonsik Kim75e22f42021-04-14 23:34:51 -07002437 // copy standard infos to graphic buffers if not already present (otherwise, we
2438 // may overwrite the actual intermediate value with a final value)
2439 stream = 0;
2440 const static C2Param::Index stdGfxInfos[] = {
2441 C2StreamRotationInfo::output::PARAM_TYPE,
2442 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2443 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2444 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Taehwan Kim2d222b82022-05-12 14:19:26 +09002445 C2StreamHdr10PlusInfo::output::PARAM_TYPE, // will be deprecated
2446 C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE,
Wonsik Kim75e22f42021-04-14 23:34:51 -07002447 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2448 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2449 };
2450 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2451 if (buf->data().graphicBlocks().size()) {
2452 for (C2Param::Index ix : stdGfxInfos) {
2453 if (!buf->hasInfo(ix)) {
2454 const C2Param *param =
2455 config->getConfigParameterValue(ix.withStream(stream));
2456 if (param) {
2457 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2458 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2459 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002460 }
2461 }
2462 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002463 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002464 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002465 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002466 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302467 if (work->worklets.empty()
2468 || !work->worklets.back()
2469 || (work->worklets.back()->output.flags
2470 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2471 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2472 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002473 }
2474 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002475 initData = initDataWatcher.update();
2476 AmendOutputFormatWithCodecSpecificData(
2477 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2478 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002479 }
2480 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002481 }
2482 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002483 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002484 break;
2485 }
2486 case kWhatWatch: {
2487 // watch message already posted; no-op.
2488 break;
2489 }
2490 default: {
2491 ALOGE("unrecognized message");
2492 break;
2493 }
2494 }
2495 setDeadline(TimePoint::max(), 0ms, "none");
2496}
2497
2498void CCodec::setDeadline(
2499 const TimePoint &now,
2500 const std::chrono::milliseconds &timeout,
2501 const char *name) {
2502 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2503 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2504 deadline->set(now + (timeout * mult), name);
2505}
2506
ted.sun765db4d2020-06-23 14:03:41 +08002507status_t CCodec::configureTunneledVideoPlayback(
2508 std::shared_ptr<Codec2Client::Component> comp,
2509 sp<NativeHandle> *sidebandHandle,
2510 const sp<AMessage> &msg) {
2511 std::vector<std::unique_ptr<C2SettingResult>> failures;
2512
2513 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2514 C2PortTunneledModeTuning::output::AllocUnique(
2515 1,
2516 C2PortTunneledModeTuning::Struct::SIDEBAND,
2517 C2PortTunneledModeTuning::Struct::REALTIME,
2518 0);
2519 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2520 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2521 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2522 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2523 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2524 } else {
2525 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2526 tunneledPlayback->setFlexCount(0);
2527 }
2528 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2529 if (c2err != C2_OK) {
2530 return UNKNOWN_ERROR;
2531 }
2532
Houxiang Dai5a97b472021-03-22 17:56:04 +08002533 if (sidebandHandle == nullptr) {
2534 return OK;
2535 }
2536
ted.sun765db4d2020-06-23 14:03:41 +08002537 std::vector<std::unique_ptr<C2Param>> params;
2538 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2539 if (c2err == C2_OK && params.size() == 1u) {
2540 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2541 C2PortTunnelHandleTuning::output::From(params[0].get());
2542 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2543 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2544 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2545 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2546 memcpy(handle->data, videoTunnelSideband->m.values,
2547 sizeof(int32_t) * videoTunnelSideband->flexCount());
2548 return OK;
2549 } else {
2550 return NO_MEMORY;
2551 }
2552 }
2553 return UNKNOWN_ERROR;
2554}
2555
Pawin Vongmasa36653902018-11-15 00:10:25 -08002556void CCodec::initiateReleaseIfStuck() {
Shrikara B3b87a532022-08-26 14:18:14 +05302557 std::string name;
2558 bool pendingDeadline = false;
2559 {
2560 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2561 if (deadline->get() < std::chrono::steady_clock::now()) {
2562 name = deadline->getName();
2563 }
2564 if (deadline->get() != TimePoint::max()) {
2565 pendingDeadline = true;
2566 }
2567 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002568 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002569 // We're not stuck.
2570 if (pendingDeadline) {
2571 // If we are not stuck yet but still has deadline coming up,
2572 // post watch message to check back later.
2573 (new AMessage(kWhatWatch, this))->post();
2574 }
2575 return;
2576 }
2577
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002578 C2String compName;
2579 {
2580 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002581 if (!state->comp) {
2582 ALOGD("previous call to %s exceeded timeout "
2583 "and the component is already released", name.c_str());
2584 return;
2585 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002586 compName = state->comp->getName();
2587 }
2588 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2589
Pawin Vongmasa36653902018-11-15 00:10:25 -08002590 initiateRelease(false);
2591 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2592}
2593
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002594// static
2595PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002596 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002597 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002598 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002599 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2600 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002601 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002602 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2603 sp<IGraphicBufferProducer> gbp;
2604 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2605 status_t err = gbs->initCheck();
2606 if (err != OK) {
2607 ALOGE("Failed to create persistent input surface: error %d", err);
2608 return nullptr;
2609 }
2610 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002611 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002612 } else {
2613 return nullptr;
2614 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002615 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002616 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002617 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002618 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002619 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002620}
2621
Wonsik Kimffb889a2020-05-28 11:32:25 -07002622class IntfCache {
2623public:
2624 IntfCache() = default;
2625
2626 status_t init(const std::string &name) {
2627 std::shared_ptr<Codec2Client::Interface> intf{
2628 Codec2Client::CreateInterfaceByName(name.c_str())};
2629 if (!intf) {
2630 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2631 mInitStatus = NO_INIT;
2632 return NO_INIT;
2633 }
2634 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2635 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2636 C2ParamField{&sUsage, &sUsage.value}));
2637 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2638 if (err != C2_OK) {
2639 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2640 name.c_str(), err);
2641 mFields[0].status = err;
2642 }
2643 std::vector<std::unique_ptr<C2Param>> params;
2644 err = intf->query(
2645 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09002646 {
2647 C2StreamBufferTypeSetting::input::PARAM_TYPE,
2648 C2PortAllocatorsTuning::input::PARAM_TYPE
2649 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07002650 C2_MAY_BLOCK,
2651 &params);
2652 if (err != C2_OK && err != C2_BAD_INDEX) {
2653 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2654 name.c_str(), err);
2655 }
2656 while (!params.empty()) {
2657 C2Param *param = params.back().release();
2658 params.pop_back();
2659 if (!param) {
2660 continue;
2661 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002662 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
2663 mInputStreamFormat.reset(
2664 C2StreamBufferTypeSetting::input::From(param));
2665 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002666 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002667 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002668 }
2669 }
2670 mInitStatus = OK;
2671 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002672 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002673
2674 status_t initCheck() const { return mInitStatus; }
2675
2676 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2677 CHECK_EQ(1u, mFields.size());
2678 return mFields[0];
2679 }
2680
2681 const C2ApiFeaturesSetting &getApiFeatures() const {
2682 return mApiFeatures;
2683 }
2684
Taehwan Kim900b49c2021-12-13 11:16:22 +09002685 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
2686 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
2687 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
2688 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
2689 param->invalidate();
2690 return param;
2691 }();
2692 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
2693 }
2694
Wonsik Kimffb889a2020-05-28 11:32:25 -07002695 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2696 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2697 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2698 C2PortAllocatorsTuning::input::AllocUnique(0);
2699 param->invalidate();
2700 return param;
2701 }();
2702 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2703 }
2704
2705private:
2706 status_t mInitStatus{NO_INIT};
2707
2708 std::vector<C2FieldSupportedValuesQuery> mFields;
2709 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09002710 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002711 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2712};
2713
2714static const IntfCache &GetIntfCache(const std::string &name) {
2715 static IntfCache sNullIntfCache;
2716 static std::mutex sMutex;
2717 static std::map<std::string, IntfCache> sCache;
2718 std::unique_lock<std::mutex> lock{sMutex};
2719 auto it = sCache.find(name);
2720 if (it == sCache.end()) {
2721 lock.unlock();
2722 IntfCache intfCache;
2723 status_t err = intfCache.init(name);
2724 if (err != OK) {
2725 return sNullIntfCache;
2726 }
2727 lock.lock();
2728 it = sCache.insert({name, std::move(intfCache)}).first;
2729 }
2730 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002731}
2732
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002733static status_t GetCommonAllocatorIds(
2734 const std::vector<std::string> &names,
2735 C2Allocator::type_t type,
2736 std::set<C2Allocator::id_t> *ids) {
2737 int poolMask = GetCodec2PoolMask();
2738 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2739 C2Allocator::id_t defaultAllocatorId =
2740 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2741
2742 ids->clear();
2743 if (names.empty()) {
2744 return OK;
2745 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002746 bool firstIteration = true;
2747 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002748 const IntfCache &intfCache = GetIntfCache(name);
2749 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002750 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002751 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002752 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
2753 if (streamFormat) {
2754 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
2755 if (streamFormat.value == C2BufferData::GRAPHIC
2756 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
2757 allocatorType = C2Allocator::GRAPHIC;
2758 }
2759
2760 if (type != allocatorType) {
2761 // requested type is not supported at input allocators
2762 ids->clear();
2763 ids->insert(defaultAllocatorId);
2764 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
2765 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
2766 break;
2767 }
2768 }
2769
Wonsik Kimffb889a2020-05-28 11:32:25 -07002770 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002771 if (firstIteration) {
2772 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002773 if (allocators && allocators.flexCount() > 0) {
2774 ids->insert(allocators.m.values,
2775 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002776 }
2777 if (ids->empty()) {
2778 // The component does not advertise allocators. Use default.
2779 ids->insert(defaultAllocatorId);
2780 }
2781 continue;
2782 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002783 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002784 if (allocators && allocators.flexCount() > 0) {
2785 filtered = true;
2786 for (auto it = ids->begin(); it != ids->end(); ) {
2787 bool found = false;
2788 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2789 if (allocators.m.values[j] == *it) {
2790 found = true;
2791 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002792 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002793 }
2794 if (found) {
2795 ++it;
2796 } else {
2797 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002798 }
2799 }
2800 }
2801 if (!filtered) {
2802 // The component does not advertise supported allocators. Use default.
2803 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2804 if (ids->size() != (containsDefault ? 1 : 0)) {
2805 ids->clear();
2806 if (containsDefault) {
2807 ids->insert(defaultAllocatorId);
2808 }
2809 }
2810 }
2811 }
2812 // Finally, filter with pool masks
2813 for (auto it = ids->begin(); it != ids->end(); ) {
2814 if ((poolMask >> *it) & 1) {
2815 ++it;
2816 } else {
2817 it = ids->erase(it);
2818 }
2819 }
2820 return OK;
2821}
2822
2823static status_t CalculateMinMaxUsage(
2824 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2825 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2826 *minUsage = 0;
2827 *maxUsage = ~0ull;
2828 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002829 const IntfCache &intfCache = GetIntfCache(name);
2830 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002831 continue;
2832 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002833 const C2FieldSupportedValuesQuery &usageSupportedValues =
2834 intfCache.getUsageSupportedValues();
2835 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002836 continue;
2837 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002838 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002839 if (supported.type != C2FieldSupportedValues::FLAGS) {
2840 continue;
2841 }
2842 if (supported.values.empty()) {
2843 *maxUsage = 0;
2844 continue;
2845 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08002846 if (supported.values.size() > 1) {
2847 *minUsage |= supported.values[1].u64;
2848 } else {
2849 *minUsage |= supported.values[0].u64;
2850 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002851 int64_t currentMaxUsage = 0;
2852 for (const C2Value::Primitive &flags : supported.values) {
2853 currentMaxUsage |= flags.u64;
2854 }
2855 *maxUsage &= currentMaxUsage;
2856 }
2857 return OK;
2858}
2859
2860// static
2861status_t CCodec::CanFetchLinearBlock(
2862 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002863 for (const std::string &name : names) {
2864 const IntfCache &intfCache = GetIntfCache(name);
2865 if (intfCache.initCheck() != OK) {
2866 continue;
2867 }
2868 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2869 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2870 *isCompatible = false;
2871 return OK;
2872 }
2873 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002874 std::set<C2Allocator::id_t> allocators;
2875 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2876 if (allocators.empty()) {
2877 *isCompatible = false;
2878 return OK;
2879 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002880
2881 uint64_t minUsage = 0;
2882 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002883 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002884 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002885 *isCompatible = ((maxUsage & minUsage) == minUsage);
2886 return OK;
2887}
2888
2889static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2890 static std::mutex sMutex{};
2891 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2892 std::unique_lock<std::mutex> lock{sMutex};
2893 std::shared_ptr<C2BlockPool> pool;
2894 auto it = sPools.find(allocId);
2895 if (it == sPools.end()) {
2896 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2897 if (err == OK) {
2898 sPools.emplace(allocId, pool);
2899 } else {
2900 pool.reset();
2901 }
2902 } else {
2903 pool = it->second;
2904 }
2905 return pool;
2906}
2907
2908// static
2909std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2910 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002911 std::set<C2Allocator::id_t> allocators;
2912 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2913 if (allocators.empty()) {
2914 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2915 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002916
2917 uint64_t minUsage = 0;
2918 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002919 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002920 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002921 if ((maxUsage & minUsage) != minUsage) {
2922 allocators.clear();
2923 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2924 }
2925 std::shared_ptr<C2LinearBlock> block;
2926 for (C2Allocator::id_t allocId : allocators) {
2927 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2928 if (!pool) {
2929 continue;
2930 }
2931 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2932 if (err != C2_OK || !block) {
2933 block.reset();
2934 continue;
2935 }
2936 break;
2937 }
2938 return block;
2939}
2940
2941// static
2942status_t CCodec::CanFetchGraphicBlock(
2943 const std::vector<std::string> &names, bool *isCompatible) {
2944 uint64_t minUsage = 0;
2945 uint64_t maxUsage = ~0ull;
2946 std::set<C2Allocator::id_t> allocators;
2947 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2948 if (allocators.empty()) {
2949 *isCompatible = false;
2950 return OK;
2951 }
2952 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2953 *isCompatible = ((maxUsage & minUsage) == minUsage);
2954 return OK;
2955}
2956
2957// static
2958std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2959 int32_t width,
2960 int32_t height,
2961 int32_t format,
2962 uint64_t usage,
2963 const std::vector<std::string> &names) {
2964 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2965 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2966 ALOGD("Unrecognized pixel format: %d", format);
2967 return nullptr;
2968 }
2969 uint64_t minUsage = 0;
2970 uint64_t maxUsage = ~0ull;
2971 std::set<C2Allocator::id_t> allocators;
2972 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2973 if (allocators.empty()) {
2974 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2975 }
2976 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2977 minUsage |= usage;
2978 if ((maxUsage & minUsage) != minUsage) {
2979 allocators.clear();
2980 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2981 }
2982 std::shared_ptr<C2GraphicBlock> block;
2983 for (C2Allocator::id_t allocId : allocators) {
2984 std::shared_ptr<C2BlockPool> pool;
2985 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2986 if (err != C2_OK || !pool) {
2987 continue;
2988 }
2989 err = pool->fetchGraphicBlock(
2990 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2991 if (err != C2_OK || !block) {
2992 block.reset();
2993 continue;
2994 }
2995 break;
2996 }
2997 return block;
2998}
2999
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003000} // namespace android