blob: 7bf4dccc389109dccfa970b293951c48ed94bb79 [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>
Harish Mahendrakarf6b3e5e2024-03-21 21:04:28 +000043#include <media/stagefright/foundation/AUtils.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070044#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
45#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070046#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080047#include <media/stagefright/BufferProducerWrapper.h>
48#include <media/stagefright/MediaCodecConstants.h>
Songyue Han1e6769b2023-08-30 18:09:27 +000049#include <media/stagefright/MediaCodecMetricsConstants.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080050#include <media/stagefright/PersistentSurface.h>
Brian Lindahlff74e9d2023-07-20 14:44:04 -060051#include <media/stagefright/RenderedFrameInfo.h>
ted.sun765db4d2020-06-23 14:03:41 +080052#include <utils/NativeHandle.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080053
Sungtak Lee64c9d932024-03-26 03:46:53 +000054#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080055#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070056#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080057#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080058#include "InputSurfaceWrapper.h"
59
60extern "C" android::PersistentSurface *CreateInputSurface();
61
62namespace android {
63
64using namespace std::chrono_literals;
65using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
66using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080067using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080068
Wonsik Kim9917d4a2019-10-24 12:56:38 -070069typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070070typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070071
Pawin Vongmasa36653902018-11-15 00:10:25 -080072namespace {
73
74class CCodecWatchdog : public AHandler {
75private:
76 enum {
77 kWhatWatch,
78 };
79 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
80
81public:
82 static sp<CCodecWatchdog> getInstance() {
83 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
84 static std::once_flag flag;
85 // Call Init() only once.
86 std::call_once(flag, Init, instance);
87 return instance;
88 }
89
90 ~CCodecWatchdog() = default;
91
92 void watch(sp<CCodec> codec) {
93 bool shouldPost = false;
94 {
95 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
96 // If a watch message is in flight, piggy-back this instance as well.
97 // Otherwise, post a new watch message.
98 shouldPost = codecs->empty();
99 codecs->emplace(codec);
100 }
101 if (shouldPost) {
102 ALOGV("posting watch message");
103 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
104 }
105 }
106
107protected:
108 void onMessageReceived(const sp<AMessage> &msg) {
109 switch (msg->what()) {
110 case kWhatWatch: {
111 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
112 ALOGV("watch for %zu codecs", codecs->size());
113 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
114 sp<CCodec> codec = it->promote();
115 if (codec == nullptr) {
116 continue;
117 }
118 codec->initiateReleaseIfStuck();
119 }
120 codecs->clear();
121 break;
122 }
123
124 default: {
125 TRESPASS("CCodecWatchdog: unrecognized message");
126 }
127 }
128 }
129
130private:
131 CCodecWatchdog() : mLooper(new ALooper) {}
132
133 static void Init(const sp<CCodecWatchdog> &thiz) {
134 ALOGV("Init");
135 thiz->mLooper->setName("CCodecWatchdog");
136 thiz->mLooper->registerHandler(thiz);
137 thiz->mLooper->start();
138 }
139
140 sp<ALooper> mLooper;
141
142 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
143};
144
145class C2InputSurfaceWrapper : public InputSurfaceWrapper {
146public:
147 explicit C2InputSurfaceWrapper(
148 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
149 mSurface(surface) {
150 }
151
152 ~C2InputSurfaceWrapper() override = default;
153
154 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
155 if (mConnection != nullptr) {
156 return ALREADY_EXISTS;
157 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800158 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800159 }
160
161 void disconnect() override {
162 if (mConnection != nullptr) {
163 mConnection->disconnect();
164 mConnection = nullptr;
165 }
166 }
167
168 status_t start() override {
169 // InputSurface does not distinguish started state
170 return OK;
171 }
172
173 status_t signalEndOfInputStream() override {
174 C2InputSurfaceEosTuning eos(true);
175 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800176 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800177 if (err != C2_OK) {
178 return UNKNOWN_ERROR;
179 }
180 return OK;
181 }
182
183 status_t configure(Config &config __unused) {
184 // TODO
185 return OK;
186 }
187
188private:
189 std::shared_ptr<Codec2Client::InputSurface> mSurface;
190 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
191};
192
193class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
194public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700195 typedef hardware::media::omx::V1_0::Status OmxStatus;
196
Pawin Vongmasa36653902018-11-15 00:10:25 -0800197 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700198 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800199 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700200 uint32_t height,
201 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800202 : mSource(source), mWidth(width), mHeight(height) {
203 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700204 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800205 }
206 ~GraphicBufferSourceWrapper() override = default;
207
208 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
209 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700210 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800211 mNode->setFrameSize(mWidth, mHeight);
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700212 // Usage is queried during configure(), so setting it beforehand.
Sungtak Lee0cd4fbc2023-02-02 00:59:01 +0000213 // 64 bit set parameter is existing only in C2OMXNode.
214 OMX_U64 usage64 = mConfig.mUsage;
215 status_t res = mNode->setParameter(
216 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits64,
217 &usage64, sizeof(usage64));
218
219 if (res != OK) {
220 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
221 (void)mNode->setParameter(
222 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
223 &usage, sizeof(usage));
224 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700225
Yanqiang Fanc56f3e62021-09-28 16:54:07 +0800226 return GetStatus(mSource->configure(
227 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800228 }
229
230 void disconnect() override {
231 if (mNode == nullptr) {
232 return;
233 }
234 sp<IOMXBufferSource> source = mNode->getSource();
235 if (source == nullptr) {
236 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
237 return;
238 }
239 source->onOmxIdle();
240 source->onOmxLoaded();
241 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700242 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800243 }
244
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700245 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
246 if (status.isOk()) {
247 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
248 } else if (status.isDeadObject()) {
249 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800250 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700251 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800252 }
253
254 status_t start() override {
255 sp<IOMXBufferSource> source = mNode->getSource();
256 if (source == nullptr) {
257 return NO_INIT;
258 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900259
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800260 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800261 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900262
Wonsik Kim34d66012021-03-01 16:40:33 -0800263 OMX_PARAM_PORTDEFINITIONTYPE param;
264 param.nPortIndex = kPortIndexInput;
265 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
266 &param, sizeof(param));
267 if (err == OK) {
268 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900269 }
270
271 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800272 source->onInputBufferAdded(i);
273 }
274
275 source->onOmxExecuting();
276 return OK;
277 }
278
279 status_t signalEndOfInputStream() override {
280 return GetStatus(mSource->signalEndOfInputStream());
281 }
282
283 status_t configure(Config &config) {
284 std::stringstream status;
285 status_t err = OK;
286
287 // handle each configuration granually, in case we need to handle part of the configuration
288 // elsewhere
289
290 // TRICKY: we do not unset frame delay repeating
291 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
292 int64_t us = 1e6 / config.mMinFps + 0.5;
293 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
294 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
295 if (res != OK) {
296 status << " (=> " << asString(res) << ")";
297 err = res;
298 }
299 mConfig.mMinFps = config.mMinFps;
300 }
301
302 // pts gap
303 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
304 if (mNode != nullptr) {
305 OMX_PARAM_U32TYPE ptrGapParam = {};
306 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700307 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800308 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
309 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700310 // float -> uint32_t is undefined if the value is negative.
311 // First convert to int32_t to ensure the expected behavior.
312 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800313 (void)mNode->setParameter(
314 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
315 &ptrGapParam, sizeof(ptrGapParam));
316 }
317 }
318
319 // max fps
320 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700321 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800322 && config.mMaxFps != mConfig.mMaxFps) {
323 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
324 status << " maxFps=" << config.mMaxFps;
325 if (res != OK) {
326 status << " (=> " << asString(res) << ")";
327 err = res;
328 }
329 mConfig.mMaxFps = config.mMaxFps;
330 }
331
332 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
333 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
334 status << " timeOffset " << config.mTimeOffsetUs << "us";
335 if (res != OK) {
336 status << " (=> " << asString(res) << ")";
337 err = res;
338 }
339 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
340 }
341
342 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
343 status_t res =
344 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
345 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
346 if (res != OK) {
347 status << " (=> " << asString(res) << ")";
348 err = res;
349 }
350 mConfig.mCaptureFps = config.mCaptureFps;
351 mConfig.mCodedFps = config.mCodedFps;
352 }
353
354 if (config.mStartAtUs != mConfig.mStartAtUs
355 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
356 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
357 status << " start at " << config.mStartAtUs << "us";
358 if (res != OK) {
359 status << " (=> " << asString(res) << ")";
360 err = res;
361 }
362 mConfig.mStartAtUs = config.mStartAtUs;
363 mConfig.mStopped = config.mStopped;
364 }
365
366 // suspend-resume
367 if (config.mSuspended != mConfig.mSuspended) {
368 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
369 status << " " << (config.mSuspended ? "suspend" : "resume")
370 << " at " << config.mSuspendAtUs << "us";
371 if (res != OK) {
372 status << " (=> " << asString(res) << ")";
373 err = res;
374 }
375 mConfig.mSuspended = config.mSuspended;
376 mConfig.mSuspendAtUs = config.mSuspendAtUs;
377 }
378
379 if (config.mStopped != mConfig.mStopped && config.mStopped) {
380 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
381 status << " stop at " << config.mStopAtUs << "us";
382 if (res != OK) {
383 status << " (=> " << asString(res) << ")";
384 err = res;
385 } else {
386 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700387 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
388 [&res, &delayUs = config.mInputDelayUs](
389 auto status, auto stopTimeOffsetUs) {
390 res = static_cast<status_t>(status);
391 delayUs = stopTimeOffsetUs;
392 });
393 if (!trans.isOk()) {
394 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
395 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800396 if (res != OK) {
397 status << " (=> " << asString(res) << ")";
398 } else {
399 status << "=" << config.mInputDelayUs << "us";
400 }
401 mConfig.mInputDelayUs = config.mInputDelayUs;
402 }
403 mConfig.mStopAtUs = config.mStopAtUs;
404 mConfig.mStopped = config.mStopped;
405 }
406
407 // color aspects (android._color-aspects)
408
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700409 // consumer usage is queried earlier.
410
Wonsik Kima1335e12021-04-22 16:28:29 -0700411 // priority
412 if (mConfig.mPriority != config.mPriority) {
413 if (config.mPriority != INT_MAX) {
414 mNode->setPriority(config.mPriority);
415 }
416 mConfig.mPriority = config.mPriority;
417 }
418
Wonsik Kimbd557932019-07-02 15:51:20 -0700419 if (status.str().empty()) {
420 ALOGD("ISConfig not changed");
421 } else {
422 ALOGD("ISConfig%s", status.str().c_str());
423 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800424 return err;
425 }
426
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700427 void onInputBufferDone(c2_cntr64_t index) override {
428 mNode->onInputBufferDone(index);
429 }
430
Wonsik Kim673dd192021-01-29 14:58:12 -0800431 android_dataspace getDataspace() override {
432 return mNode->getDataspace();
433 }
434
Songyue Hanad01f6a2023-08-17 05:45:35 +0000435 uint32_t getPixelFormat() override {
436 return mNode->getPixelFormat();
437 }
438
Pawin Vongmasa36653902018-11-15 00:10:25 -0800439private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700440 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800441 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700442 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800443 uint32_t mWidth;
444 uint32_t mHeight;
445 Config mConfig;
446};
447
448class Codec2ClientInterfaceWrapper : public C2ComponentStore {
449 std::shared_ptr<Codec2Client> mClient;
450
451public:
452 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
453 : mClient(client) { }
454
455 virtual ~Codec2ClientInterfaceWrapper() = default;
456
457 virtual c2_status_t config_sm(
458 const std::vector<C2Param *> &params,
459 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
460 return mClient->config(params, C2_MAY_BLOCK, failures);
461 };
462
463 virtual c2_status_t copyBuffer(
464 std::shared_ptr<C2GraphicBuffer>,
465 std::shared_ptr<C2GraphicBuffer>) {
466 return C2_OMITTED;
467 }
468
469 virtual c2_status_t createComponent(
470 C2String, std::shared_ptr<C2Component> *const component) {
471 component->reset();
472 return C2_OMITTED;
473 }
474
475 virtual c2_status_t createInterface(
476 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
477 interface->reset();
478 return C2_OMITTED;
479 }
480
481 virtual c2_status_t query_sm(
482 const std::vector<C2Param *> &stackParams,
483 const std::vector<C2Param::Index> &heapParamIndices,
484 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
485 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
486 }
487
488 virtual c2_status_t querySupportedParams_nb(
489 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
490 return mClient->querySupportedParams(params);
491 }
492
493 virtual c2_status_t querySupportedValues_sm(
494 std::vector<C2FieldSupportedValuesQuery> &fields) const {
495 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
496 }
497
498 virtual C2String getName() const {
499 return mClient->getName();
500 }
501
502 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
503 return mClient->getParamReflector();
504 }
505
506 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
507 return std::vector<std::shared_ptr<const C2Component::Traits>>();
508 }
509};
510
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800511void RevertOutputFormatIfNeeded(
512 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
513 // We used to not report changes to these keys to the client.
514 const static std::set<std::string> sIgnoredKeys({
515 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800516 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800517 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800518 KEY_MAX_WIDTH,
519 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800520 "csd-0",
521 "csd-1",
522 "csd-2",
523 });
524 if (currentFormat == oldFormat) {
525 return;
526 }
527 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
528 AMessage::Type type;
529 for (size_t i = diff->countEntries(); i > 0; --i) {
530 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
531 diff->removeEntryAt(i - 1);
532 }
533 }
534 if (diff->countEntries() == 0) {
535 currentFormat = oldFormat;
536 }
537}
538
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700539void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700540 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700541 const sp<AMessage> &outputFormat) {
542 if (mediaType == MIMETYPE_VIDEO_AVC) {
543 // Codec specific data should be SPS and PPS in a single buffer,
544 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
545 // We separate the two and put them into the output format
546 // under the keys "csd-0" and "csd-1".
547
548 unsigned csdIndex = 0;
549
550 const uint8_t *nalStart;
551 size_t nalSize;
552 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
553 sp<ABuffer> csd = new ABuffer(nalSize + 4);
554 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
555 memcpy(csd->data() + 4, nalStart, nalSize);
556
557 outputFormat->setBuffer(
558 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
559
560 ++csdIndex;
561 }
562
563 if (csdIndex != 2) {
564 ALOGW("Expected two NAL units from AVC codec config, but %u found",
565 csdIndex);
566 }
567 } else {
568 // For everything else we just stash the codec specific data into
569 // the output format as a single piece of csd under "csd-0".
570 sp<ABuffer> csd = new ABuffer(size);
571 memcpy(csd->data(), data, size);
572 csd->setRange(0, size);
573 outputFormat->setBuffer("csd-0", csd);
574 }
575}
576
Pawin Vongmasa36653902018-11-15 00:10:25 -0800577} // namespace
578
579// CCodec::ClientListener
580
581struct CCodec::ClientListener : public Codec2Client::Listener {
582
583 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
584
585 virtual void onWorkDone(
586 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800587 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800588 (void)component;
589 sp<CCodec> codec(mCodec.promote());
590 if (!codec) {
591 return;
592 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800593 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800594 }
595
596 virtual void onTripped(
597 const std::weak_ptr<Codec2Client::Component>& component,
598 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
599 ) override {
600 // TODO
601 (void)component;
602 (void)settingResult;
603 }
604
605 virtual void onError(
606 const std::weak_ptr<Codec2Client::Component>& component,
607 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800608 {
609 // Component is only used for reporting as we use a separate listener for each instance
610 std::shared_ptr<Codec2Client::Component> comp = component.lock();
611 if (!comp) {
612 ALOGD("Component died with error: 0x%x", errorCode);
613 } else {
614 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
615 }
616 }
617
618 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800619 // Note: for now we do not propagate the error code to MediaCodec
620 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800621 sp<CCodec> codec(mCodec.promote());
622 if (!codec || !codec->mCallback) {
623 return;
624 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800625 codec->mCallback->onError(
626 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
627 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800628 }
629
630 virtual void onDeath(
631 const std::weak_ptr<Codec2Client::Component>& component) override {
632 { // Log the death of the component.
633 std::shared_ptr<Codec2Client::Component> comp = component.lock();
634 if (!comp) {
635 ALOGE("Codec2 component died.");
636 } else {
637 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
638 }
639 }
640
641 // Report to MediaCodec.
642 sp<CCodec> codec(mCodec.promote());
643 if (!codec || !codec->mCallback) {
644 return;
645 }
646 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
647 }
648
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800649 virtual void onFrameRendered(uint64_t bufferQueueId,
650 int32_t slotId,
651 int64_t timestampNs) override {
652 // TODO: implement
653 (void)bufferQueueId;
654 (void)slotId;
655 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800656 }
657
658 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800659 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800660 sp<CCodec> codec(mCodec.promote());
661 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800662 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800663 }
664 }
665
666private:
667 wp<CCodec> mCodec;
668};
669
670// CCodecCallbackImpl
671
672class CCodecCallbackImpl : public CCodecCallback {
673public:
674 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
675 ~CCodecCallbackImpl() override = default;
676
677 void onError(status_t err, enum ActionCode actionCode) override {
678 mCodec->mCallback->onError(err, actionCode);
679 }
680
681 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
Brian Lindahlff74e9d2023-07-20 14:44:04 -0600682 mCodec->mCallback->onOutputFramesRendered({RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
Pawin Vongmasa36653902018-11-15 00:10:25 -0800683 }
684
Pawin Vongmasa36653902018-11-15 00:10:25 -0800685 void onOutputBuffersChanged() override {
686 mCodec->mCallback->onOutputBuffersChanged();
687 }
688
Guillaume Chelfi5ffbcb32021-04-12 14:23:43 +0200689 void onFirstTunnelFrameReady() override {
690 mCodec->mCallback->onFirstTunnelFrameReady();
691 }
692
Pawin Vongmasa36653902018-11-15 00:10:25 -0800693private:
694 CCodec *mCodec;
695};
696
697// CCodec
698
699CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700700 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
701 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800702}
703
704CCodec::~CCodec() {
705}
706
707std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
708 return mChannel;
709}
710
711status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
712 status_t err = job();
713 if (err != C2_OK) {
714 mCallback->onError(err, ACTION_CODE_FATAL);
715 }
716 return err;
717}
718
719void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
720 auto setAllocating = [this] {
721 Mutexed<State>::Locked state(mState);
722 if (state->get() != RELEASED) {
723 return INVALID_OPERATION;
724 }
725 state->set(ALLOCATING);
726 return OK;
727 };
728 if (tryAndReportOnError(setAllocating) != OK) {
729 return;
730 }
731
732 sp<RefBase> codecInfo;
733 CHECK(msg->findObject("codecInfo", &codecInfo));
734 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
735
736 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
737 allocMsg->setObject("codecInfo", codecInfo);
738 allocMsg->post();
739}
740
741void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
742 if (codecInfo == nullptr) {
743 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
744 return;
745 }
746 ALOGD("allocate(%s)", codecInfo->getCodecName());
747 mClientListener.reset(new ClientListener(this));
748
749 AString componentName = codecInfo->getCodecName();
750 std::shared_ptr<Codec2Client> client;
751
752 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700753 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800754 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800755 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800756 SetPreferredCodec2ComponentStore(
757 std::make_shared<Codec2ClientInterfaceWrapper>(client));
758 }
759
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900760 std::shared_ptr<Codec2Client::Component> comp;
761 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800762 componentName.c_str(),
763 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900764 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800765 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900766 if (status != C2_OK) {
767 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800768 Mutexed<State>::Locked state(mState);
769 state->set(RELEASED);
770 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900771 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800772 state.lock();
773 return;
774 }
775 ALOGI("Created component [%s]", componentName.c_str());
776 mChannel->setComponent(comp);
777 auto setAllocated = [this, comp, client] {
778 Mutexed<State>::Locked state(mState);
779 if (state->get() != ALLOCATING) {
780 state->set(RELEASED);
781 return UNKNOWN_ERROR;
782 }
783 state->set(ALLOCATED);
784 state->comp = comp;
785 mClient = client;
786 return OK;
787 };
788 if (tryAndReportOnError(setAllocated) != OK) {
789 return;
790 }
791
792 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700793 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
794 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800795 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800796 if (err != OK) {
797 ALOGW("Failed to initialize configuration support");
798 // TODO: report error once we complete implementation.
799 }
800 config->queryConfiguration(comp);
801
802 mCallback->onComponentAllocated(componentName.c_str());
803}
804
805void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
806 auto checkAllocated = [this] {
807 Mutexed<State>::Locked state(mState);
808 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
809 };
810 if (tryAndReportOnError(checkAllocated) != OK) {
811 return;
812 }
813
814 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
815 msg->setMessage("format", format);
816 msg->post();
817}
818
819void CCodec::configure(const sp<AMessage> &msg) {
820 std::shared_ptr<Codec2Client::Component> comp;
821 auto checkAllocated = [this, &comp] {
822 Mutexed<State>::Locked state(mState);
823 if (state->get() != ALLOCATED) {
824 state->set(RELEASED);
825 return UNKNOWN_ERROR;
826 }
827 comp = state->comp;
828 return OK;
829 };
830 if (tryAndReportOnError(checkAllocated) != OK) {
831 return;
832 }
833
834 auto doConfig = [msg, comp, this]() -> status_t {
835 AString mime;
836 if (!msg->findString("mime", &mime)) {
837 return BAD_VALUE;
838 }
839
840 int32_t encoder;
841 if (!msg->findInt32("encoder", &encoder)) {
842 encoder = false;
843 }
844
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800845 int32_t flags;
846 if (!msg->findInt32("flags", &flags)) {
847 return BAD_VALUE;
848 }
849
Pawin Vongmasa36653902018-11-15 00:10:25 -0800850 // TODO: read from intf()
851 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
852 return UNKNOWN_ERROR;
853 }
854
855 int32_t storeMeta;
856 if (encoder
857 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
858 && storeMeta != kMetadataBufferTypeInvalid) {
859 if (storeMeta != kMetadataBufferTypeANWBuffer) {
860 ALOGD("Only ANW buffers are supported for legacy metadata mode");
861 return BAD_VALUE;
862 }
863 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
864 }
865
ted.sun765db4d2020-06-23 14:03:41 +0800866 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800867 sp<RefBase> obj;
868 sp<Surface> surface;
869 if (msg->findObject("native-window", &obj)) {
870 surface = static_cast<Surface *>(obj.get());
Sungtak Lee214ce612023-11-01 10:01:13 +0000871 int32_t generation;
872 (void)msg->findInt32("native-window-generation", &generation);
ted.sun765db4d2020-06-23 14:03:41 +0800873 // setup tunneled playback
874 if (surface != nullptr) {
875 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
876 const std::unique_ptr<Config> &config = *configLocked;
877 if ((config->mDomain & Config::IS_DECODER)
878 && (config->mDomain & Config::IS_VIDEO)) {
879 int32_t tunneled;
880 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
881 ALOGI("Configuring TUNNELED video playback.");
882
883 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
884 if (err != OK) {
885 ALOGE("configureTunneledVideoPlayback failed!");
886 return err;
887 }
888 config->mTunneled = true;
889 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +0100890
891 int32_t pushBlankBuffersOnStop = 0;
892 if (msg->findInt32(KEY_PUSH_BLANK_BUFFERS_ON_STOP, &pushBlankBuffersOnStop)) {
893 config->mPushBlankBuffersOnStop = pushBlankBuffersOnStop == 1;
894 }
shuanglong.wang480a8362023-02-17 20:55:51 +0800895 // secure compoment or protected content default with
896 // "push-blank-buffers-on-shutdown" flag
897 if (!config->mPushBlankBuffersOnStop) {
898 int32_t usageProtected;
899 if (comp->getName().find(".secure") != std::string::npos) {
900 config->mPushBlankBuffersOnStop = true;
901 } else if (msg->findInt32("protected", &usageProtected) && usageProtected) {
902 config->mPushBlankBuffersOnStop = true;
903 }
904 }
ted.sun765db4d2020-06-23 14:03:41 +0800905 }
906 }
Sungtak Lee214ce612023-11-01 10:01:13 +0000907 setSurface(surface, (uint32_t)generation);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800908 }
909
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700910 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
911 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800912 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800913 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
914 ALOGD("[%s] buffers are %sbound to CCodec for this session",
915 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800916
Wonsik Kim1114eea2019-02-25 14:35:24 -0800917 // Enforce required parameters
918 int32_t i32;
919 float flt;
920 if (config->mDomain & Config::IS_AUDIO) {
921 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
922 ALOGD("sample rate is missing, which is required for audio components.");
923 return BAD_VALUE;
924 }
925 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
926 ALOGD("channel count is missing, which is required for audio components.");
927 return BAD_VALUE;
928 }
929 if ((config->mDomain & Config::IS_ENCODER)
930 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
931 && !msg->findInt32(KEY_BIT_RATE, &i32)
932 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
933 ALOGD("bitrate is missing, which is required for audio encoders.");
934 return BAD_VALUE;
935 }
936 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800937 int32_t width = 0;
938 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800939 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800940 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800941 ALOGD("width is missing, which is required for image/video components.");
942 return BAD_VALUE;
943 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800944 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800945 ALOGD("height is missing, which is required for image/video components.");
946 return BAD_VALUE;
947 }
948 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700949 int32_t mode = BITRATE_MODE_VBR;
950 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700951 if (!msg->findInt32(KEY_QUALITY, &i32)) {
952 ALOGD("quality is missing, which is required for video encoders in CQ.");
953 return BAD_VALUE;
954 }
955 } else {
956 if (!msg->findInt32(KEY_BIT_RATE, &i32)
957 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
958 ALOGD("bitrate is missing, which is required for video encoders.");
959 return BAD_VALUE;
960 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800961 }
962 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
963 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
964 ALOGD("I frame interval is missing, which is required for video encoders.");
965 return BAD_VALUE;
966 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700967 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
968 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
969 ALOGD("frame rate is missing, which is required for video encoders.");
970 return BAD_VALUE;
971 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800972 }
973 }
974
Pawin Vongmasa36653902018-11-15 00:10:25 -0800975 /*
976 * Handle input surface configuration
977 */
978 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
979 && (config->mDomain & Config::IS_ENCODER)) {
980 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
981 {
982 config->mISConfig->mMinFps = 0;
983 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800984 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800985 config->mISConfig->mMinFps = 1e6 / value;
986 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700987 if (!msg->findFloat(
988 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
989 config->mISConfig->mMaxFps = -1;
990 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800991 config->mISConfig->mMinAdjustedFps = 0;
992 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800993 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800994 if (value < 0 && value >= INT32_MIN) {
995 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700996 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800997 } else if (value > 0 && value <= INT32_MAX) {
998 config->mISConfig->mMinAdjustedFps = 1e6 / value;
999 }
1000 }
1001 }
1002
1003 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -07001004 bool captureFpsFound = false;
1005 double timeLapseFps;
1006 float captureRate;
1007 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
1008 config->mISConfig->mCaptureFps = timeLapseFps;
1009 captureFpsFound = true;
1010 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
1011 config->mISConfig->mCaptureFps = captureRate;
1012 captureFpsFound = true;
1013 }
1014 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001015 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
1016 }
1017 }
1018
1019 {
1020 config->mISConfig->mSuspended = false;
1021 config->mISConfig->mSuspendAtUs = -1;
1022 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001023 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001024 config->mISConfig->mSuspended = true;
1025 }
1026 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001027 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -07001028 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001029 }
1030
1031 /*
1032 * Handle desired color format.
1033 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001034 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001035 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001036 int32_t format = 0;
1037 // Query vendor format for Flexible YUV
1038 std::vector<std::unique_ptr<C2Param>> heapParams;
1039 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
Wonsik Kim50811882022-04-28 15:57:27 -07001040 int vendorSdkVersion = base::GetIntProperty(
1041 "ro.vendor.build.version.sdk", android_get_device_api_level());
guochuang709b48b2022-10-25 20:40:42 +08001042 if (mClient->query(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001043 {},
1044 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1045 C2_MAY_BLOCK,
1046 &heapParams) == C2_OK
1047 && heapParams.size() == 1u) {
1048 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1049 heapParams[0].get());
1050 } else {
1051 pixelFormatInfo = nullptr;
1052 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001053 // bit depth -> format
1054 std::map<uint32_t, uint32_t> flexPixelFormat;
1055 std::map<uint32_t, uint32_t> flexPlanarPixelFormat;
1056 std::map<uint32_t, uint32_t> flexSemiPlanarPixelFormat;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001057 if (pixelFormatInfo && *pixelFormatInfo) {
1058 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1059 const C2FlexiblePixelFormatDescriptorStruct &desc =
1060 pixelFormatInfo->m.values[i];
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001061 if (desc.subsampling != C2Color::YUV_420
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001062 // TODO(b/180076105): some device report wrong layout
1063 // || desc.layout == C2Color::INTERLEAVED_PACKED
1064 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1065 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1066 continue;
1067 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001068 if (flexPixelFormat.count(desc.bitDepth) == 0) {
1069 flexPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001070 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001071 if (desc.layout == C2Color::PLANAR_PACKED
1072 && flexPlanarPixelFormat.count(desc.bitDepth) == 0) {
1073 flexPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001074 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001075 if (desc.layout == C2Color::SEMIPLANAR_PACKED
1076 && flexSemiPlanarPixelFormat.count(desc.bitDepth) == 0) {
1077 flexSemiPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001078 }
1079 }
1080 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001081 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001082 // Also handle default color format (encoders require color format, so this is only
1083 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001084 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001085 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001086 const char *prefix = "";
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001087 if (flexSemiPlanarPixelFormat.count(8) != 0) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001088 format = COLOR_FormatYUV420SemiPlanar;
1089 prefix = "semi-";
1090 } else {
1091 format = COLOR_FormatYUV420Planar;
1092 }
1093 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1094 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001095 } else {
1096 format = COLOR_FormatSurface;
1097 }
1098 defaultColorFormat = format;
1099 }
1100 } else {
1101 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001102 if (vendorSdkVersion < __ANDROID_API_S__ &&
Taehwan Kim43e715d2022-09-22 12:04:59 +09001103 (format == COLOR_FormatYUV420Planar ||
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001104 format == COLOR_FormatYUV420PackedPlanar ||
1105 format == COLOR_FormatYUV420SemiPlanar ||
1106 format == COLOR_FormatYUV420PackedSemiPlanar)) {
1107 // pre-S framework used to map these color formats into YV12.
1108 // Codecs from older vendor partition may be relying on
1109 // this assumption.
1110 format = HAL_PIXEL_FORMAT_YV12;
1111 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001112 switch (format) {
1113 case COLOR_FormatYUV420Flexible:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001114 format = COLOR_FormatYUV420Planar;
1115 if (flexPixelFormat.count(8) != 0) {
1116 format = flexPixelFormat[8];
1117 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001118 break;
1119 case COLOR_FormatYUV420Planar:
1120 case COLOR_FormatYUV420PackedPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001121 if (flexPlanarPixelFormat.count(8) != 0) {
1122 format = flexPlanarPixelFormat[8];
1123 } else if (flexPixelFormat.count(8) != 0) {
1124 format = flexPixelFormat[8];
1125 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001126 break;
1127 case COLOR_FormatYUV420SemiPlanar:
1128 case COLOR_FormatYUV420PackedSemiPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001129 if (flexSemiPlanarPixelFormat.count(8) != 0) {
1130 format = flexSemiPlanarPixelFormat[8];
1131 } else if (flexPixelFormat.count(8) != 0) {
1132 format = flexPixelFormat[8];
1133 }
1134 break;
1135 case COLOR_FormatYUVP010:
1136 format = COLOR_FormatYUVP010;
1137 if (flexSemiPlanarPixelFormat.count(10) != 0) {
1138 format = flexSemiPlanarPixelFormat[10];
1139 } else if (flexPixelFormat.count(10) != 0) {
1140 format = flexPixelFormat[10];
1141 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001142 break;
1143 default:
1144 // No-op
1145 break;
1146 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001147 }
1148 }
1149
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001150 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001151 msg->setInt32("android._color-format", format);
1152 }
1153 }
1154
Wonsik Kim77e97c72021-01-20 10:33:22 -08001155 /*
1156 * Handle dataspace
1157 */
1158 int32_t usingRecorder;
1159 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1160 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1161 int32_t width, height;
1162 if (msg->findInt32("width", &width)
1163 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001164 ColorAspects aspects;
1165 getColorAspectsFromFormat(msg, aspects);
1166 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001167 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001168 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1169 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001170 }
1171 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1172 ALOGD("setting dataspace to %x", dataSpace);
1173 }
1174
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001175 int32_t subscribeToAllVendorParams;
1176 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1177 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1178 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1179 }
1180 }
1181
Pawin Vongmasa36653902018-11-15 00:10:25 -08001182 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001183 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1184 // the behavior here.
1185 sp<AMessage> sdkParams = msg;
1186 int32_t videoBitrate;
1187 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1188 sdkParams = msg->dup();
1189 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1190 }
ted.sun765db4d2020-06-23 14:03:41 +08001191 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001192 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001193 if (err != OK) {
1194 ALOGW("failed to convert configuration to c2 params");
1195 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001196
1197 int32_t maxBframes = 0;
1198 if ((config->mDomain & Config::IS_ENCODER)
1199 && (config->mDomain & Config::IS_VIDEO)
1200 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1201 && maxBframes > 0) {
1202 std::unique_ptr<C2StreamGopTuning::output> gop =
1203 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1204 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1205 gop->m.values[1] = {
1206 C2Config::picture_type_t(P_FRAME | B_FRAME),
1207 uint32_t(maxBframes)
1208 };
1209 configUpdate.push_back(std::move(gop));
1210 }
1211
Ray Essicka0ae6972021-03-10 19:40:01 -08001212 if ((config->mDomain & Config::IS_ENCODER)
1213 && (config->mDomain & Config::IS_VIDEO)) {
1214 // we may not use all 3 of these entries
1215 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1216 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1217 0u /* stream */);
1218
1219 int ix = 0;
1220
1221 int32_t iMax = INT32_MAX;
1222 int32_t iMin = INT32_MIN;
1223 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1224 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1225 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1226 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1227 }
1228
1229 int32_t pMax = INT32_MAX;
1230 int32_t pMin = INT32_MIN;
1231 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1232 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1233 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1234 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1235 }
1236
1237 int32_t bMax = INT32_MAX;
1238 int32_t bMin = INT32_MIN;
1239 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1240 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1241 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1242 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1243 }
1244
1245 // adjust to reflect actual use.
1246 qp->setFlexCount(ix);
1247
1248 configUpdate.push_back(std::move(qp));
1249 }
1250
Wonsik Kima1335e12021-04-22 16:28:29 -07001251 int32_t background = 0;
1252 if ((config->mDomain & Config::IS_VIDEO)
1253 && msg->findInt32("android._background-mode", &background)
1254 && background) {
1255 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1256 if (config->mISConfig) {
1257 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1258 }
1259 }
1260
Pawin Vongmasa36653902018-11-15 00:10:25 -08001261 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1262 if (err != OK) {
1263 ALOGW("failed to configure c2 params");
1264 return err;
1265 }
1266
1267 std::vector<std::unique_ptr<C2Param>> params;
1268 C2StreamUsageTuning::input usage(0u, 0u);
1269 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001270 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001271
Wonsik Kim3baecda2021-02-07 22:19:56 -08001272 C2Param::Index colorAspectsRequestIndex =
1273 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001274 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001275 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001276 };
Chaejung Lim86c22dc2021-12-23 00:41:05 -08001277 int32_t colorTransferRequest = 0;
1278 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1279 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1280 colorTransferRequest = 0;
1281 }
1282 c2_status_t c2err = C2_OK;
1283 if (colorTransferRequest != 0) {
1284 c2err = comp->query(
1285 { &usage, &maxInputSize, &prepend },
1286 indices,
1287 C2_DONT_BLOCK,
1288 &params);
1289 } else {
1290 c2err = comp->query(
1291 { &usage, &maxInputSize, &prepend },
1292 {},
1293 C2_DONT_BLOCK,
1294 &params);
1295 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001296 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1297 ALOGE("Failed to query component interface: %d", c2err);
1298 return UNKNOWN_ERROR;
1299 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001300 if (usage) {
1301 if (usage.value & C2MemoryUsage::CPU_READ) {
1302 config->mInputFormat->setInt32("using-sw-read-often", true);
1303 }
1304 if (config->mISConfig) {
1305 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1306 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1307 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001308 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001309 }
1310
1311 // NOTE: we don't blindly use client specified input size if specified as clients
1312 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1313 // client specified size is only used to ask for bigger buffers than component suggested
1314 // size.
1315 int32_t clientInputSize = 0;
1316 bool clientSpecifiedInputSize =
1317 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1318 // TEMP: enforce minimum buffer size of 1MB for video decoders
1319 // and 16K / 4K for audio encoders/decoders
1320 if (maxInputSize.value == 0) {
1321 if (config->mDomain & Config::IS_AUDIO) {
1322 maxInputSize.value = encoder ? 16384 : 4096;
1323 } else if (!encoder) {
1324 maxInputSize.value = 1048576u;
1325 }
1326 }
1327
1328 // verify that CSD fits into this size (if defined)
1329 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1330 sp<ABuffer> csd;
1331 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1332 if (csd && csd->size() > maxInputSize.value) {
1333 maxInputSize.value = csd->size();
1334 }
1335 }
1336 }
1337
1338 // TODO: do this based on component requiring linear allocator for input
1339 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1340 if (clientSpecifiedInputSize) {
1341 // Warn that we're overriding client's max input size if necessary.
1342 if ((uint32_t)clientInputSize < maxInputSize.value) {
1343 ALOGD("client requested max input size %d, which is smaller than "
1344 "what component recommended (%u); overriding with component "
1345 "recommendation.", clientInputSize, maxInputSize.value);
1346 ALOGW("This behavior is subject to change. It is recommended that "
1347 "app developers double check whether the requested "
1348 "max input size is in reasonable range.");
1349 } else {
1350 maxInputSize.value = clientInputSize;
1351 }
1352 }
1353 // Pass max input size on input format to the buffer channel (if supplied by the
1354 // component or by a default)
1355 if (maxInputSize.value) {
1356 config->mInputFormat->setInt32(
1357 KEY_MAX_INPUT_SIZE,
1358 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1359 }
1360 }
1361
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001362 int32_t clientPrepend;
1363 if ((config->mDomain & Config::IS_VIDEO)
1364 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001365 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001366 && clientPrepend
1367 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001368 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001369 return BAD_VALUE;
1370 }
1371
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001372 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001373 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1374 // propagate HDR static info to output format for both encoders and decoders
1375 // if component supports this info, we will update from component, but only the raw port,
1376 // so don't propagate if component already filled it in.
1377 sp<ABuffer> hdrInfo;
1378 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1379 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1380 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1381 }
1382
1383 // Set desired color format from configuration parameter
1384 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001385 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1386 format = defaultColorFormat;
1387 }
1388 if (config->mDomain & Config::IS_ENCODER) {
1389 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001390 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1391 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001392 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001393 } else {
1394 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001395 }
1396 }
1397
1398 // propagate encoder delay and padding to output format
1399 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1400 int delay = 0;
1401 if (msg->findInt32("encoder-delay", &delay)) {
1402 config->mOutputFormat->setInt32("encoder-delay", delay);
1403 }
1404 int padding = 0;
1405 if (msg->findInt32("encoder-padding", &padding)) {
1406 config->mOutputFormat->setInt32("encoder-padding", padding);
1407 }
1408 }
1409
Pawin Vongmasa36653902018-11-15 00:10:25 -08001410 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001411 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001412 int32_t mask;
1413 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1414 if (config->mDomain & Config::IS_ENCODER) {
1415 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1416 } else {
1417 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1418 }
1419 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001420
1421 // set PCM encoding
1422 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1423 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1424 if (encoder) {
1425 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1426 } else {
1427 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1428 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001429 }
1430
Wonsik Kim3baecda2021-02-07 22:19:56 -08001431 std::unique_ptr<C2Param> colorTransferRequestParam;
1432 for (std::unique_ptr<C2Param> &param : params) {
1433 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1434 ALOGI("found color transfer request param");
1435 colorTransferRequestParam = std::move(param);
1436 }
1437 }
Wonsik Kim3baecda2021-02-07 22:19:56 -08001438
1439 if (colorTransferRequest != 0) {
1440 if (colorTransferRequestParam && *colorTransferRequestParam) {
1441 C2StreamColorAspectsInfo::output *info =
1442 static_cast<C2StreamColorAspectsInfo::output *>(
1443 colorTransferRequestParam.get());
1444 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1445 colorTransferRequest = 0;
1446 }
1447 } else {
1448 colorTransferRequest = 0;
1449 }
1450 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1451 }
1452
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001453 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1454 // Need to get stride/vstride
1455 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1456 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1457 // TODO: retrieve these values without allocating a buffer.
1458 // Currently allocating a buffer is necessary to retrieve the layout.
1459 int64_t blockUsage =
1460 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1461 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
Harish Mahendrakarf6b3e5e2024-03-21 21:04:28 +00001462 align(width, 2), align(height, 2), componentColorFormat, blockUsage,
1463 {comp->getName()});
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001464 sp<GraphicBlockBuffer> buffer;
1465 if (block) {
1466 buffer = GraphicBlockBuffer::Allocate(
1467 config->mInputFormat,
1468 block,
1469 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1470 } else {
1471 ALOGD("Failed to allocate a graphic block "
1472 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1473 width, height, pixelFormat, (long long)blockUsage);
1474 // This means that byte buffer mode is not supported in this configuration
1475 // anyway. Skip setting stride/vstride to input format.
1476 }
1477 if (buffer) {
1478 sp<ABuffer> imageData = buffer->getImageData();
1479 MediaImage2 *img = nullptr;
1480 if (imageData && imageData->data()
1481 && imageData->size() >= sizeof(MediaImage2)) {
1482 img = (MediaImage2*)imageData->data();
1483 }
1484 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1485 int32_t stride = img->mPlane[0].mRowInc;
1486 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1487 if (img->mNumPlanes > 1 && stride > 0) {
1488 int64_t offsetDelta =
1489 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1490 if (offsetDelta % stride == 0) {
1491 int32_t vstride = int32_t(offsetDelta / stride);
1492 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1493 } else {
1494 ALOGD("Cannot report accurate slice height: "
1495 "offsetDelta = %lld stride = %d",
1496 (long long)offsetDelta, stride);
1497 }
1498 }
1499 }
1500 }
1501 }
1502 }
1503
Wonsik Kimec585c32021-10-01 01:11:00 -07001504 if (config->mTunneled) {
1505 config->mOutputFormat->setInt32("android._tunneled", 1);
1506 }
1507
Yushin Cho91873b52021-12-21 04:08:35 -08001508 // Convert an encoding statistics level to corresponding encoding statistics
1509 // kinds
1510 int32_t encodingStatisticsLevel = VIDEO_ENCODING_STATISTICS_LEVEL_NONE;
1511 if ((config->mDomain & Config::IS_ENCODER)
1512 && (config->mDomain & Config::IS_VIDEO)
1513 && msg->findInt32(KEY_VIDEO_ENCODING_STATISTICS_LEVEL, &encodingStatisticsLevel)) {
1514 // Higher level include all the enc stats belong to lower level.
1515 switch (encodingStatisticsLevel) {
1516 // case VIDEO_ENCODING_STATISTICS_LEVEL_2: // reserved for the future level 2
1517 // with more enc stat kinds
1518 // Future extended encoding statistics for the level 2 should be added here
1519 case VIDEO_ENCODING_STATISTICS_LEVEL_1:
Wonsik Kimeebab652022-06-02 13:01:55 -07001520 config->subscribeToConfigUpdate(
1521 comp,
1522 {
1523 C2AndroidStreamAverageBlockQuantizationInfo::output::PARAM_TYPE,
1524 C2StreamPictureTypeInfo::output::PARAM_TYPE,
1525 });
Yushin Cho91873b52021-12-21 04:08:35 -08001526 break;
1527 case VIDEO_ENCODING_STATISTICS_LEVEL_NONE:
1528 break;
1529 }
1530 }
1531 ALOGD("encoding statistics level = %d", encodingStatisticsLevel);
1532
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001533 ALOGD("setup formats input: %s",
1534 config->mInputFormat->debugString().c_str());
1535 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001536 config->mOutputFormat->debugString().c_str());
1537 return OK;
1538 };
1539 if (tryAndReportOnError(doConfig) != OK) {
1540 return;
1541 }
1542
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001543 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1544 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001545
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001546 config->queryConfiguration(comp);
1547
Songyue Han1e6769b2023-08-30 18:09:27 +00001548 mMetrics = new AMessage;
1549 mChannel->resetBuffersPixelFormat((config->mDomain & Config::IS_ENCODER) ? true : false);
1550
Pawin Vongmasa36653902018-11-15 00:10:25 -08001551 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1552}
1553
1554void CCodec::initiateCreateInputSurface() {
1555 status_t err = [this] {
1556 Mutexed<State>::Locked state(mState);
1557 if (state->get() != ALLOCATED) {
1558 return UNKNOWN_ERROR;
1559 }
1560 // TODO: read it from intf() properly.
1561 if (state->comp->getName().find("encoder") == std::string::npos) {
1562 return INVALID_OPERATION;
1563 }
1564 return OK;
1565 }();
1566 if (err != OK) {
1567 mCallback->onInputSurfaceCreationFailed(err);
1568 return;
1569 }
1570
1571 (new AMessage(kWhatCreateInputSurface, this))->post();
1572}
1573
Lajos Molnar47118272019-01-31 16:28:04 -08001574sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1575 using namespace android::hardware::media::omx::V1_0;
1576 using namespace android::hardware::media::omx::V1_0::utils;
1577 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1578 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1579 android::sp<IOmx> omx = IOmx::getService();
Sungtak Lee47dcb482022-04-15 10:47:08 -07001580 if (omx == nullptr) {
1581 return nullptr;
1582 }
Lajos Molnar47118272019-01-31 16:28:04 -08001583 typedef android::hardware::graphics::bufferqueue::V1_0::
1584 IGraphicBufferProducer HGraphicBufferProducer;
1585 typedef android::hardware::media::omx::V1_0::
1586 IGraphicBufferSource HGraphicBufferSource;
1587 OmxStatus s;
1588 android::sp<HGraphicBufferProducer> gbp;
1589 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001590
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001591 using ::android::hardware::Return;
1592 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001593 [&s, &gbp, &gbs](
1594 OmxStatus status,
1595 const android::sp<HGraphicBufferProducer>& producer,
1596 const android::sp<HGraphicBufferSource>& source) {
1597 s = status;
1598 gbp = producer;
1599 gbs = source;
1600 });
1601 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001602 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001603 }
1604
1605 return nullptr;
1606}
1607
1608sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1609 sp<PersistentSurface> surface(CreateInputSurface());
1610
1611 if (surface == nullptr) {
1612 surface = CreateOmxInputSurface();
1613 }
1614
1615 return surface;
1616}
1617
Pawin Vongmasa36653902018-11-15 00:10:25 -08001618void CCodec::createInputSurface() {
1619 status_t err;
1620 sp<IGraphicBufferProducer> bufferProducer;
1621
Pawin Vongmasa36653902018-11-15 00:10:25 -08001622 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001623 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001624 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001625 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1626 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001627 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001628 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001629 }
1630
Lajos Molnar47118272019-01-31 16:28:04 -08001631 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001632 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1633 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1634 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001635
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001636 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001637 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1638 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001639 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001640 inputSurface));
1641 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001642 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001643 int32_t width = 0;
1644 (void)outputFormat->findInt32("width", &width);
1645 int32_t height = 0;
1646 (void)outputFormat->findInt32("height", &height);
1647 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001648 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001649 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001650 } else {
1651 ALOGE("Corrupted input surface");
1652 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1653 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001654 }
1655
1656 if (err != OK) {
1657 ALOGE("Failed to set up input surface: %d", err);
1658 mCallback->onInputSurfaceCreationFailed(err);
1659 return;
1660 }
1661
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001662 // Formats can change after setupInputSurface
1663 sp<AMessage> inputFormat;
1664 {
1665 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1666 const std::unique_ptr<Config> &config = *configLocked;
1667 inputFormat = config->mInputFormat;
1668 outputFormat = config->mOutputFormat;
1669 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001670 mCallback->onInputSurfaceCreated(
1671 inputFormat,
1672 outputFormat,
1673 new BufferProducerWrapper(bufferProducer));
1674}
1675
1676status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001677 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1678 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001679 config->mUsingSurface = true;
1680
1681 // we are now using surface - apply default color aspects to input format - as well as
1682 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001683 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001684
1685 // configure dataspace
1686 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
Wonsik Kim66b19552021-08-02 16:07:49 -07001687
1688 // The output format contains app-configured color aspects, and the input format
1689 // has the default color aspects. Use the default for the unspecified params.
1690 ColorAspects inputColorAspects, colorAspects;
1691 getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
1692 getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
1693 if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
1694 colorAspects.mRange = inputColorAspects.mRange;
1695 }
1696 if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
1697 colorAspects.mPrimaries = inputColorAspects.mPrimaries;
1698 }
1699 if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
1700 colorAspects.mTransfer = inputColorAspects.mTransfer;
1701 }
1702 if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
1703 colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
1704 }
1705 android_dataspace dataSpace = getDataSpaceForColorAspects(
1706 colorAspects, /* mayExtend = */ false);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001707 surface->setDataSpace(dataSpace);
Wonsik Kim66b19552021-08-02 16:07:49 -07001708 setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
1709 config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
1710
1711 ALOGD("input format %s to %s",
1712 inputFormatChanged ? "changed" : "unchanged",
1713 config->mInputFormat->debugString().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001714
1715 status_t err = mChannel->setInputSurface(surface);
1716 if (err != OK) {
1717 // undo input format update
1718 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001719 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001720 return err;
1721 }
1722 config->mInputSurface = surface;
1723
1724 if (config->mISConfig) {
1725 surface->configure(*config->mISConfig);
1726 } else {
1727 ALOGD("ISConfig: no configuration");
1728 }
1729
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001730 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001731}
1732
1733void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1734 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1735 msg->setObject("surface", surface);
1736 msg->post();
1737}
1738
1739void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001740 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001741 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001742 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001743 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1744 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001745 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001746 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001747 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001748 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1749 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1750 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1751 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001752 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1753 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1754 if (err != OK) {
1755 ALOGE("Failed to set up input surface: %d", err);
1756 mCallback->onInputSurfaceDeclined(err);
1757 return;
1758 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001759 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001760 int32_t width = 0;
1761 (void)outputFormat->findInt32("width", &width);
1762 int32_t height = 0;
1763 (void)outputFormat->findInt32("height", &height);
1764 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001765 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001766 if (err != OK) {
1767 ALOGE("Failed to set up input surface: %d", err);
1768 mCallback->onInputSurfaceDeclined(err);
1769 return;
1770 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001771 } else {
1772 ALOGE("Failed to set input surface: Corrupted surface.");
1773 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1774 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001775 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001776 // Formats can change after setupInputSurface
1777 sp<AMessage> inputFormat;
1778 {
1779 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1780 const std::unique_ptr<Config> &config = *configLocked;
1781 inputFormat = config->mInputFormat;
1782 outputFormat = config->mOutputFormat;
1783 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001784 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1785}
1786
1787void CCodec::initiateStart() {
1788 auto setStarting = [this] {
1789 Mutexed<State>::Locked state(mState);
1790 if (state->get() != ALLOCATED) {
1791 return UNKNOWN_ERROR;
1792 }
1793 state->set(STARTING);
1794 return OK;
1795 };
1796 if (tryAndReportOnError(setStarting) != OK) {
1797 return;
1798 }
1799
1800 (new AMessage(kWhatStart, this))->post();
1801}
1802
1803void CCodec::start() {
1804 std::shared_ptr<Codec2Client::Component> comp;
1805 auto checkStarting = [this, &comp] {
1806 Mutexed<State>::Locked state(mState);
1807 if (state->get() != STARTING) {
1808 return UNKNOWN_ERROR;
1809 }
1810 comp = state->comp;
1811 return OK;
1812 };
1813 if (tryAndReportOnError(checkStarting) != OK) {
1814 return;
1815 }
1816
1817 c2_status_t err = comp->start();
1818 if (err != C2_OK) {
1819 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1820 ACTION_CODE_FATAL);
1821 return;
1822 }
Wonsik Kimd55ed3b2023-06-22 14:42:17 -07001823
1824 // clear the deadline after the component starts
1825 setDeadline(TimePoint::max(), 0ms, "none");
1826
Pawin Vongmasa36653902018-11-15 00:10:25 -08001827 sp<AMessage> inputFormat;
1828 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001829 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001830 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001831 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001832 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1833 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001834 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001835 // start triggers format dup
1836 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001837 if (config->mInputSurface) {
1838 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001839 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001840 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001841 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001842 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001843 if (err2 != OK) {
1844 mCallback->onError(err2, ACTION_CODE_FATAL);
1845 return;
1846 }
Arun Johnson106fe7a2023-04-26 17:49:43 +00001847
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001848 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001849 if (err2 != OK) {
1850 mCallback->onError(err2, ACTION_CODE_FATAL);
1851 return;
1852 }
1853
1854 auto setRunning = [this] {
1855 Mutexed<State>::Locked state(mState);
1856 if (state->get() != STARTING) {
1857 return UNKNOWN_ERROR;
1858 }
1859 state->set(RUNNING);
1860 return OK;
1861 };
1862 if (tryAndReportOnError(setRunning) != OK) {
1863 return;
1864 }
Arun Johnson5997bb02022-04-01 19:35:44 +00001865
Wonsik Kim34b28b42022-05-20 15:49:32 -07001866 // preparation of input buffers may not succeed due to the lack of
1867 // memory; returning correct error code (NO_MEMORY) as an error allows
1868 // MediaCodec to try reclaim and restart codec gracefully.
1869 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
1870 err2 = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
1871 if (err2 != OK) {
1872 ALOGE("Initial preparation for Input Buffers failed");
1873 mCallback->onError(err2, ACTION_CODE_FATAL);
1874 return;
1875 }
1876
Pawin Vongmasa36653902018-11-15 00:10:25 -08001877 mCallback->onStartCompleted();
1878
Wonsik Kim34b28b42022-05-20 15:49:32 -07001879 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001880}
1881
1882void CCodec::initiateShutdown(bool keepComponentAllocated) {
1883 if (keepComponentAllocated) {
1884 initiateStop();
1885 } else {
1886 initiateRelease();
1887 }
1888}
1889
1890void CCodec::initiateStop() {
1891 {
1892 Mutexed<State>::Locked state(mState);
1893 if (state->get() == ALLOCATED
1894 || state->get() == RELEASED
1895 || state->get() == STOPPING
1896 || state->get() == RELEASING) {
1897 // We're already stopped, released, or doing it right now.
1898 state.unlock();
1899 mCallback->onStopCompleted();
1900 state.lock();
1901 return;
1902 }
1903 state->set(STOPPING);
1904 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001905 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00001906 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
1907 sp<AMessage> stopMessage(new AMessage(kWhatStop, this));
1908 stopMessage->setInt32("pushBlankBuffer", pushBlankBuffer);
1909 stopMessage->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001910}
1911
Sungtak Lee99144332023-01-26 11:03:14 +00001912void CCodec::stop(bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001913 std::shared_ptr<Codec2Client::Component> comp;
1914 {
1915 Mutexed<State>::Locked state(mState);
1916 if (state->get() == RELEASING) {
1917 state.unlock();
1918 // We're already stopped or release is in progress.
1919 mCallback->onStopCompleted();
1920 state.lock();
1921 return;
1922 } else if (state->get() != STOPPING) {
1923 state.unlock();
1924 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1925 state.lock();
1926 return;
1927 }
1928 comp = state->comp;
1929 }
Sungtak Leec0c05962023-10-25 08:14:13 +00001930
1931 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->stop().
1932 // But in the case some HAL implementations hang forever on comp->stop().
1933 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
1934 // completing stop()).
1935 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
1936 // prior to comp->stop().
1937 // See also b/300350761.
Sungtak Lee99144332023-01-26 11:03:14 +00001938 mChannel->stopUseOutputSurface(pushBlankBuffer);
Sungtak Leec0c05962023-10-25 08:14:13 +00001939 status_t err = comp->stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001940 if (err != C2_OK) {
1941 // TODO: convert err into status_t
1942 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1943 }
1944
1945 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001946 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1947 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001948 if (config->mInputSurface) {
1949 config->mInputSurface->disconnect();
1950 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001951 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001952 }
1953 }
1954 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001955 Mutexed<State>::Locked state(mState);
1956 if (state->get() == STOPPING) {
1957 state->set(ALLOCATED);
1958 }
1959 }
1960 mCallback->onStopCompleted();
1961}
1962
1963void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001964 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001965 {
1966 Mutexed<State>::Locked state(mState);
1967 if (state->get() == RELEASED || state->get() == RELEASING) {
1968 // We're already released or doing it right now.
1969 if (sendCallback) {
1970 state.unlock();
1971 mCallback->onReleaseCompleted();
1972 state.lock();
1973 }
1974 return;
1975 }
1976 if (state->get() == ALLOCATING) {
1977 state->set(RELEASING);
1978 // With the altered state allocate() would fail and clean up.
1979 if (sendCallback) {
1980 state.unlock();
1981 mCallback->onReleaseCompleted();
1982 state.lock();
1983 }
1984 return;
1985 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001986 if (state->get() == STARTING
1987 || state->get() == RUNNING
1988 || state->get() == STOPPING) {
1989 // Input surface may have been started, so clean up is needed.
1990 clearInputSurfaceIfNeeded = true;
1991 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001992 state->set(RELEASING);
1993 }
1994
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001995 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001996 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1997 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001998 if (config->mInputSurface) {
1999 config->mInputSurface->disconnect();
2000 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08002001 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002002 }
2003 }
2004
Wonsik Kim936a89c2020-05-08 16:07:50 -07002005 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00002006 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002007 // thiz holds strong ref to this while the thread is running.
2008 sp<CCodec> thiz(this);
Sungtak Lee99144332023-01-26 11:03:14 +00002009 std::thread([thiz, sendCallback, pushBlankBuffer]
2010 { thiz->release(sendCallback, pushBlankBuffer); }).detach();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002011}
2012
Sungtak Lee99144332023-01-26 11:03:14 +00002013void CCodec::release(bool sendCallback, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002014 std::shared_ptr<Codec2Client::Component> comp;
2015 {
2016 Mutexed<State>::Locked state(mState);
2017 if (state->get() == RELEASED) {
2018 if (sendCallback) {
2019 state.unlock();
2020 mCallback->onReleaseCompleted();
2021 state.lock();
2022 }
2023 return;
2024 }
2025 comp = state->comp;
2026 }
Sungtak Leec0c05962023-10-25 08:14:13 +00002027 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->release().
2028 // But in the case some HAL implementations hang forever on comp->release().
2029 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
2030 // completing release()).
2031 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
2032 // prior to comp->release().
2033 // See also b/300350761.
Sungtak Lee99144332023-01-26 11:03:14 +00002034 mChannel->stopUseOutputSurface(pushBlankBuffer);
Sungtak Leec0c05962023-10-25 08:14:13 +00002035 comp->release();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002036
2037 {
2038 Mutexed<State>::Locked state(mState);
2039 state->set(RELEASED);
2040 state->comp.reset();
2041 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002042 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002043 if (sendCallback) {
2044 mCallback->onReleaseCompleted();
2045 }
2046}
2047
Sungtak Lee214ce612023-11-01 10:01:13 +00002048status_t CCodec::setSurface(const sp<Surface> &surface, uint32_t generation) {
Sungtak Lee99144332023-01-26 11:03:14 +00002049 bool pushBlankBuffer = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002050 {
2051 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2052 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002053 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
2054 status_t err = OK;
2055
Wonsik Kim75e22f42021-04-14 23:34:51 -07002056 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002057 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07002058 nativeWindow.get(),
2059 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
2060 if (err != OK) {
2061 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
2062 nativeWindow.get(), config->mSidebandHandle->handle(), err);
2063 return err;
2064 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002065 } else {
2066 // Explicitly reset the sideband handle of the window for
2067 // non-tunneled video in case the window was previously used
2068 // for a tunneled video playback.
2069 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
2070 if (err != OK) {
2071 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
2072 return err;
2073 }
ted.sun765db4d2020-06-23 14:03:41 +08002074 }
Sungtak Lee99144332023-01-26 11:03:14 +00002075 pushBlankBuffer = config->mPushBlankBuffersOnStop;
ted.sun765db4d2020-06-23 14:03:41 +08002076 }
Sungtak Lee214ce612023-11-01 10:01:13 +00002077 return mChannel->setSurface(surface, generation, pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002078}
2079
2080void CCodec::signalFlush() {
2081 status_t err = [this] {
2082 Mutexed<State>::Locked state(mState);
2083 if (state->get() == FLUSHED) {
2084 return ALREADY_EXISTS;
2085 }
2086 if (state->get() != RUNNING) {
2087 return UNKNOWN_ERROR;
2088 }
2089 state->set(FLUSHING);
2090 return OK;
2091 }();
2092 switch (err) {
2093 case ALREADY_EXISTS:
2094 mCallback->onFlushCompleted();
2095 return;
2096 case OK:
2097 break;
2098 default:
2099 mCallback->onError(err, ACTION_CODE_FATAL);
2100 return;
2101 }
2102
2103 mChannel->stop();
2104 (new AMessage(kWhatFlush, this))->post();
2105}
2106
2107void CCodec::flush() {
2108 std::shared_ptr<Codec2Client::Component> comp;
2109 auto checkFlushing = [this, &comp] {
2110 Mutexed<State>::Locked state(mState);
2111 if (state->get() != FLUSHING) {
2112 return UNKNOWN_ERROR;
2113 }
2114 comp = state->comp;
2115 return OK;
2116 };
2117 if (tryAndReportOnError(checkFlushing) != OK) {
2118 return;
2119 }
2120
2121 std::list<std::unique_ptr<C2Work>> flushedWork;
2122 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2123 {
2124 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2125 flushedWork.splice(flushedWork.end(), *queue);
2126 }
2127 if (err != C2_OK) {
2128 // TODO: convert err into status_t
2129 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2130 }
2131
2132 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002133
2134 {
2135 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002136 if (state->get() == FLUSHING) {
2137 state->set(FLUSHED);
2138 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002139 }
2140 mCallback->onFlushCompleted();
2141}
2142
2143void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002144 std::shared_ptr<Codec2Client::Component> comp;
2145 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002146 Mutexed<State>::Locked state(mState);
2147 if (state->get() != FLUSHED) {
2148 return UNKNOWN_ERROR;
2149 }
2150 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002151 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002152 return OK;
2153 };
2154 if (tryAndReportOnError(setResuming) != OK) {
2155 return;
2156 }
2157
Wonsik Kime75a5da2020-02-14 17:29:03 -08002158 {
2159 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2160 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002161 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002162 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002163 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002164 }
2165
Arun Johnson106fe7a2023-04-26 17:49:43 +00002166 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
Arun Johnson326166e2023-07-28 19:11:52 +00002167 status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers, true);
Arun Johnson106fe7a2023-04-26 17:49:43 +00002168 if (err != OK) {
2169 if (err == NO_MEMORY) {
2170 // NO_MEMORY happens here when all the buffers are still
2171 // with the codec. That is not an error as it is momentarily
2172 // and the buffers are send to the client as soon as the codec
2173 // releases them
2174 ALOGI("Resuming with all input buffers still with codec");
2175 } else {
2176 ALOGE("Resume request for Input Buffers failed");
2177 mCallback->onError(err, ACTION_CODE_FATAL);
2178 return;
2179 }
2180 }
2181
2182 // channel start should be called after prepareInitialBuffers
2183 // Calling before can cause a failure during prepare when
2184 // buffers are sent to the client before preparation from onWorkDone
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002185 (void)mChannel->start(nullptr, nullptr, [&]{
2186 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2187 const std::unique_ptr<Config> &config = *configLocked;
2188 return config->mBuffersBoundToCodec;
2189 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002190 {
2191 Mutexed<State>::Locked state(mState);
2192 if (state->get() != RESUMING) {
2193 state.unlock();
2194 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2195 state.lock();
2196 return;
2197 }
2198 state->set(RUNNING);
2199 }
2200
Wonsik Kim34b28b42022-05-20 15:49:32 -07002201 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002202}
2203
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002204void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002205 std::shared_ptr<Codec2Client::Component> comp;
2206 auto checkState = [this, &comp] {
2207 Mutexed<State>::Locked state(mState);
2208 if (state->get() == RELEASED) {
2209 return INVALID_OPERATION;
2210 }
2211 comp = state->comp;
2212 return OK;
2213 };
2214 if (tryAndReportOnError(checkState) != OK) {
2215 return;
2216 }
2217
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002218 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2219 // the behavior here.
2220 sp<AMessage> params = msg;
2221 int32_t bitrate;
2222 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2223 params = msg->dup();
2224 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2225 }
2226
Houxiang Dai5a97b472021-03-22 17:56:04 +08002227 int32_t syncId = 0;
2228 if (params->findInt32("audio-hw-sync", &syncId)
2229 || params->findInt32("hw-av-sync-id", &syncId)) {
2230 configureTunneledVideoPlayback(comp, nullptr, params);
2231 }
2232
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002233 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2234 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002235
2236 /**
2237 * Handle input surface parameters
2238 */
2239 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002240 && (config->mDomain & Config::IS_ENCODER)
2241 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002242 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002243
2244 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2245 config->mISConfig->mStopped = false;
2246 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2247 config->mISConfig->mStopped = true;
2248 }
2249
2250 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002251 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002252 config->mISConfig->mSuspended = value;
2253 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002254 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002255 }
2256
2257 (void)config->mInputSurface->configure(*config->mISConfig);
2258 if (config->mISConfig->mStopped) {
2259 config->mInputFormat->setInt64(
2260 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2261 }
2262 }
2263
2264 std::vector<std::unique_ptr<C2Param>> configUpdate;
2265 (void)config->getConfigUpdateFromSdkParams(
2266 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2267 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2268 // Parameter synchronization is not defined when using input surface. For now, route
2269 // these directly to the component.
2270 if (config->mInputSurface == nullptr
2271 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2272 || comp->getName().find("c2.android.") == 0)) {
2273 mChannel->setParameters(configUpdate);
2274 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002275 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002276 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002277 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002278 }
2279}
2280
2281void CCodec::signalEndOfInputStream() {
2282 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2283}
2284
2285void CCodec::signalRequestIDRFrame() {
2286 std::shared_ptr<Codec2Client::Component> comp;
2287 {
2288 Mutexed<State>::Locked state(mState);
2289 if (state->get() == RELEASED) {
2290 ALOGD("no IDR request sent since component is released");
2291 return;
2292 }
2293 comp = state->comp;
2294 }
2295 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002296 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2297 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002298 std::vector<std::unique_ptr<C2Param>> params;
2299 params.push_back(
2300 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2301 config->setParameters(comp, params, C2_MAY_BLOCK);
2302}
2303
Wonsik Kim874ad382021-03-12 09:59:36 -08002304status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2305 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2306 const std::unique_ptr<Config> &config = *configLocked;
2307 return config->querySupportedParameters(names);
2308}
2309
2310status_t CCodec::describeParameter(
2311 const std::string &name, CodecParameterDescriptor *desc) {
2312 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2313 const std::unique_ptr<Config> &config = *configLocked;
2314 return config->describe(name, desc);
2315}
2316
2317status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2318 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2319 if (!comp) {
2320 return INVALID_OPERATION;
2321 }
2322 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2323 const std::unique_ptr<Config> &config = *configLocked;
2324 return config->subscribeToVendorConfigUpdate(comp, names);
2325}
2326
2327status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2328 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2329 if (!comp) {
2330 return INVALID_OPERATION;
2331 }
2332 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2333 const std::unique_ptr<Config> &config = *configLocked;
2334 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2335}
2336
Wonsik Kimab34ed62019-01-31 15:28:46 -08002337void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002338 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002339 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002340 bool shouldPost = queue->empty();
Wonsik Kimab34ed62019-01-31 15:28:46 -08002341 queue->splice(queue->end(), workItems);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002342 if (shouldPost) {
2343 (new AMessage(kWhatWorkDone, this))->post();
2344 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002345 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002346}
2347
Wonsik Kimab34ed62019-01-31 15:28:46 -08002348void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2349 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002350 if (arrayIndex == 0) {
2351 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002352 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2353 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002354 if (config->mInputSurface) {
2355 config->mInputSurface->onInputBufferDone(frameIndex);
2356 }
2357 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002358}
2359
2360void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2361 TimePoint now = std::chrono::steady_clock::now();
2362 CCodecWatchdog::getInstance()->watch(this);
2363 switch (msg->what()) {
2364 case kWhatAllocate: {
2365 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002366 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002367 sp<RefBase> obj;
2368 CHECK(msg->findObject("codecInfo", &obj));
2369 allocate((MediaCodecInfo *)obj.get());
2370 break;
2371 }
2372 case kWhatConfigure: {
2373 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002374 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002375 sp<AMessage> format;
2376 CHECK(msg->findMessage("format", &format));
2377 configure(format);
2378 break;
2379 }
2380 case kWhatStart: {
2381 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002382 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002383 start();
2384 break;
2385 }
2386 case kWhatStop: {
2387 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002388 setDeadline(now, 1500ms, "stop");
Sungtak Lee99144332023-01-26 11:03:14 +00002389 int32_t pushBlankBuffer;
2390 if (!msg->findInt32("pushBlankBuffer", &pushBlankBuffer)) {
2391 pushBlankBuffer = 0;
2392 }
2393 stop(static_cast<bool>(pushBlankBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002394 break;
2395 }
2396 case kWhatFlush: {
2397 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002398 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002399 flush();
2400 break;
2401 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002402 case kWhatRelease: {
2403 mChannel->release();
2404 mClient.reset();
2405 mClientListener.reset();
2406 break;
2407 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002408 case kWhatCreateInputSurface: {
2409 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002410 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002411 createInputSurface();
2412 break;
2413 }
2414 case kWhatSetInputSurface: {
2415 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002416 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002417 sp<RefBase> obj;
2418 CHECK(msg->findObject("surface", &obj));
2419 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2420 setInputSurface(surface);
2421 break;
2422 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002423 case kWhatWorkDone: {
2424 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002425 bool shouldPost = false;
2426 {
2427 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2428 if (queue->empty()) {
2429 break;
2430 }
2431 work.swap(queue->front());
2432 queue->pop_front();
2433 shouldPost = !queue->empty();
2434 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002435 if (shouldPost) {
2436 (new AMessage(kWhatWorkDone, this))->post();
2437 }
2438
Pawin Vongmasa36653902018-11-15 00:10:25 -08002439 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002440 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002441 sp<AMessage> outputFormat = nullptr;
2442 {
2443 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2444 const std::unique_ptr<Config> &config = *configLocked;
2445 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2446 config->watch<C2StreamInitDataInfo::output>();
2447 if (!work->worklets.empty()
2448 && (work->worklets.front()->output.flags
2449 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002450
Wonsik Kim75e22f42021-04-14 23:34:51 -07002451 // copy buffer info to config
2452 std::vector<std::unique_ptr<C2Param>> updates;
2453 for (const std::unique_ptr<C2Param> &param
2454 : work->worklets.front()->output.configUpdate) {
2455 updates.push_back(C2Param::Copy(*param));
2456 }
2457 unsigned stream = 0;
2458 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2459 work->worklets.front()->output.buffers;
2460 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2461 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2462 // move all info into output-stream #0 domain
2463 updates.emplace_back(
2464 C2Param::CopyAsStream(*info, true /* output */, stream));
2465 }
2466
2467 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2468 // for now only do the first block
2469 if (!blocks.empty()) {
2470 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2471 // block.crop().left, block.crop().top,
2472 // block.crop().width, block.crop().height,
2473 // block.width(), block.height());
2474 const C2ConstGraphicBlock &block = blocks[0];
2475 updates.emplace_back(new C2StreamCropRectInfo::output(
2476 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002477 }
2478 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002479 }
George Burgess IVc813a592020-02-22 22:54:44 -08002480
Wonsik Kim75e22f42021-04-14 23:34:51 -07002481 sp<AMessage> oldFormat = config->mOutputFormat;
2482 config->updateConfiguration(updates, config->mOutputDomain);
2483 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002484
Wonsik Kim75e22f42021-04-14 23:34:51 -07002485 // copy standard infos to graphic buffers if not already present (otherwise, we
2486 // may overwrite the actual intermediate value with a final value)
2487 stream = 0;
2488 const static C2Param::Index stdGfxInfos[] = {
2489 C2StreamRotationInfo::output::PARAM_TYPE,
2490 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2491 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2492 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Taehwan Kim2d222b82022-05-12 14:19:26 +09002493 C2StreamHdr10PlusInfo::output::PARAM_TYPE, // will be deprecated
2494 C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE,
Wonsik Kim75e22f42021-04-14 23:34:51 -07002495 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2496 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2497 };
2498 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2499 if (buf->data().graphicBlocks().size()) {
2500 for (C2Param::Index ix : stdGfxInfos) {
2501 if (!buf->hasInfo(ix)) {
2502 const C2Param *param =
2503 config->getConfigParameterValue(ix.withStream(stream));
2504 if (param) {
2505 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2506 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2507 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002508 }
2509 }
2510 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002511 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002512 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002513 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002514 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302515 if (work->worklets.empty()
2516 || !work->worklets.back()
2517 || (work->worklets.back()->output.flags
2518 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2519 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2520 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002521 }
2522 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002523 initData = initDataWatcher.update();
2524 AmendOutputFormatWithCodecSpecificData(
2525 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2526 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002527 }
2528 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002529 }
2530 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002531 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Songyue Han1e6769b2023-08-30 18:09:27 +00002532 // log metrics to MediaCodec
2533 if (mMetrics->countEntries() == 0) {
2534 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2535 const std::unique_ptr<Config> &config = *configLocked;
2536 uint32_t pf = PIXEL_FORMAT_UNKNOWN;
2537 if (!config->mInputSurface) {
2538 pf = mChannel->getBuffersPixelFormat(config->mDomain & Config::IS_ENCODER);
Songyue Hanad01f6a2023-08-17 05:45:35 +00002539 } else {
2540 pf = config->mInputSurface->getPixelFormat();
Songyue Han1e6769b2023-08-30 18:09:27 +00002541 }
2542 if (pf != PIXEL_FORMAT_UNKNOWN) {
2543 mMetrics->setInt64(kCodecPixelFormat, pf);
2544 mCallback->onMetricsUpdated(mMetrics);
2545 }
2546 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002547 break;
2548 }
2549 case kWhatWatch: {
2550 // watch message already posted; no-op.
2551 break;
2552 }
2553 default: {
2554 ALOGE("unrecognized message");
2555 break;
2556 }
2557 }
2558 setDeadline(TimePoint::max(), 0ms, "none");
2559}
2560
2561void CCodec::setDeadline(
2562 const TimePoint &now,
2563 const std::chrono::milliseconds &timeout,
2564 const char *name) {
2565 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2566 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2567 deadline->set(now + (timeout * mult), name);
2568}
2569
ted.sun765db4d2020-06-23 14:03:41 +08002570status_t CCodec::configureTunneledVideoPlayback(
2571 std::shared_ptr<Codec2Client::Component> comp,
2572 sp<NativeHandle> *sidebandHandle,
2573 const sp<AMessage> &msg) {
2574 std::vector<std::unique_ptr<C2SettingResult>> failures;
2575
2576 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2577 C2PortTunneledModeTuning::output::AllocUnique(
2578 1,
2579 C2PortTunneledModeTuning::Struct::SIDEBAND,
2580 C2PortTunneledModeTuning::Struct::REALTIME,
2581 0);
2582 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2583 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2584 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2585 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2586 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2587 } else {
2588 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2589 tunneledPlayback->setFlexCount(0);
2590 }
2591 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2592 if (c2err != C2_OK) {
2593 return UNKNOWN_ERROR;
2594 }
2595
Houxiang Dai5a97b472021-03-22 17:56:04 +08002596 if (sidebandHandle == nullptr) {
2597 return OK;
2598 }
2599
ted.sun765db4d2020-06-23 14:03:41 +08002600 std::vector<std::unique_ptr<C2Param>> params;
2601 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2602 if (c2err == C2_OK && params.size() == 1u) {
2603 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2604 C2PortTunnelHandleTuning::output::From(params[0].get());
2605 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2606 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2607 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2608 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2609 memcpy(handle->data, videoTunnelSideband->m.values,
2610 sizeof(int32_t) * videoTunnelSideband->flexCount());
2611 return OK;
2612 } else {
2613 return NO_MEMORY;
2614 }
2615 }
2616 return UNKNOWN_ERROR;
2617}
2618
Pawin Vongmasa36653902018-11-15 00:10:25 -08002619void CCodec::initiateReleaseIfStuck() {
Shrikara B3b87a532022-08-26 14:18:14 +05302620 std::string name;
2621 bool pendingDeadline = false;
2622 {
2623 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2624 if (deadline->get() < std::chrono::steady_clock::now()) {
2625 name = deadline->getName();
2626 }
2627 if (deadline->get() != TimePoint::max()) {
2628 pendingDeadline = true;
2629 }
2630 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002631 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002632 // We're not stuck.
2633 if (pendingDeadline) {
2634 // If we are not stuck yet but still has deadline coming up,
2635 // post watch message to check back later.
2636 (new AMessage(kWhatWatch, this))->post();
2637 }
2638 return;
2639 }
2640
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002641 C2String compName;
2642 {
2643 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002644 if (!state->comp) {
2645 ALOGD("previous call to %s exceeded timeout "
2646 "and the component is already released", name.c_str());
2647 return;
2648 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002649 compName = state->comp->getName();
2650 }
2651 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2652
Pawin Vongmasa36653902018-11-15 00:10:25 -08002653 initiateRelease(false);
2654 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2655}
2656
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002657// static
2658PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002659 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002660 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002661 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002662 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2663 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002664 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002665 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2666 sp<IGraphicBufferProducer> gbp;
2667 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2668 status_t err = gbs->initCheck();
2669 if (err != OK) {
2670 ALOGE("Failed to create persistent input surface: error %d", err);
2671 return nullptr;
2672 }
2673 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002674 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002675 } else {
2676 return nullptr;
2677 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002678 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002679 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002680 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002681 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002682 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002683}
2684
Wonsik Kimffb889a2020-05-28 11:32:25 -07002685class IntfCache {
2686public:
2687 IntfCache() = default;
2688
2689 status_t init(const std::string &name) {
2690 std::shared_ptr<Codec2Client::Interface> intf{
2691 Codec2Client::CreateInterfaceByName(name.c_str())};
2692 if (!intf) {
2693 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2694 mInitStatus = NO_INIT;
2695 return NO_INIT;
2696 }
2697 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2698 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2699 C2ParamField{&sUsage, &sUsage.value}));
2700 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2701 if (err != C2_OK) {
2702 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2703 name.c_str(), err);
2704 mFields[0].status = err;
2705 }
2706 std::vector<std::unique_ptr<C2Param>> params;
2707 err = intf->query(
2708 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09002709 {
2710 C2StreamBufferTypeSetting::input::PARAM_TYPE,
2711 C2PortAllocatorsTuning::input::PARAM_TYPE
2712 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07002713 C2_MAY_BLOCK,
2714 &params);
2715 if (err != C2_OK && err != C2_BAD_INDEX) {
2716 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2717 name.c_str(), err);
2718 }
2719 while (!params.empty()) {
2720 C2Param *param = params.back().release();
2721 params.pop_back();
2722 if (!param) {
2723 continue;
2724 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002725 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
2726 mInputStreamFormat.reset(
2727 C2StreamBufferTypeSetting::input::From(param));
2728 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002729 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002730 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002731 }
2732 }
2733 mInitStatus = OK;
2734 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002735 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002736
2737 status_t initCheck() const { return mInitStatus; }
2738
2739 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2740 CHECK_EQ(1u, mFields.size());
2741 return mFields[0];
2742 }
2743
2744 const C2ApiFeaturesSetting &getApiFeatures() const {
2745 return mApiFeatures;
2746 }
2747
Taehwan Kim900b49c2021-12-13 11:16:22 +09002748 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
2749 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
2750 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
2751 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
2752 param->invalidate();
2753 return param;
2754 }();
2755 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
2756 }
2757
Wonsik Kimffb889a2020-05-28 11:32:25 -07002758 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2759 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2760 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2761 C2PortAllocatorsTuning::input::AllocUnique(0);
2762 param->invalidate();
2763 return param;
2764 }();
2765 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2766 }
2767
2768private:
2769 status_t mInitStatus{NO_INIT};
2770
2771 std::vector<C2FieldSupportedValuesQuery> mFields;
2772 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09002773 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002774 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2775};
2776
2777static const IntfCache &GetIntfCache(const std::string &name) {
2778 static IntfCache sNullIntfCache;
2779 static std::mutex sMutex;
2780 static std::map<std::string, IntfCache> sCache;
2781 std::unique_lock<std::mutex> lock{sMutex};
2782 auto it = sCache.find(name);
2783 if (it == sCache.end()) {
2784 lock.unlock();
2785 IntfCache intfCache;
2786 status_t err = intfCache.init(name);
2787 if (err != OK) {
2788 return sNullIntfCache;
2789 }
2790 lock.lock();
2791 it = sCache.insert({name, std::move(intfCache)}).first;
2792 }
2793 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002794}
2795
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002796static status_t GetCommonAllocatorIds(
2797 const std::vector<std::string> &names,
2798 C2Allocator::type_t type,
2799 std::set<C2Allocator::id_t> *ids) {
2800 int poolMask = GetCodec2PoolMask();
2801 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2802 C2Allocator::id_t defaultAllocatorId =
2803 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2804
2805 ids->clear();
2806 if (names.empty()) {
2807 return OK;
2808 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002809 bool firstIteration = true;
2810 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002811 const IntfCache &intfCache = GetIntfCache(name);
2812 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002813 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002814 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002815 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
2816 if (streamFormat) {
2817 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
2818 if (streamFormat.value == C2BufferData::GRAPHIC
2819 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
2820 allocatorType = C2Allocator::GRAPHIC;
2821 }
2822
2823 if (type != allocatorType) {
2824 // requested type is not supported at input allocators
2825 ids->clear();
2826 ids->insert(defaultAllocatorId);
2827 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
2828 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
2829 break;
2830 }
2831 }
2832
Wonsik Kimffb889a2020-05-28 11:32:25 -07002833 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002834 if (firstIteration) {
2835 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002836 if (allocators && allocators.flexCount() > 0) {
2837 ids->insert(allocators.m.values,
2838 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002839 }
2840 if (ids->empty()) {
2841 // The component does not advertise allocators. Use default.
2842 ids->insert(defaultAllocatorId);
2843 }
2844 continue;
2845 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002846 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002847 if (allocators && allocators.flexCount() > 0) {
2848 filtered = true;
2849 for (auto it = ids->begin(); it != ids->end(); ) {
2850 bool found = false;
2851 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2852 if (allocators.m.values[j] == *it) {
2853 found = true;
2854 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002855 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002856 }
2857 if (found) {
2858 ++it;
2859 } else {
2860 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002861 }
2862 }
2863 }
2864 if (!filtered) {
2865 // The component does not advertise supported allocators. Use default.
2866 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2867 if (ids->size() != (containsDefault ? 1 : 0)) {
2868 ids->clear();
2869 if (containsDefault) {
2870 ids->insert(defaultAllocatorId);
2871 }
2872 }
2873 }
2874 }
2875 // Finally, filter with pool masks
2876 for (auto it = ids->begin(); it != ids->end(); ) {
2877 if ((poolMask >> *it) & 1) {
2878 ++it;
2879 } else {
2880 it = ids->erase(it);
2881 }
2882 }
2883 return OK;
2884}
2885
2886static status_t CalculateMinMaxUsage(
2887 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2888 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2889 *minUsage = 0;
2890 *maxUsage = ~0ull;
2891 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002892 const IntfCache &intfCache = GetIntfCache(name);
2893 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002894 continue;
2895 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002896 const C2FieldSupportedValuesQuery &usageSupportedValues =
2897 intfCache.getUsageSupportedValues();
2898 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002899 continue;
2900 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002901 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002902 if (supported.type != C2FieldSupportedValues::FLAGS) {
2903 continue;
2904 }
2905 if (supported.values.empty()) {
2906 *maxUsage = 0;
2907 continue;
2908 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08002909 if (supported.values.size() > 1) {
2910 *minUsage |= supported.values[1].u64;
2911 } else {
2912 *minUsage |= supported.values[0].u64;
2913 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002914 int64_t currentMaxUsage = 0;
2915 for (const C2Value::Primitive &flags : supported.values) {
2916 currentMaxUsage |= flags.u64;
2917 }
2918 *maxUsage &= currentMaxUsage;
2919 }
2920 return OK;
2921}
2922
2923// static
2924status_t CCodec::CanFetchLinearBlock(
2925 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002926 for (const std::string &name : names) {
2927 const IntfCache &intfCache = GetIntfCache(name);
2928 if (intfCache.initCheck() != OK) {
2929 continue;
2930 }
2931 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2932 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2933 *isCompatible = false;
2934 return OK;
2935 }
2936 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002937 std::set<C2Allocator::id_t> allocators;
2938 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2939 if (allocators.empty()) {
2940 *isCompatible = false;
2941 return OK;
2942 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002943
2944 uint64_t minUsage = 0;
2945 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002946 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002947 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002948 *isCompatible = ((maxUsage & minUsage) == minUsage);
2949 return OK;
2950}
2951
2952static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2953 static std::mutex sMutex{};
2954 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2955 std::unique_lock<std::mutex> lock{sMutex};
2956 std::shared_ptr<C2BlockPool> pool;
2957 auto it = sPools.find(allocId);
2958 if (it == sPools.end()) {
2959 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2960 if (err == OK) {
2961 sPools.emplace(allocId, pool);
2962 } else {
2963 pool.reset();
2964 }
2965 } else {
2966 pool = it->second;
2967 }
2968 return pool;
2969}
2970
2971// static
2972std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2973 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002974 std::set<C2Allocator::id_t> allocators;
2975 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2976 if (allocators.empty()) {
2977 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2978 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002979
2980 uint64_t minUsage = 0;
2981 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002982 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002983 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002984 if ((maxUsage & minUsage) != minUsage) {
2985 allocators.clear();
2986 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2987 }
2988 std::shared_ptr<C2LinearBlock> block;
2989 for (C2Allocator::id_t allocId : allocators) {
2990 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2991 if (!pool) {
2992 continue;
2993 }
2994 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2995 if (err != C2_OK || !block) {
2996 block.reset();
2997 continue;
2998 }
2999 break;
3000 }
3001 return block;
3002}
3003
3004// static
3005status_t CCodec::CanFetchGraphicBlock(
3006 const std::vector<std::string> &names, bool *isCompatible) {
3007 uint64_t minUsage = 0;
3008 uint64_t maxUsage = ~0ull;
3009 std::set<C2Allocator::id_t> allocators;
3010 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3011 if (allocators.empty()) {
3012 *isCompatible = false;
3013 return OK;
3014 }
3015 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3016 *isCompatible = ((maxUsage & minUsage) == minUsage);
3017 return OK;
3018}
3019
3020// static
3021std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
3022 int32_t width,
3023 int32_t height,
3024 int32_t format,
3025 uint64_t usage,
3026 const std::vector<std::string> &names) {
3027 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
3028 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
3029 ALOGD("Unrecognized pixel format: %d", format);
3030 return nullptr;
3031 }
3032 uint64_t minUsage = 0;
3033 uint64_t maxUsage = ~0ull;
3034 std::set<C2Allocator::id_t> allocators;
3035 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3036 if (allocators.empty()) {
3037 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3038 }
3039 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3040 minUsage |= usage;
3041 if ((maxUsage & minUsage) != minUsage) {
3042 allocators.clear();
3043 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3044 }
3045 std::shared_ptr<C2GraphicBlock> block;
3046 for (C2Allocator::id_t allocId : allocators) {
3047 std::shared_ptr<C2BlockPool> pool;
3048 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3049 if (err != C2_OK || !pool) {
3050 continue;
3051 }
3052 err = pool->fetchGraphicBlock(
3053 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
3054 if (err != C2_OK || !block) {
3055 block.reset();
3056 continue;
3057 }
3058 break;
3059 }
3060 return block;
3061}
3062
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003063} // namespace android