blob: 9c264af02fb2c796ed4a05cd359196c9485d7fee [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodec"
19#include <utils/Log.h>
20
21#include <sstream>
22#include <thread>
23
24#include <C2Config.h>
25#include <C2Debug.h>
26#include <C2ParamInternal.h>
27#include <C2PlatformSupport.h>
28
Pawin Vongmasa36653902018-11-15 00:10:25 -080029#include <android/IOMXBufferSource.h>
Pawin Vongmasabf69de92019-10-29 06:21:27 -070030#include <android/hardware/media/c2/1.0/IInputSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080031#include <android/hardware/media/omx/1.0/IGraphicBufferSource.h>
32#include <android/hardware/media/omx/1.0/IOmx.h>
Wonsik Kim50811882022-04-28 15:57:27 -070033#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080034#include <android-base/stringprintf.h>
35#include <cutils/properties.h>
36#include <gui/IGraphicBufferProducer.h>
37#include <gui/Surface.h>
38#include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070039#include <media/omx/1.0/WOmxNode.h>
40#include <media/openmax/OMX_Core.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080041#include <media/openmax/OMX_IndexExt.h>
Wonsik Kim1f5063d2021-05-03 15:41:17 -070042#include <media/stagefright/foundation/avc_utils.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070043#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
44#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070045#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080046#include <media/stagefright/BufferProducerWrapper.h>
47#include <media/stagefright/MediaCodecConstants.h>
Songyue Han1e6769b2023-08-30 18:09:27 +000048#include <media/stagefright/MediaCodecMetricsConstants.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080049#include <media/stagefright/PersistentSurface.h>
Brian Lindahlff74e9d2023-07-20 14:44:04 -060050#include <media/stagefright/RenderedFrameInfo.h>
ted.sun765db4d2020-06-23 14:03:41 +080051#include <utils/NativeHandle.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080052
53#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080054#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070055#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080056#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080057#include "InputSurfaceWrapper.h"
58
59extern "C" android::PersistentSurface *CreateInputSurface();
60
61namespace android {
62
63using namespace std::chrono_literals;
64using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
65using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080066using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080067
Wonsik Kim9917d4a2019-10-24 12:56:38 -070068typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070069typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070070
Pawin Vongmasa36653902018-11-15 00:10:25 -080071namespace {
72
73class CCodecWatchdog : public AHandler {
74private:
75 enum {
76 kWhatWatch,
77 };
78 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
79
80public:
81 static sp<CCodecWatchdog> getInstance() {
82 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
83 static std::once_flag flag;
84 // Call Init() only once.
85 std::call_once(flag, Init, instance);
86 return instance;
87 }
88
89 ~CCodecWatchdog() = default;
90
91 void watch(sp<CCodec> codec) {
92 bool shouldPost = false;
93 {
94 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
95 // If a watch message is in flight, piggy-back this instance as well.
96 // Otherwise, post a new watch message.
97 shouldPost = codecs->empty();
98 codecs->emplace(codec);
99 }
100 if (shouldPost) {
101 ALOGV("posting watch message");
102 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
103 }
104 }
105
106protected:
107 void onMessageReceived(const sp<AMessage> &msg) {
108 switch (msg->what()) {
109 case kWhatWatch: {
110 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
111 ALOGV("watch for %zu codecs", codecs->size());
112 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
113 sp<CCodec> codec = it->promote();
114 if (codec == nullptr) {
115 continue;
116 }
117 codec->initiateReleaseIfStuck();
118 }
119 codecs->clear();
120 break;
121 }
122
123 default: {
124 TRESPASS("CCodecWatchdog: unrecognized message");
125 }
126 }
127 }
128
129private:
130 CCodecWatchdog() : mLooper(new ALooper) {}
131
132 static void Init(const sp<CCodecWatchdog> &thiz) {
133 ALOGV("Init");
134 thiz->mLooper->setName("CCodecWatchdog");
135 thiz->mLooper->registerHandler(thiz);
136 thiz->mLooper->start();
137 }
138
139 sp<ALooper> mLooper;
140
141 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
142};
143
144class C2InputSurfaceWrapper : public InputSurfaceWrapper {
145public:
146 explicit C2InputSurfaceWrapper(
147 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
148 mSurface(surface) {
149 }
150
151 ~C2InputSurfaceWrapper() override = default;
152
153 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
154 if (mConnection != nullptr) {
155 return ALREADY_EXISTS;
156 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800157 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800158 }
159
160 void disconnect() override {
161 if (mConnection != nullptr) {
162 mConnection->disconnect();
163 mConnection = nullptr;
164 }
165 }
166
167 status_t start() override {
168 // InputSurface does not distinguish started state
169 return OK;
170 }
171
172 status_t signalEndOfInputStream() override {
173 C2InputSurfaceEosTuning eos(true);
174 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800175 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800176 if (err != C2_OK) {
177 return UNKNOWN_ERROR;
178 }
179 return OK;
180 }
181
182 status_t configure(Config &config __unused) {
183 // TODO
184 return OK;
185 }
186
187private:
188 std::shared_ptr<Codec2Client::InputSurface> mSurface;
189 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
190};
191
192class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
193public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700194 typedef hardware::media::omx::V1_0::Status OmxStatus;
195
Pawin Vongmasa36653902018-11-15 00:10:25 -0800196 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700197 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800198 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700199 uint32_t height,
200 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800201 : mSource(source), mWidth(width), mHeight(height) {
202 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700203 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800204 }
205 ~GraphicBufferSourceWrapper() override = default;
206
207 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
208 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700209 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800210 mNode->setFrameSize(mWidth, mHeight);
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700211 // Usage is queried during configure(), so setting it beforehand.
Sungtak Lee0cd4fbc2023-02-02 00:59:01 +0000212 // 64 bit set parameter is existing only in C2OMXNode.
213 OMX_U64 usage64 = mConfig.mUsage;
214 status_t res = mNode->setParameter(
215 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits64,
216 &usage64, sizeof(usage64));
217
218 if (res != OK) {
219 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
220 (void)mNode->setParameter(
221 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
222 &usage, sizeof(usage));
223 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700224
Yanqiang Fanc56f3e62021-09-28 16:54:07 +0800225 return GetStatus(mSource->configure(
226 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800227 }
228
229 void disconnect() override {
230 if (mNode == nullptr) {
231 return;
232 }
233 sp<IOMXBufferSource> source = mNode->getSource();
234 if (source == nullptr) {
235 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
236 return;
237 }
238 source->onOmxIdle();
239 source->onOmxLoaded();
240 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700241 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800242 }
243
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700244 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
245 if (status.isOk()) {
246 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
247 } else if (status.isDeadObject()) {
248 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800249 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700250 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800251 }
252
253 status_t start() override {
254 sp<IOMXBufferSource> source = mNode->getSource();
255 if (source == nullptr) {
256 return NO_INIT;
257 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900258
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800259 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800260 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900261
Wonsik Kim34d66012021-03-01 16:40:33 -0800262 OMX_PARAM_PORTDEFINITIONTYPE param;
263 param.nPortIndex = kPortIndexInput;
264 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
265 &param, sizeof(param));
266 if (err == OK) {
267 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900268 }
269
270 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800271 source->onInputBufferAdded(i);
272 }
273
274 source->onOmxExecuting();
275 return OK;
276 }
277
278 status_t signalEndOfInputStream() override {
279 return GetStatus(mSource->signalEndOfInputStream());
280 }
281
282 status_t configure(Config &config) {
283 std::stringstream status;
284 status_t err = OK;
285
286 // handle each configuration granually, in case we need to handle part of the configuration
287 // elsewhere
288
289 // TRICKY: we do not unset frame delay repeating
290 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
291 int64_t us = 1e6 / config.mMinFps + 0.5;
292 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
293 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
294 if (res != OK) {
295 status << " (=> " << asString(res) << ")";
296 err = res;
297 }
298 mConfig.mMinFps = config.mMinFps;
299 }
300
301 // pts gap
302 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
303 if (mNode != nullptr) {
304 OMX_PARAM_U32TYPE ptrGapParam = {};
305 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700306 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800307 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
308 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700309 // float -> uint32_t is undefined if the value is negative.
310 // First convert to int32_t to ensure the expected behavior.
311 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800312 (void)mNode->setParameter(
313 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
314 &ptrGapParam, sizeof(ptrGapParam));
315 }
316 }
317
318 // max fps
319 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700320 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800321 && config.mMaxFps != mConfig.mMaxFps) {
322 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
323 status << " maxFps=" << config.mMaxFps;
324 if (res != OK) {
325 status << " (=> " << asString(res) << ")";
326 err = res;
327 }
328 mConfig.mMaxFps = config.mMaxFps;
329 }
330
331 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
332 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
333 status << " timeOffset " << config.mTimeOffsetUs << "us";
334 if (res != OK) {
335 status << " (=> " << asString(res) << ")";
336 err = res;
337 }
338 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
339 }
340
341 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
342 status_t res =
343 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
344 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
345 if (res != OK) {
346 status << " (=> " << asString(res) << ")";
347 err = res;
348 }
349 mConfig.mCaptureFps = config.mCaptureFps;
350 mConfig.mCodedFps = config.mCodedFps;
351 }
352
353 if (config.mStartAtUs != mConfig.mStartAtUs
354 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
355 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
356 status << " start at " << config.mStartAtUs << "us";
357 if (res != OK) {
358 status << " (=> " << asString(res) << ")";
359 err = res;
360 }
361 mConfig.mStartAtUs = config.mStartAtUs;
362 mConfig.mStopped = config.mStopped;
363 }
364
365 // suspend-resume
366 if (config.mSuspended != mConfig.mSuspended) {
367 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
368 status << " " << (config.mSuspended ? "suspend" : "resume")
369 << " at " << config.mSuspendAtUs << "us";
370 if (res != OK) {
371 status << " (=> " << asString(res) << ")";
372 err = res;
373 }
374 mConfig.mSuspended = config.mSuspended;
375 mConfig.mSuspendAtUs = config.mSuspendAtUs;
376 }
377
378 if (config.mStopped != mConfig.mStopped && config.mStopped) {
379 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
380 status << " stop at " << config.mStopAtUs << "us";
381 if (res != OK) {
382 status << " (=> " << asString(res) << ")";
383 err = res;
384 } else {
385 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700386 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
387 [&res, &delayUs = config.mInputDelayUs](
388 auto status, auto stopTimeOffsetUs) {
389 res = static_cast<status_t>(status);
390 delayUs = stopTimeOffsetUs;
391 });
392 if (!trans.isOk()) {
393 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
394 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800395 if (res != OK) {
396 status << " (=> " << asString(res) << ")";
397 } else {
398 status << "=" << config.mInputDelayUs << "us";
399 }
400 mConfig.mInputDelayUs = config.mInputDelayUs;
401 }
402 mConfig.mStopAtUs = config.mStopAtUs;
403 mConfig.mStopped = config.mStopped;
404 }
405
406 // color aspects (android._color-aspects)
407
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700408 // consumer usage is queried earlier.
409
Wonsik Kima1335e12021-04-22 16:28:29 -0700410 // priority
411 if (mConfig.mPriority != config.mPriority) {
412 if (config.mPriority != INT_MAX) {
413 mNode->setPriority(config.mPriority);
414 }
415 mConfig.mPriority = config.mPriority;
416 }
417
Wonsik Kimbd557932019-07-02 15:51:20 -0700418 if (status.str().empty()) {
419 ALOGD("ISConfig not changed");
420 } else {
421 ALOGD("ISConfig%s", status.str().c_str());
422 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800423 return err;
424 }
425
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700426 void onInputBufferDone(c2_cntr64_t index) override {
427 mNode->onInputBufferDone(index);
428 }
429
Wonsik Kim673dd192021-01-29 14:58:12 -0800430 android_dataspace getDataspace() override {
431 return mNode->getDataspace();
432 }
433
Songyue Hanad01f6a2023-08-17 05:45:35 +0000434 uint32_t getPixelFormat() override {
435 return mNode->getPixelFormat();
436 }
437
Pawin Vongmasa36653902018-11-15 00:10:25 -0800438private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700439 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800440 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700441 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800442 uint32_t mWidth;
443 uint32_t mHeight;
444 Config mConfig;
445};
446
447class Codec2ClientInterfaceWrapper : public C2ComponentStore {
448 std::shared_ptr<Codec2Client> mClient;
449
450public:
451 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
452 : mClient(client) { }
453
454 virtual ~Codec2ClientInterfaceWrapper() = default;
455
456 virtual c2_status_t config_sm(
457 const std::vector<C2Param *> &params,
458 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
459 return mClient->config(params, C2_MAY_BLOCK, failures);
460 };
461
462 virtual c2_status_t copyBuffer(
463 std::shared_ptr<C2GraphicBuffer>,
464 std::shared_ptr<C2GraphicBuffer>) {
465 return C2_OMITTED;
466 }
467
468 virtual c2_status_t createComponent(
469 C2String, std::shared_ptr<C2Component> *const component) {
470 component->reset();
471 return C2_OMITTED;
472 }
473
474 virtual c2_status_t createInterface(
475 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
476 interface->reset();
477 return C2_OMITTED;
478 }
479
480 virtual c2_status_t query_sm(
481 const std::vector<C2Param *> &stackParams,
482 const std::vector<C2Param::Index> &heapParamIndices,
483 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
484 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
485 }
486
487 virtual c2_status_t querySupportedParams_nb(
488 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
489 return mClient->querySupportedParams(params);
490 }
491
492 virtual c2_status_t querySupportedValues_sm(
493 std::vector<C2FieldSupportedValuesQuery> &fields) const {
494 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
495 }
496
497 virtual C2String getName() const {
498 return mClient->getName();
499 }
500
501 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
502 return mClient->getParamReflector();
503 }
504
505 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
506 return std::vector<std::shared_ptr<const C2Component::Traits>>();
507 }
508};
509
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800510void RevertOutputFormatIfNeeded(
511 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
512 // We used to not report changes to these keys to the client.
513 const static std::set<std::string> sIgnoredKeys({
514 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800515 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800516 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800517 KEY_MAX_WIDTH,
518 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800519 "csd-0",
520 "csd-1",
521 "csd-2",
522 });
523 if (currentFormat == oldFormat) {
524 return;
525 }
526 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
527 AMessage::Type type;
528 for (size_t i = diff->countEntries(); i > 0; --i) {
529 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
530 diff->removeEntryAt(i - 1);
531 }
532 }
533 if (diff->countEntries() == 0) {
534 currentFormat = oldFormat;
535 }
536}
537
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700538void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700539 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700540 const sp<AMessage> &outputFormat) {
541 if (mediaType == MIMETYPE_VIDEO_AVC) {
542 // Codec specific data should be SPS and PPS in a single buffer,
543 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
544 // We separate the two and put them into the output format
545 // under the keys "csd-0" and "csd-1".
546
547 unsigned csdIndex = 0;
548
549 const uint8_t *nalStart;
550 size_t nalSize;
551 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
552 sp<ABuffer> csd = new ABuffer(nalSize + 4);
553 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
554 memcpy(csd->data() + 4, nalStart, nalSize);
555
556 outputFormat->setBuffer(
557 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
558
559 ++csdIndex;
560 }
561
562 if (csdIndex != 2) {
563 ALOGW("Expected two NAL units from AVC codec config, but %u found",
564 csdIndex);
565 }
566 } else {
567 // For everything else we just stash the codec specific data into
568 // the output format as a single piece of csd under "csd-0".
569 sp<ABuffer> csd = new ABuffer(size);
570 memcpy(csd->data(), data, size);
571 csd->setRange(0, size);
572 outputFormat->setBuffer("csd-0", csd);
573 }
574}
575
Pawin Vongmasa36653902018-11-15 00:10:25 -0800576} // namespace
577
578// CCodec::ClientListener
579
580struct CCodec::ClientListener : public Codec2Client::Listener {
581
582 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
583
584 virtual void onWorkDone(
585 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800586 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800587 (void)component;
588 sp<CCodec> codec(mCodec.promote());
589 if (!codec) {
590 return;
591 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800592 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800593 }
594
595 virtual void onTripped(
596 const std::weak_ptr<Codec2Client::Component>& component,
597 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
598 ) override {
599 // TODO
600 (void)component;
601 (void)settingResult;
602 }
603
604 virtual void onError(
605 const std::weak_ptr<Codec2Client::Component>& component,
606 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800607 {
608 // Component is only used for reporting as we use a separate listener for each instance
609 std::shared_ptr<Codec2Client::Component> comp = component.lock();
610 if (!comp) {
611 ALOGD("Component died with error: 0x%x", errorCode);
612 } else {
613 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
614 }
615 }
616
617 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800618 // Note: for now we do not propagate the error code to MediaCodec
619 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800620 sp<CCodec> codec(mCodec.promote());
621 if (!codec || !codec->mCallback) {
622 return;
623 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800624 codec->mCallback->onError(
625 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
626 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800627 }
628
629 virtual void onDeath(
630 const std::weak_ptr<Codec2Client::Component>& component) override {
631 { // Log the death of the component.
632 std::shared_ptr<Codec2Client::Component> comp = component.lock();
633 if (!comp) {
634 ALOGE("Codec2 component died.");
635 } else {
636 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
637 }
638 }
639
640 // Report to MediaCodec.
641 sp<CCodec> codec(mCodec.promote());
642 if (!codec || !codec->mCallback) {
643 return;
644 }
645 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
646 }
647
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800648 virtual void onFrameRendered(uint64_t bufferQueueId,
649 int32_t slotId,
650 int64_t timestampNs) override {
651 // TODO: implement
652 (void)bufferQueueId;
653 (void)slotId;
654 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800655 }
656
657 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800658 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800659 sp<CCodec> codec(mCodec.promote());
660 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800661 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800662 }
663 }
664
665private:
666 wp<CCodec> mCodec;
667};
668
669// CCodecCallbackImpl
670
671class CCodecCallbackImpl : public CCodecCallback {
672public:
673 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
674 ~CCodecCallbackImpl() override = default;
675
676 void onError(status_t err, enum ActionCode actionCode) override {
677 mCodec->mCallback->onError(err, actionCode);
678 }
679
680 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
Brian Lindahlff74e9d2023-07-20 14:44:04 -0600681 mCodec->mCallback->onOutputFramesRendered({RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
Pawin Vongmasa36653902018-11-15 00:10:25 -0800682 }
683
Pawin Vongmasa36653902018-11-15 00:10:25 -0800684 void onOutputBuffersChanged() override {
685 mCodec->mCallback->onOutputBuffersChanged();
686 }
687
Guillaume Chelfi5ffbcb32021-04-12 14:23:43 +0200688 void onFirstTunnelFrameReady() override {
689 mCodec->mCallback->onFirstTunnelFrameReady();
690 }
691
Pawin Vongmasa36653902018-11-15 00:10:25 -0800692private:
693 CCodec *mCodec;
694};
695
696// CCodec
697
698CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700699 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
700 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800701}
702
703CCodec::~CCodec() {
704}
705
706std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
707 return mChannel;
708}
709
710status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
711 status_t err = job();
712 if (err != C2_OK) {
713 mCallback->onError(err, ACTION_CODE_FATAL);
714 }
715 return err;
716}
717
718void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
719 auto setAllocating = [this] {
720 Mutexed<State>::Locked state(mState);
721 if (state->get() != RELEASED) {
722 return INVALID_OPERATION;
723 }
724 state->set(ALLOCATING);
725 return OK;
726 };
727 if (tryAndReportOnError(setAllocating) != OK) {
728 return;
729 }
730
731 sp<RefBase> codecInfo;
732 CHECK(msg->findObject("codecInfo", &codecInfo));
733 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
734
735 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
736 allocMsg->setObject("codecInfo", codecInfo);
737 allocMsg->post();
738}
739
740void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
741 if (codecInfo == nullptr) {
742 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
743 return;
744 }
745 ALOGD("allocate(%s)", codecInfo->getCodecName());
746 mClientListener.reset(new ClientListener(this));
747
748 AString componentName = codecInfo->getCodecName();
749 std::shared_ptr<Codec2Client> client;
750
751 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700752 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800753 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800754 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800755 SetPreferredCodec2ComponentStore(
756 std::make_shared<Codec2ClientInterfaceWrapper>(client));
757 }
758
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900759 std::shared_ptr<Codec2Client::Component> comp;
760 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800761 componentName.c_str(),
762 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900763 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800764 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900765 if (status != C2_OK) {
766 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800767 Mutexed<State>::Locked state(mState);
768 state->set(RELEASED);
769 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900770 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800771 state.lock();
772 return;
773 }
774 ALOGI("Created component [%s]", componentName.c_str());
775 mChannel->setComponent(comp);
776 auto setAllocated = [this, comp, client] {
777 Mutexed<State>::Locked state(mState);
778 if (state->get() != ALLOCATING) {
779 state->set(RELEASED);
780 return UNKNOWN_ERROR;
781 }
782 state->set(ALLOCATED);
783 state->comp = comp;
784 mClient = client;
785 return OK;
786 };
787 if (tryAndReportOnError(setAllocated) != OK) {
788 return;
789 }
790
791 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700792 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
793 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800794 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800795 if (err != OK) {
796 ALOGW("Failed to initialize configuration support");
797 // TODO: report error once we complete implementation.
798 }
799 config->queryConfiguration(comp);
800
801 mCallback->onComponentAllocated(componentName.c_str());
802}
803
804void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
805 auto checkAllocated = [this] {
806 Mutexed<State>::Locked state(mState);
807 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
808 };
809 if (tryAndReportOnError(checkAllocated) != OK) {
810 return;
811 }
812
813 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
814 msg->setMessage("format", format);
815 msg->post();
816}
817
818void CCodec::configure(const sp<AMessage> &msg) {
819 std::shared_ptr<Codec2Client::Component> comp;
820 auto checkAllocated = [this, &comp] {
821 Mutexed<State>::Locked state(mState);
822 if (state->get() != ALLOCATED) {
823 state->set(RELEASED);
824 return UNKNOWN_ERROR;
825 }
826 comp = state->comp;
827 return OK;
828 };
829 if (tryAndReportOnError(checkAllocated) != OK) {
830 return;
831 }
832
833 auto doConfig = [msg, comp, this]() -> status_t {
834 AString mime;
835 if (!msg->findString("mime", &mime)) {
836 return BAD_VALUE;
837 }
838
839 int32_t encoder;
840 if (!msg->findInt32("encoder", &encoder)) {
841 encoder = false;
842 }
843
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800844 int32_t flags;
845 if (!msg->findInt32("flags", &flags)) {
846 return BAD_VALUE;
847 }
848
Pawin Vongmasa36653902018-11-15 00:10:25 -0800849 // TODO: read from intf()
850 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
851 return UNKNOWN_ERROR;
852 }
853
854 int32_t storeMeta;
855 if (encoder
856 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
857 && storeMeta != kMetadataBufferTypeInvalid) {
858 if (storeMeta != kMetadataBufferTypeANWBuffer) {
859 ALOGD("Only ANW buffers are supported for legacy metadata mode");
860 return BAD_VALUE;
861 }
862 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
863 }
864
ted.sun765db4d2020-06-23 14:03:41 +0800865 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800866 sp<RefBase> obj;
867 sp<Surface> surface;
868 if (msg->findObject("native-window", &obj)) {
869 surface = static_cast<Surface *>(obj.get());
Sungtak Lee214ce612023-11-01 10:01:13 +0000870 int32_t generation;
871 (void)msg->findInt32("native-window-generation", &generation);
ted.sun765db4d2020-06-23 14:03:41 +0800872 // setup tunneled playback
873 if (surface != nullptr) {
874 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
875 const std::unique_ptr<Config> &config = *configLocked;
876 if ((config->mDomain & Config::IS_DECODER)
877 && (config->mDomain & Config::IS_VIDEO)) {
878 int32_t tunneled;
879 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
880 ALOGI("Configuring TUNNELED video playback.");
881
882 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
883 if (err != OK) {
884 ALOGE("configureTunneledVideoPlayback failed!");
885 return err;
886 }
887 config->mTunneled = true;
888 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +0100889
890 int32_t pushBlankBuffersOnStop = 0;
891 if (msg->findInt32(KEY_PUSH_BLANK_BUFFERS_ON_STOP, &pushBlankBuffersOnStop)) {
892 config->mPushBlankBuffersOnStop = pushBlankBuffersOnStop == 1;
893 }
shuanglong.wang480a8362023-02-17 20:55:51 +0800894 // secure compoment or protected content default with
895 // "push-blank-buffers-on-shutdown" flag
896 if (!config->mPushBlankBuffersOnStop) {
897 int32_t usageProtected;
898 if (comp->getName().find(".secure") != std::string::npos) {
899 config->mPushBlankBuffersOnStop = true;
900 } else if (msg->findInt32("protected", &usageProtected) && usageProtected) {
901 config->mPushBlankBuffersOnStop = true;
902 }
903 }
ted.sun765db4d2020-06-23 14:03:41 +0800904 }
905 }
Sungtak Lee214ce612023-11-01 10:01:13 +0000906 setSurface(surface, (uint32_t)generation);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800907 }
908
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700909 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
910 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800911 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800912 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
913 ALOGD("[%s] buffers are %sbound to CCodec for this session",
914 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800915
Wonsik Kim1114eea2019-02-25 14:35:24 -0800916 // Enforce required parameters
917 int32_t i32;
918 float flt;
919 if (config->mDomain & Config::IS_AUDIO) {
920 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
921 ALOGD("sample rate is missing, which is required for audio components.");
922 return BAD_VALUE;
923 }
924 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
925 ALOGD("channel count is missing, which is required for audio components.");
926 return BAD_VALUE;
927 }
928 if ((config->mDomain & Config::IS_ENCODER)
929 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
930 && !msg->findInt32(KEY_BIT_RATE, &i32)
931 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
932 ALOGD("bitrate is missing, which is required for audio encoders.");
933 return BAD_VALUE;
934 }
935 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800936 int32_t width = 0;
937 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800938 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800939 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800940 ALOGD("width is missing, which is required for image/video components.");
941 return BAD_VALUE;
942 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800943 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800944 ALOGD("height is missing, which is required for image/video components.");
945 return BAD_VALUE;
946 }
947 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700948 int32_t mode = BITRATE_MODE_VBR;
949 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700950 if (!msg->findInt32(KEY_QUALITY, &i32)) {
951 ALOGD("quality is missing, which is required for video encoders in CQ.");
952 return BAD_VALUE;
953 }
954 } else {
955 if (!msg->findInt32(KEY_BIT_RATE, &i32)
956 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
957 ALOGD("bitrate is missing, which is required for video encoders.");
958 return BAD_VALUE;
959 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800960 }
961 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
962 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
963 ALOGD("I frame interval is missing, which is required for video encoders.");
964 return BAD_VALUE;
965 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700966 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
967 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
968 ALOGD("frame rate is missing, which is required for video encoders.");
969 return BAD_VALUE;
970 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800971 }
972 }
973
Pawin Vongmasa36653902018-11-15 00:10:25 -0800974 /*
975 * Handle input surface configuration
976 */
977 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
978 && (config->mDomain & Config::IS_ENCODER)) {
979 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
980 {
981 config->mISConfig->mMinFps = 0;
982 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800983 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800984 config->mISConfig->mMinFps = 1e6 / value;
985 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700986 if (!msg->findFloat(
987 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
988 config->mISConfig->mMaxFps = -1;
989 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800990 config->mISConfig->mMinAdjustedFps = 0;
991 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800992 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800993 if (value < 0 && value >= INT32_MIN) {
994 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700995 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800996 } else if (value > 0 && value <= INT32_MAX) {
997 config->mISConfig->mMinAdjustedFps = 1e6 / value;
998 }
999 }
1000 }
1001
1002 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -07001003 bool captureFpsFound = false;
1004 double timeLapseFps;
1005 float captureRate;
1006 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
1007 config->mISConfig->mCaptureFps = timeLapseFps;
1008 captureFpsFound = true;
1009 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
1010 config->mISConfig->mCaptureFps = captureRate;
1011 captureFpsFound = true;
1012 }
1013 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001014 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
1015 }
1016 }
1017
1018 {
1019 config->mISConfig->mSuspended = false;
1020 config->mISConfig->mSuspendAtUs = -1;
1021 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001022 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001023 config->mISConfig->mSuspended = true;
1024 }
1025 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001026 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -07001027 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001028 }
1029
1030 /*
1031 * Handle desired color format.
1032 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001033 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001034 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001035 int32_t format = 0;
1036 // Query vendor format for Flexible YUV
1037 std::vector<std::unique_ptr<C2Param>> heapParams;
1038 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
Wonsik Kim50811882022-04-28 15:57:27 -07001039 int vendorSdkVersion = base::GetIntProperty(
1040 "ro.vendor.build.version.sdk", android_get_device_api_level());
guochuang709b48b2022-10-25 20:40:42 +08001041 if (mClient->query(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001042 {},
1043 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1044 C2_MAY_BLOCK,
1045 &heapParams) == C2_OK
1046 && heapParams.size() == 1u) {
1047 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1048 heapParams[0].get());
1049 } else {
1050 pixelFormatInfo = nullptr;
1051 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001052 // bit depth -> format
1053 std::map<uint32_t, uint32_t> flexPixelFormat;
1054 std::map<uint32_t, uint32_t> flexPlanarPixelFormat;
1055 std::map<uint32_t, uint32_t> flexSemiPlanarPixelFormat;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001056 if (pixelFormatInfo && *pixelFormatInfo) {
1057 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1058 const C2FlexiblePixelFormatDescriptorStruct &desc =
1059 pixelFormatInfo->m.values[i];
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001060 if (desc.subsampling != C2Color::YUV_420
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001061 // TODO(b/180076105): some device report wrong layout
1062 // || desc.layout == C2Color::INTERLEAVED_PACKED
1063 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1064 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1065 continue;
1066 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001067 if (flexPixelFormat.count(desc.bitDepth) == 0) {
1068 flexPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001069 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001070 if (desc.layout == C2Color::PLANAR_PACKED
1071 && flexPlanarPixelFormat.count(desc.bitDepth) == 0) {
1072 flexPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001073 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001074 if (desc.layout == C2Color::SEMIPLANAR_PACKED
1075 && flexSemiPlanarPixelFormat.count(desc.bitDepth) == 0) {
1076 flexSemiPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001077 }
1078 }
1079 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001080 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001081 // Also handle default color format (encoders require color format, so this is only
1082 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001083 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001084 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001085 const char *prefix = "";
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001086 if (flexSemiPlanarPixelFormat.count(8) != 0) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001087 format = COLOR_FormatYUV420SemiPlanar;
1088 prefix = "semi-";
1089 } else {
1090 format = COLOR_FormatYUV420Planar;
1091 }
1092 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1093 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001094 } else {
1095 format = COLOR_FormatSurface;
1096 }
1097 defaultColorFormat = format;
1098 }
1099 } else {
1100 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001101 if (vendorSdkVersion < __ANDROID_API_S__ &&
Taehwan Kim43e715d2022-09-22 12:04:59 +09001102 (format == COLOR_FormatYUV420Planar ||
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001103 format == COLOR_FormatYUV420PackedPlanar ||
1104 format == COLOR_FormatYUV420SemiPlanar ||
1105 format == COLOR_FormatYUV420PackedSemiPlanar)) {
1106 // pre-S framework used to map these color formats into YV12.
1107 // Codecs from older vendor partition may be relying on
1108 // this assumption.
1109 format = HAL_PIXEL_FORMAT_YV12;
1110 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001111 switch (format) {
1112 case COLOR_FormatYUV420Flexible:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001113 format = COLOR_FormatYUV420Planar;
1114 if (flexPixelFormat.count(8) != 0) {
1115 format = flexPixelFormat[8];
1116 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001117 break;
1118 case COLOR_FormatYUV420Planar:
1119 case COLOR_FormatYUV420PackedPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001120 if (flexPlanarPixelFormat.count(8) != 0) {
1121 format = flexPlanarPixelFormat[8];
1122 } else if (flexPixelFormat.count(8) != 0) {
1123 format = flexPixelFormat[8];
1124 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001125 break;
1126 case COLOR_FormatYUV420SemiPlanar:
1127 case COLOR_FormatYUV420PackedSemiPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001128 if (flexSemiPlanarPixelFormat.count(8) != 0) {
1129 format = flexSemiPlanarPixelFormat[8];
1130 } else if (flexPixelFormat.count(8) != 0) {
1131 format = flexPixelFormat[8];
1132 }
1133 break;
1134 case COLOR_FormatYUVP010:
1135 format = COLOR_FormatYUVP010;
1136 if (flexSemiPlanarPixelFormat.count(10) != 0) {
1137 format = flexSemiPlanarPixelFormat[10];
1138 } else if (flexPixelFormat.count(10) != 0) {
1139 format = flexPixelFormat[10];
1140 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001141 break;
1142 default:
1143 // No-op
1144 break;
1145 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001146 }
1147 }
1148
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001149 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001150 msg->setInt32("android._color-format", format);
1151 }
1152 }
1153
Wonsik Kim77e97c72021-01-20 10:33:22 -08001154 /*
1155 * Handle dataspace
1156 */
1157 int32_t usingRecorder;
1158 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1159 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1160 int32_t width, height;
1161 if (msg->findInt32("width", &width)
1162 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001163 ColorAspects aspects;
1164 getColorAspectsFromFormat(msg, aspects);
1165 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001166 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001167 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1168 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001169 }
1170 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1171 ALOGD("setting dataspace to %x", dataSpace);
1172 }
1173
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001174 int32_t subscribeToAllVendorParams;
1175 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1176 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1177 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1178 }
1179 }
1180
Pawin Vongmasa36653902018-11-15 00:10:25 -08001181 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001182 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1183 // the behavior here.
1184 sp<AMessage> sdkParams = msg;
1185 int32_t videoBitrate;
1186 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1187 sdkParams = msg->dup();
1188 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1189 }
ted.sun765db4d2020-06-23 14:03:41 +08001190 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001191 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001192 if (err != OK) {
1193 ALOGW("failed to convert configuration to c2 params");
1194 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001195
1196 int32_t maxBframes = 0;
1197 if ((config->mDomain & Config::IS_ENCODER)
1198 && (config->mDomain & Config::IS_VIDEO)
1199 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1200 && maxBframes > 0) {
1201 std::unique_ptr<C2StreamGopTuning::output> gop =
1202 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1203 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1204 gop->m.values[1] = {
1205 C2Config::picture_type_t(P_FRAME | B_FRAME),
1206 uint32_t(maxBframes)
1207 };
1208 configUpdate.push_back(std::move(gop));
1209 }
1210
Ray Essicka0ae6972021-03-10 19:40:01 -08001211 if ((config->mDomain & Config::IS_ENCODER)
1212 && (config->mDomain & Config::IS_VIDEO)) {
1213 // we may not use all 3 of these entries
1214 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1215 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1216 0u /* stream */);
1217
1218 int ix = 0;
1219
1220 int32_t iMax = INT32_MAX;
1221 int32_t iMin = INT32_MIN;
1222 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1223 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1224 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1225 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1226 }
1227
1228 int32_t pMax = INT32_MAX;
1229 int32_t pMin = INT32_MIN;
1230 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1231 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1232 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1233 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1234 }
1235
1236 int32_t bMax = INT32_MAX;
1237 int32_t bMin = INT32_MIN;
1238 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1239 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1240 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1241 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1242 }
1243
1244 // adjust to reflect actual use.
1245 qp->setFlexCount(ix);
1246
1247 configUpdate.push_back(std::move(qp));
1248 }
1249
Wonsik Kima1335e12021-04-22 16:28:29 -07001250 int32_t background = 0;
1251 if ((config->mDomain & Config::IS_VIDEO)
1252 && msg->findInt32("android._background-mode", &background)
1253 && background) {
1254 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1255 if (config->mISConfig) {
1256 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1257 }
1258 }
1259
Pawin Vongmasa36653902018-11-15 00:10:25 -08001260 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1261 if (err != OK) {
1262 ALOGW("failed to configure c2 params");
1263 return err;
1264 }
1265
1266 std::vector<std::unique_ptr<C2Param>> params;
1267 C2StreamUsageTuning::input usage(0u, 0u);
1268 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001269 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001270
Wonsik Kim3baecda2021-02-07 22:19:56 -08001271 C2Param::Index colorAspectsRequestIndex =
1272 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001273 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001274 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001275 };
Chaejung Lim86c22dc2021-12-23 00:41:05 -08001276 int32_t colorTransferRequest = 0;
1277 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1278 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1279 colorTransferRequest = 0;
1280 }
1281 c2_status_t c2err = C2_OK;
1282 if (colorTransferRequest != 0) {
1283 c2err = comp->query(
1284 { &usage, &maxInputSize, &prepend },
1285 indices,
1286 C2_DONT_BLOCK,
1287 &params);
1288 } else {
1289 c2err = comp->query(
1290 { &usage, &maxInputSize, &prepend },
1291 {},
1292 C2_DONT_BLOCK,
1293 &params);
1294 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001295 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1296 ALOGE("Failed to query component interface: %d", c2err);
1297 return UNKNOWN_ERROR;
1298 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001299 if (usage) {
1300 if (usage.value & C2MemoryUsage::CPU_READ) {
1301 config->mInputFormat->setInt32("using-sw-read-often", true);
1302 }
1303 if (config->mISConfig) {
1304 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1305 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1306 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001307 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001308 }
1309
1310 // NOTE: we don't blindly use client specified input size if specified as clients
1311 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1312 // client specified size is only used to ask for bigger buffers than component suggested
1313 // size.
1314 int32_t clientInputSize = 0;
1315 bool clientSpecifiedInputSize =
1316 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1317 // TEMP: enforce minimum buffer size of 1MB for video decoders
1318 // and 16K / 4K for audio encoders/decoders
1319 if (maxInputSize.value == 0) {
1320 if (config->mDomain & Config::IS_AUDIO) {
1321 maxInputSize.value = encoder ? 16384 : 4096;
1322 } else if (!encoder) {
1323 maxInputSize.value = 1048576u;
1324 }
1325 }
1326
1327 // verify that CSD fits into this size (if defined)
1328 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1329 sp<ABuffer> csd;
1330 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1331 if (csd && csd->size() > maxInputSize.value) {
1332 maxInputSize.value = csd->size();
1333 }
1334 }
1335 }
1336
1337 // TODO: do this based on component requiring linear allocator for input
1338 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1339 if (clientSpecifiedInputSize) {
1340 // Warn that we're overriding client's max input size if necessary.
1341 if ((uint32_t)clientInputSize < maxInputSize.value) {
1342 ALOGD("client requested max input size %d, which is smaller than "
1343 "what component recommended (%u); overriding with component "
1344 "recommendation.", clientInputSize, maxInputSize.value);
1345 ALOGW("This behavior is subject to change. It is recommended that "
1346 "app developers double check whether the requested "
1347 "max input size is in reasonable range.");
1348 } else {
1349 maxInputSize.value = clientInputSize;
1350 }
1351 }
1352 // Pass max input size on input format to the buffer channel (if supplied by the
1353 // component or by a default)
1354 if (maxInputSize.value) {
1355 config->mInputFormat->setInt32(
1356 KEY_MAX_INPUT_SIZE,
1357 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1358 }
1359 }
1360
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001361 int32_t clientPrepend;
1362 if ((config->mDomain & Config::IS_VIDEO)
1363 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001364 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001365 && clientPrepend
1366 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001367 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001368 return BAD_VALUE;
1369 }
1370
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001371 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001372 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1373 // propagate HDR static info to output format for both encoders and decoders
1374 // if component supports this info, we will update from component, but only the raw port,
1375 // so don't propagate if component already filled it in.
1376 sp<ABuffer> hdrInfo;
1377 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1378 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1379 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1380 }
1381
1382 // Set desired color format from configuration parameter
1383 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001384 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1385 format = defaultColorFormat;
1386 }
1387 if (config->mDomain & Config::IS_ENCODER) {
1388 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001389 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1390 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001391 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001392 } else {
1393 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 }
1395 }
1396
1397 // propagate encoder delay and padding to output format
1398 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1399 int delay = 0;
1400 if (msg->findInt32("encoder-delay", &delay)) {
1401 config->mOutputFormat->setInt32("encoder-delay", delay);
1402 }
1403 int padding = 0;
1404 if (msg->findInt32("encoder-padding", &padding)) {
1405 config->mOutputFormat->setInt32("encoder-padding", padding);
1406 }
1407 }
1408
Pawin Vongmasa36653902018-11-15 00:10:25 -08001409 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001410 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001411 int32_t mask;
1412 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1413 if (config->mDomain & Config::IS_ENCODER) {
1414 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1415 } else {
1416 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1417 }
1418 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001419
1420 // set PCM encoding
1421 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1422 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1423 if (encoder) {
1424 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1425 } else {
1426 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1427 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001428 }
1429
Wonsik Kim3baecda2021-02-07 22:19:56 -08001430 std::unique_ptr<C2Param> colorTransferRequestParam;
1431 for (std::unique_ptr<C2Param> &param : params) {
1432 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1433 ALOGI("found color transfer request param");
1434 colorTransferRequestParam = std::move(param);
1435 }
1436 }
Wonsik Kim3baecda2021-02-07 22:19:56 -08001437
1438 if (colorTransferRequest != 0) {
1439 if (colorTransferRequestParam && *colorTransferRequestParam) {
1440 C2StreamColorAspectsInfo::output *info =
1441 static_cast<C2StreamColorAspectsInfo::output *>(
1442 colorTransferRequestParam.get());
1443 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1444 colorTransferRequest = 0;
1445 }
1446 } else {
1447 colorTransferRequest = 0;
1448 }
1449 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1450 }
1451
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001452 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1453 // Need to get stride/vstride
1454 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1455 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1456 // TODO: retrieve these values without allocating a buffer.
1457 // Currently allocating a buffer is necessary to retrieve the layout.
1458 int64_t blockUsage =
1459 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1460 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
Taehwan Kim2772e1c2022-03-31 17:15:08 +09001461 width, height, componentColorFormat, blockUsage, {comp->getName()});
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001462 sp<GraphicBlockBuffer> buffer;
1463 if (block) {
1464 buffer = GraphicBlockBuffer::Allocate(
1465 config->mInputFormat,
1466 block,
1467 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1468 } else {
1469 ALOGD("Failed to allocate a graphic block "
1470 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1471 width, height, pixelFormat, (long long)blockUsage);
1472 // This means that byte buffer mode is not supported in this configuration
1473 // anyway. Skip setting stride/vstride to input format.
1474 }
1475 if (buffer) {
1476 sp<ABuffer> imageData = buffer->getImageData();
1477 MediaImage2 *img = nullptr;
1478 if (imageData && imageData->data()
1479 && imageData->size() >= sizeof(MediaImage2)) {
1480 img = (MediaImage2*)imageData->data();
1481 }
1482 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1483 int32_t stride = img->mPlane[0].mRowInc;
1484 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1485 if (img->mNumPlanes > 1 && stride > 0) {
1486 int64_t offsetDelta =
1487 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1488 if (offsetDelta % stride == 0) {
1489 int32_t vstride = int32_t(offsetDelta / stride);
1490 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1491 } else {
1492 ALOGD("Cannot report accurate slice height: "
1493 "offsetDelta = %lld stride = %d",
1494 (long long)offsetDelta, stride);
1495 }
1496 }
1497 }
1498 }
1499 }
1500 }
1501
Wonsik Kimec585c32021-10-01 01:11:00 -07001502 if (config->mTunneled) {
1503 config->mOutputFormat->setInt32("android._tunneled", 1);
1504 }
1505
Yushin Cho91873b52021-12-21 04:08:35 -08001506 // Convert an encoding statistics level to corresponding encoding statistics
1507 // kinds
1508 int32_t encodingStatisticsLevel = VIDEO_ENCODING_STATISTICS_LEVEL_NONE;
1509 if ((config->mDomain & Config::IS_ENCODER)
1510 && (config->mDomain & Config::IS_VIDEO)
1511 && msg->findInt32(KEY_VIDEO_ENCODING_STATISTICS_LEVEL, &encodingStatisticsLevel)) {
1512 // Higher level include all the enc stats belong to lower level.
1513 switch (encodingStatisticsLevel) {
1514 // case VIDEO_ENCODING_STATISTICS_LEVEL_2: // reserved for the future level 2
1515 // with more enc stat kinds
1516 // Future extended encoding statistics for the level 2 should be added here
1517 case VIDEO_ENCODING_STATISTICS_LEVEL_1:
Wonsik Kimeebab652022-06-02 13:01:55 -07001518 config->subscribeToConfigUpdate(
1519 comp,
1520 {
1521 C2AndroidStreamAverageBlockQuantizationInfo::output::PARAM_TYPE,
1522 C2StreamPictureTypeInfo::output::PARAM_TYPE,
1523 });
Yushin Cho91873b52021-12-21 04:08:35 -08001524 break;
1525 case VIDEO_ENCODING_STATISTICS_LEVEL_NONE:
1526 break;
1527 }
1528 }
1529 ALOGD("encoding statistics level = %d", encodingStatisticsLevel);
1530
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001531 ALOGD("setup formats input: %s",
1532 config->mInputFormat->debugString().c_str());
1533 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001534 config->mOutputFormat->debugString().c_str());
1535 return OK;
1536 };
1537 if (tryAndReportOnError(doConfig) != OK) {
1538 return;
1539 }
1540
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001541 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1542 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001543
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001544 config->queryConfiguration(comp);
1545
Songyue Han1e6769b2023-08-30 18:09:27 +00001546 mMetrics = new AMessage;
1547 mChannel->resetBuffersPixelFormat((config->mDomain & Config::IS_ENCODER) ? true : false);
1548
Pawin Vongmasa36653902018-11-15 00:10:25 -08001549 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1550}
1551
1552void CCodec::initiateCreateInputSurface() {
1553 status_t err = [this] {
1554 Mutexed<State>::Locked state(mState);
1555 if (state->get() != ALLOCATED) {
1556 return UNKNOWN_ERROR;
1557 }
1558 // TODO: read it from intf() properly.
1559 if (state->comp->getName().find("encoder") == std::string::npos) {
1560 return INVALID_OPERATION;
1561 }
1562 return OK;
1563 }();
1564 if (err != OK) {
1565 mCallback->onInputSurfaceCreationFailed(err);
1566 return;
1567 }
1568
1569 (new AMessage(kWhatCreateInputSurface, this))->post();
1570}
1571
Lajos Molnar47118272019-01-31 16:28:04 -08001572sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1573 using namespace android::hardware::media::omx::V1_0;
1574 using namespace android::hardware::media::omx::V1_0::utils;
1575 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1576 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1577 android::sp<IOmx> omx = IOmx::getService();
Sungtak Lee47dcb482022-04-15 10:47:08 -07001578 if (omx == nullptr) {
1579 return nullptr;
1580 }
Lajos Molnar47118272019-01-31 16:28:04 -08001581 typedef android::hardware::graphics::bufferqueue::V1_0::
1582 IGraphicBufferProducer HGraphicBufferProducer;
1583 typedef android::hardware::media::omx::V1_0::
1584 IGraphicBufferSource HGraphicBufferSource;
1585 OmxStatus s;
1586 android::sp<HGraphicBufferProducer> gbp;
1587 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001588
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001589 using ::android::hardware::Return;
1590 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001591 [&s, &gbp, &gbs](
1592 OmxStatus status,
1593 const android::sp<HGraphicBufferProducer>& producer,
1594 const android::sp<HGraphicBufferSource>& source) {
1595 s = status;
1596 gbp = producer;
1597 gbs = source;
1598 });
1599 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001600 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001601 }
1602
1603 return nullptr;
1604}
1605
1606sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1607 sp<PersistentSurface> surface(CreateInputSurface());
1608
1609 if (surface == nullptr) {
1610 surface = CreateOmxInputSurface();
1611 }
1612
1613 return surface;
1614}
1615
Pawin Vongmasa36653902018-11-15 00:10:25 -08001616void CCodec::createInputSurface() {
1617 status_t err;
1618 sp<IGraphicBufferProducer> bufferProducer;
1619
Pawin Vongmasa36653902018-11-15 00:10:25 -08001620 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001621 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001622 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001623 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1624 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001625 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001626 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001627 }
1628
Lajos Molnar47118272019-01-31 16:28:04 -08001629 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001630 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1631 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1632 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001633
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001634 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001635 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1636 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001637 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001638 inputSurface));
1639 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001640 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001641 int32_t width = 0;
1642 (void)outputFormat->findInt32("width", &width);
1643 int32_t height = 0;
1644 (void)outputFormat->findInt32("height", &height);
1645 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001646 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001647 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001648 } else {
1649 ALOGE("Corrupted input surface");
1650 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1651 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001652 }
1653
1654 if (err != OK) {
1655 ALOGE("Failed to set up input surface: %d", err);
1656 mCallback->onInputSurfaceCreationFailed(err);
1657 return;
1658 }
1659
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001660 // Formats can change after setupInputSurface
1661 sp<AMessage> inputFormat;
1662 {
1663 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1664 const std::unique_ptr<Config> &config = *configLocked;
1665 inputFormat = config->mInputFormat;
1666 outputFormat = config->mOutputFormat;
1667 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001668 mCallback->onInputSurfaceCreated(
1669 inputFormat,
1670 outputFormat,
1671 new BufferProducerWrapper(bufferProducer));
1672}
1673
1674status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001675 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1676 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001677 config->mUsingSurface = true;
1678
1679 // we are now using surface - apply default color aspects to input format - as well as
1680 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001681 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001682
1683 // configure dataspace
1684 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
Wonsik Kim66b19552021-08-02 16:07:49 -07001685
1686 // The output format contains app-configured color aspects, and the input format
1687 // has the default color aspects. Use the default for the unspecified params.
1688 ColorAspects inputColorAspects, colorAspects;
1689 getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
1690 getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
1691 if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
1692 colorAspects.mRange = inputColorAspects.mRange;
1693 }
1694 if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
1695 colorAspects.mPrimaries = inputColorAspects.mPrimaries;
1696 }
1697 if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
1698 colorAspects.mTransfer = inputColorAspects.mTransfer;
1699 }
1700 if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
1701 colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
1702 }
1703 android_dataspace dataSpace = getDataSpaceForColorAspects(
1704 colorAspects, /* mayExtend = */ false);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001705 surface->setDataSpace(dataSpace);
Wonsik Kim66b19552021-08-02 16:07:49 -07001706 setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
1707 config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
1708
1709 ALOGD("input format %s to %s",
1710 inputFormatChanged ? "changed" : "unchanged",
1711 config->mInputFormat->debugString().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001712
1713 status_t err = mChannel->setInputSurface(surface);
1714 if (err != OK) {
1715 // undo input format update
1716 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001717 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001718 return err;
1719 }
1720 config->mInputSurface = surface;
1721
1722 if (config->mISConfig) {
1723 surface->configure(*config->mISConfig);
1724 } else {
1725 ALOGD("ISConfig: no configuration");
1726 }
1727
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001728 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001729}
1730
1731void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1732 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1733 msg->setObject("surface", surface);
1734 msg->post();
1735}
1736
1737void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001738 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001739 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001740 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001741 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1742 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001743 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001744 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001745 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001746 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1747 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1748 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1749 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001750 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1751 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1752 if (err != OK) {
1753 ALOGE("Failed to set up input surface: %d", err);
1754 mCallback->onInputSurfaceDeclined(err);
1755 return;
1756 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001757 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001758 int32_t width = 0;
1759 (void)outputFormat->findInt32("width", &width);
1760 int32_t height = 0;
1761 (void)outputFormat->findInt32("height", &height);
1762 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001763 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001764 if (err != OK) {
1765 ALOGE("Failed to set up input surface: %d", err);
1766 mCallback->onInputSurfaceDeclined(err);
1767 return;
1768 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001769 } else {
1770 ALOGE("Failed to set input surface: Corrupted surface.");
1771 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1772 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001773 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001774 // Formats can change after setupInputSurface
1775 sp<AMessage> inputFormat;
1776 {
1777 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1778 const std::unique_ptr<Config> &config = *configLocked;
1779 inputFormat = config->mInputFormat;
1780 outputFormat = config->mOutputFormat;
1781 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001782 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1783}
1784
1785void CCodec::initiateStart() {
1786 auto setStarting = [this] {
1787 Mutexed<State>::Locked state(mState);
1788 if (state->get() != ALLOCATED) {
1789 return UNKNOWN_ERROR;
1790 }
1791 state->set(STARTING);
1792 return OK;
1793 };
1794 if (tryAndReportOnError(setStarting) != OK) {
1795 return;
1796 }
1797
1798 (new AMessage(kWhatStart, this))->post();
1799}
1800
1801void CCodec::start() {
1802 std::shared_ptr<Codec2Client::Component> comp;
1803 auto checkStarting = [this, &comp] {
1804 Mutexed<State>::Locked state(mState);
1805 if (state->get() != STARTING) {
1806 return UNKNOWN_ERROR;
1807 }
1808 comp = state->comp;
1809 return OK;
1810 };
1811 if (tryAndReportOnError(checkStarting) != OK) {
1812 return;
1813 }
1814
1815 c2_status_t err = comp->start();
1816 if (err != C2_OK) {
1817 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1818 ACTION_CODE_FATAL);
1819 return;
1820 }
Wonsik Kimd55ed3b2023-06-22 14:42:17 -07001821
1822 // clear the deadline after the component starts
1823 setDeadline(TimePoint::max(), 0ms, "none");
1824
Pawin Vongmasa36653902018-11-15 00:10:25 -08001825 sp<AMessage> inputFormat;
1826 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001827 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001828 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001829 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001830 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1831 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001832 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001833 // start triggers format dup
1834 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001835 if (config->mInputSurface) {
1836 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001837 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001838 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001839 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001840 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001841 if (err2 != OK) {
1842 mCallback->onError(err2, ACTION_CODE_FATAL);
1843 return;
1844 }
Arun Johnson106fe7a2023-04-26 17:49:43 +00001845
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001846 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001847 if (err2 != OK) {
1848 mCallback->onError(err2, ACTION_CODE_FATAL);
1849 return;
1850 }
1851
1852 auto setRunning = [this] {
1853 Mutexed<State>::Locked state(mState);
1854 if (state->get() != STARTING) {
1855 return UNKNOWN_ERROR;
1856 }
1857 state->set(RUNNING);
1858 return OK;
1859 };
1860 if (tryAndReportOnError(setRunning) != OK) {
1861 return;
1862 }
Arun Johnson5997bb02022-04-01 19:35:44 +00001863
Wonsik Kim34b28b42022-05-20 15:49:32 -07001864 // preparation of input buffers may not succeed due to the lack of
1865 // memory; returning correct error code (NO_MEMORY) as an error allows
1866 // MediaCodec to try reclaim and restart codec gracefully.
1867 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
1868 err2 = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
1869 if (err2 != OK) {
1870 ALOGE("Initial preparation for Input Buffers failed");
1871 mCallback->onError(err2, ACTION_CODE_FATAL);
1872 return;
1873 }
1874
Pawin Vongmasa36653902018-11-15 00:10:25 -08001875 mCallback->onStartCompleted();
1876
Wonsik Kim34b28b42022-05-20 15:49:32 -07001877 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001878}
1879
1880void CCodec::initiateShutdown(bool keepComponentAllocated) {
1881 if (keepComponentAllocated) {
1882 initiateStop();
1883 } else {
1884 initiateRelease();
1885 }
1886}
1887
1888void CCodec::initiateStop() {
1889 {
1890 Mutexed<State>::Locked state(mState);
1891 if (state->get() == ALLOCATED
1892 || state->get() == RELEASED
1893 || state->get() == STOPPING
1894 || state->get() == RELEASING) {
1895 // We're already stopped, released, or doing it right now.
1896 state.unlock();
1897 mCallback->onStopCompleted();
1898 state.lock();
1899 return;
1900 }
1901 state->set(STOPPING);
1902 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001903 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00001904 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
1905 sp<AMessage> stopMessage(new AMessage(kWhatStop, this));
1906 stopMessage->setInt32("pushBlankBuffer", pushBlankBuffer);
1907 stopMessage->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001908}
1909
Sungtak Lee99144332023-01-26 11:03:14 +00001910void CCodec::stop(bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001911 std::shared_ptr<Codec2Client::Component> comp;
1912 {
1913 Mutexed<State>::Locked state(mState);
1914 if (state->get() == RELEASING) {
1915 state.unlock();
1916 // We're already stopped or release is in progress.
1917 mCallback->onStopCompleted();
1918 state.lock();
1919 return;
1920 } else if (state->get() != STOPPING) {
1921 state.unlock();
1922 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1923 state.lock();
1924 return;
1925 }
1926 comp = state->comp;
1927 }
Sungtak Leec0c05962023-10-25 08:14:13 +00001928
1929 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->stop().
1930 // But in the case some HAL implementations hang forever on comp->stop().
1931 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
1932 // completing stop()).
1933 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
1934 // prior to comp->stop().
1935 // See also b/300350761.
Sungtak Lee99144332023-01-26 11:03:14 +00001936 mChannel->stopUseOutputSurface(pushBlankBuffer);
Sungtak Leec0c05962023-10-25 08:14:13 +00001937 status_t err = comp->stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001938 if (err != C2_OK) {
1939 // TODO: convert err into status_t
1940 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1941 }
1942
1943 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001944 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1945 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001946 if (config->mInputSurface) {
1947 config->mInputSurface->disconnect();
1948 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001949 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001950 }
1951 }
1952 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001953 Mutexed<State>::Locked state(mState);
1954 if (state->get() == STOPPING) {
1955 state->set(ALLOCATED);
1956 }
1957 }
1958 mCallback->onStopCompleted();
1959}
1960
1961void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001962 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001963 {
1964 Mutexed<State>::Locked state(mState);
1965 if (state->get() == RELEASED || state->get() == RELEASING) {
1966 // We're already released or doing it right now.
1967 if (sendCallback) {
1968 state.unlock();
1969 mCallback->onReleaseCompleted();
1970 state.lock();
1971 }
1972 return;
1973 }
1974 if (state->get() == ALLOCATING) {
1975 state->set(RELEASING);
1976 // With the altered state allocate() would fail and clean up.
1977 if (sendCallback) {
1978 state.unlock();
1979 mCallback->onReleaseCompleted();
1980 state.lock();
1981 }
1982 return;
1983 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001984 if (state->get() == STARTING
1985 || state->get() == RUNNING
1986 || state->get() == STOPPING) {
1987 // Input surface may have been started, so clean up is needed.
1988 clearInputSurfaceIfNeeded = true;
1989 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001990 state->set(RELEASING);
1991 }
1992
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001993 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001994 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1995 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001996 if (config->mInputSurface) {
1997 config->mInputSurface->disconnect();
1998 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001999 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002000 }
2001 }
2002
Wonsik Kim936a89c2020-05-08 16:07:50 -07002003 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00002004 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002005 // thiz holds strong ref to this while the thread is running.
2006 sp<CCodec> thiz(this);
Sungtak Lee99144332023-01-26 11:03:14 +00002007 std::thread([thiz, sendCallback, pushBlankBuffer]
2008 { thiz->release(sendCallback, pushBlankBuffer); }).detach();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002009}
2010
Sungtak Lee99144332023-01-26 11:03:14 +00002011void CCodec::release(bool sendCallback, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002012 std::shared_ptr<Codec2Client::Component> comp;
2013 {
2014 Mutexed<State>::Locked state(mState);
2015 if (state->get() == RELEASED) {
2016 if (sendCallback) {
2017 state.unlock();
2018 mCallback->onReleaseCompleted();
2019 state.lock();
2020 }
2021 return;
2022 }
2023 comp = state->comp;
2024 }
Sungtak Leec0c05962023-10-25 08:14:13 +00002025 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->release().
2026 // But in the case some HAL implementations hang forever on comp->release().
2027 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
2028 // completing release()).
2029 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
2030 // prior to comp->release().
2031 // See also b/300350761.
Sungtak Lee99144332023-01-26 11:03:14 +00002032 mChannel->stopUseOutputSurface(pushBlankBuffer);
Sungtak Leec0c05962023-10-25 08:14:13 +00002033 comp->release();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002034
2035 {
2036 Mutexed<State>::Locked state(mState);
2037 state->set(RELEASED);
2038 state->comp.reset();
2039 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002040 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002041 if (sendCallback) {
2042 mCallback->onReleaseCompleted();
2043 }
2044}
2045
Sungtak Lee214ce612023-11-01 10:01:13 +00002046status_t CCodec::setSurface(const sp<Surface> &surface, uint32_t generation) {
Sungtak Lee99144332023-01-26 11:03:14 +00002047 bool pushBlankBuffer = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002048 {
2049 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2050 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002051 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
2052 status_t err = OK;
2053
Wonsik Kim75e22f42021-04-14 23:34:51 -07002054 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002055 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07002056 nativeWindow.get(),
2057 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
2058 if (err != OK) {
2059 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
2060 nativeWindow.get(), config->mSidebandHandle->handle(), err);
2061 return err;
2062 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002063 } else {
2064 // Explicitly reset the sideband handle of the window for
2065 // non-tunneled video in case the window was previously used
2066 // for a tunneled video playback.
2067 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
2068 if (err != OK) {
2069 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
2070 return err;
2071 }
ted.sun765db4d2020-06-23 14:03:41 +08002072 }
Sungtak Lee99144332023-01-26 11:03:14 +00002073 pushBlankBuffer = config->mPushBlankBuffersOnStop;
ted.sun765db4d2020-06-23 14:03:41 +08002074 }
Sungtak Lee214ce612023-11-01 10:01:13 +00002075 return mChannel->setSurface(surface, generation, pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002076}
2077
2078void CCodec::signalFlush() {
2079 status_t err = [this] {
2080 Mutexed<State>::Locked state(mState);
2081 if (state->get() == FLUSHED) {
2082 return ALREADY_EXISTS;
2083 }
2084 if (state->get() != RUNNING) {
2085 return UNKNOWN_ERROR;
2086 }
2087 state->set(FLUSHING);
2088 return OK;
2089 }();
2090 switch (err) {
2091 case ALREADY_EXISTS:
2092 mCallback->onFlushCompleted();
2093 return;
2094 case OK:
2095 break;
2096 default:
2097 mCallback->onError(err, ACTION_CODE_FATAL);
2098 return;
2099 }
2100
2101 mChannel->stop();
2102 (new AMessage(kWhatFlush, this))->post();
2103}
2104
2105void CCodec::flush() {
2106 std::shared_ptr<Codec2Client::Component> comp;
2107 auto checkFlushing = [this, &comp] {
2108 Mutexed<State>::Locked state(mState);
2109 if (state->get() != FLUSHING) {
2110 return UNKNOWN_ERROR;
2111 }
2112 comp = state->comp;
2113 return OK;
2114 };
2115 if (tryAndReportOnError(checkFlushing) != OK) {
2116 return;
2117 }
2118
2119 std::list<std::unique_ptr<C2Work>> flushedWork;
2120 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2121 {
2122 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2123 flushedWork.splice(flushedWork.end(), *queue);
2124 }
2125 if (err != C2_OK) {
2126 // TODO: convert err into status_t
2127 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2128 }
2129
2130 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002131
2132 {
2133 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002134 if (state->get() == FLUSHING) {
2135 state->set(FLUSHED);
2136 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002137 }
2138 mCallback->onFlushCompleted();
2139}
2140
2141void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002142 std::shared_ptr<Codec2Client::Component> comp;
2143 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002144 Mutexed<State>::Locked state(mState);
2145 if (state->get() != FLUSHED) {
2146 return UNKNOWN_ERROR;
2147 }
2148 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002149 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002150 return OK;
2151 };
2152 if (tryAndReportOnError(setResuming) != OK) {
2153 return;
2154 }
2155
Wonsik Kime75a5da2020-02-14 17:29:03 -08002156 {
2157 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2158 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002159 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002160 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002161 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002162 }
2163
Arun Johnson106fe7a2023-04-26 17:49:43 +00002164 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
Arun Johnson326166e2023-07-28 19:11:52 +00002165 status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers, true);
Arun Johnson106fe7a2023-04-26 17:49:43 +00002166 if (err != OK) {
2167 if (err == NO_MEMORY) {
2168 // NO_MEMORY happens here when all the buffers are still
2169 // with the codec. That is not an error as it is momentarily
2170 // and the buffers are send to the client as soon as the codec
2171 // releases them
2172 ALOGI("Resuming with all input buffers still with codec");
2173 } else {
2174 ALOGE("Resume request for Input Buffers failed");
2175 mCallback->onError(err, ACTION_CODE_FATAL);
2176 return;
2177 }
2178 }
2179
2180 // channel start should be called after prepareInitialBuffers
2181 // Calling before can cause a failure during prepare when
2182 // buffers are sent to the client before preparation from onWorkDone
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002183 (void)mChannel->start(nullptr, nullptr, [&]{
2184 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2185 const std::unique_ptr<Config> &config = *configLocked;
2186 return config->mBuffersBoundToCodec;
2187 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002188 {
2189 Mutexed<State>::Locked state(mState);
2190 if (state->get() != RESUMING) {
2191 state.unlock();
2192 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2193 state.lock();
2194 return;
2195 }
2196 state->set(RUNNING);
2197 }
2198
Wonsik Kim34b28b42022-05-20 15:49:32 -07002199 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002200}
2201
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002202void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002203 std::shared_ptr<Codec2Client::Component> comp;
2204 auto checkState = [this, &comp] {
2205 Mutexed<State>::Locked state(mState);
2206 if (state->get() == RELEASED) {
2207 return INVALID_OPERATION;
2208 }
2209 comp = state->comp;
2210 return OK;
2211 };
2212 if (tryAndReportOnError(checkState) != OK) {
2213 return;
2214 }
2215
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002216 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2217 // the behavior here.
2218 sp<AMessage> params = msg;
2219 int32_t bitrate;
2220 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2221 params = msg->dup();
2222 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2223 }
2224
Houxiang Dai5a97b472021-03-22 17:56:04 +08002225 int32_t syncId = 0;
2226 if (params->findInt32("audio-hw-sync", &syncId)
2227 || params->findInt32("hw-av-sync-id", &syncId)) {
2228 configureTunneledVideoPlayback(comp, nullptr, params);
2229 }
2230
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002231 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2232 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002233
2234 /**
2235 * Handle input surface parameters
2236 */
2237 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002238 && (config->mDomain & Config::IS_ENCODER)
2239 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002240 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002241
2242 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2243 config->mISConfig->mStopped = false;
2244 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2245 config->mISConfig->mStopped = true;
2246 }
2247
2248 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002249 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002250 config->mISConfig->mSuspended = value;
2251 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002252 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002253 }
2254
2255 (void)config->mInputSurface->configure(*config->mISConfig);
2256 if (config->mISConfig->mStopped) {
2257 config->mInputFormat->setInt64(
2258 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2259 }
2260 }
2261
2262 std::vector<std::unique_ptr<C2Param>> configUpdate;
2263 (void)config->getConfigUpdateFromSdkParams(
2264 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2265 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2266 // Parameter synchronization is not defined when using input surface. For now, route
2267 // these directly to the component.
2268 if (config->mInputSurface == nullptr
2269 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2270 || comp->getName().find("c2.android.") == 0)) {
2271 mChannel->setParameters(configUpdate);
2272 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002273 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002274 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002275 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002276 }
2277}
2278
2279void CCodec::signalEndOfInputStream() {
2280 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2281}
2282
2283void CCodec::signalRequestIDRFrame() {
2284 std::shared_ptr<Codec2Client::Component> comp;
2285 {
2286 Mutexed<State>::Locked state(mState);
2287 if (state->get() == RELEASED) {
2288 ALOGD("no IDR request sent since component is released");
2289 return;
2290 }
2291 comp = state->comp;
2292 }
2293 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002294 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2295 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002296 std::vector<std::unique_ptr<C2Param>> params;
2297 params.push_back(
2298 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2299 config->setParameters(comp, params, C2_MAY_BLOCK);
2300}
2301
Wonsik Kim874ad382021-03-12 09:59:36 -08002302status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2303 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2304 const std::unique_ptr<Config> &config = *configLocked;
2305 return config->querySupportedParameters(names);
2306}
2307
2308status_t CCodec::describeParameter(
2309 const std::string &name, CodecParameterDescriptor *desc) {
2310 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2311 const std::unique_ptr<Config> &config = *configLocked;
2312 return config->describe(name, desc);
2313}
2314
2315status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2316 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2317 if (!comp) {
2318 return INVALID_OPERATION;
2319 }
2320 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2321 const std::unique_ptr<Config> &config = *configLocked;
2322 return config->subscribeToVendorConfigUpdate(comp, names);
2323}
2324
2325status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2326 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2327 if (!comp) {
2328 return INVALID_OPERATION;
2329 }
2330 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2331 const std::unique_ptr<Config> &config = *configLocked;
2332 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2333}
2334
Wonsik Kimab34ed62019-01-31 15:28:46 -08002335void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002336 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002337 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002338 bool shouldPost = queue->empty();
Wonsik Kimab34ed62019-01-31 15:28:46 -08002339 queue->splice(queue->end(), workItems);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002340 if (shouldPost) {
2341 (new AMessage(kWhatWorkDone, this))->post();
2342 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002343 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002344}
2345
Wonsik Kimab34ed62019-01-31 15:28:46 -08002346void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2347 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002348 if (arrayIndex == 0) {
2349 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002350 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2351 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002352 if (config->mInputSurface) {
2353 config->mInputSurface->onInputBufferDone(frameIndex);
2354 }
2355 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002356}
2357
2358void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2359 TimePoint now = std::chrono::steady_clock::now();
2360 CCodecWatchdog::getInstance()->watch(this);
2361 switch (msg->what()) {
2362 case kWhatAllocate: {
2363 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002364 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002365 sp<RefBase> obj;
2366 CHECK(msg->findObject("codecInfo", &obj));
2367 allocate((MediaCodecInfo *)obj.get());
2368 break;
2369 }
2370 case kWhatConfigure: {
2371 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002372 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002373 sp<AMessage> format;
2374 CHECK(msg->findMessage("format", &format));
2375 configure(format);
2376 break;
2377 }
2378 case kWhatStart: {
2379 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002380 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002381 start();
2382 break;
2383 }
2384 case kWhatStop: {
2385 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002386 setDeadline(now, 1500ms, "stop");
Sungtak Lee99144332023-01-26 11:03:14 +00002387 int32_t pushBlankBuffer;
2388 if (!msg->findInt32("pushBlankBuffer", &pushBlankBuffer)) {
2389 pushBlankBuffer = 0;
2390 }
2391 stop(static_cast<bool>(pushBlankBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002392 break;
2393 }
2394 case kWhatFlush: {
2395 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002396 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002397 flush();
2398 break;
2399 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002400 case kWhatRelease: {
2401 mChannel->release();
2402 mClient.reset();
2403 mClientListener.reset();
2404 break;
2405 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002406 case kWhatCreateInputSurface: {
2407 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002408 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002409 createInputSurface();
2410 break;
2411 }
2412 case kWhatSetInputSurface: {
2413 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002414 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002415 sp<RefBase> obj;
2416 CHECK(msg->findObject("surface", &obj));
2417 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2418 setInputSurface(surface);
2419 break;
2420 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002421 case kWhatWorkDone: {
2422 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002423 bool shouldPost = false;
2424 {
2425 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2426 if (queue->empty()) {
2427 break;
2428 }
2429 work.swap(queue->front());
2430 queue->pop_front();
2431 shouldPost = !queue->empty();
2432 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002433 if (shouldPost) {
2434 (new AMessage(kWhatWorkDone, this))->post();
2435 }
2436
Pawin Vongmasa36653902018-11-15 00:10:25 -08002437 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002438 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002439 sp<AMessage> outputFormat = nullptr;
2440 {
2441 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2442 const std::unique_ptr<Config> &config = *configLocked;
2443 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2444 config->watch<C2StreamInitDataInfo::output>();
2445 if (!work->worklets.empty()
2446 && (work->worklets.front()->output.flags
2447 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002448
Wonsik Kim75e22f42021-04-14 23:34:51 -07002449 // copy buffer info to config
2450 std::vector<std::unique_ptr<C2Param>> updates;
2451 for (const std::unique_ptr<C2Param> &param
2452 : work->worklets.front()->output.configUpdate) {
2453 updates.push_back(C2Param::Copy(*param));
2454 }
2455 unsigned stream = 0;
2456 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2457 work->worklets.front()->output.buffers;
2458 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2459 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2460 // move all info into output-stream #0 domain
2461 updates.emplace_back(
2462 C2Param::CopyAsStream(*info, true /* output */, stream));
2463 }
2464
2465 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2466 // for now only do the first block
2467 if (!blocks.empty()) {
2468 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2469 // block.crop().left, block.crop().top,
2470 // block.crop().width, block.crop().height,
2471 // block.width(), block.height());
2472 const C2ConstGraphicBlock &block = blocks[0];
2473 updates.emplace_back(new C2StreamCropRectInfo::output(
2474 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002475 }
2476 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002477 }
George Burgess IVc813a592020-02-22 22:54:44 -08002478
Wonsik Kim75e22f42021-04-14 23:34:51 -07002479 sp<AMessage> oldFormat = config->mOutputFormat;
2480 config->updateConfiguration(updates, config->mOutputDomain);
2481 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002482
Wonsik Kim75e22f42021-04-14 23:34:51 -07002483 // copy standard infos to graphic buffers if not already present (otherwise, we
2484 // may overwrite the actual intermediate value with a final value)
2485 stream = 0;
2486 const static C2Param::Index stdGfxInfos[] = {
2487 C2StreamRotationInfo::output::PARAM_TYPE,
2488 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2489 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2490 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Taehwan Kim2d222b82022-05-12 14:19:26 +09002491 C2StreamHdr10PlusInfo::output::PARAM_TYPE, // will be deprecated
2492 C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE,
Wonsik Kim75e22f42021-04-14 23:34:51 -07002493 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2494 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2495 };
2496 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2497 if (buf->data().graphicBlocks().size()) {
2498 for (C2Param::Index ix : stdGfxInfos) {
2499 if (!buf->hasInfo(ix)) {
2500 const C2Param *param =
2501 config->getConfigParameterValue(ix.withStream(stream));
2502 if (param) {
2503 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2504 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2505 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002506 }
2507 }
2508 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002509 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002510 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002511 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002512 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302513 if (work->worklets.empty()
2514 || !work->worklets.back()
2515 || (work->worklets.back()->output.flags
2516 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2517 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2518 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002519 }
2520 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002521 initData = initDataWatcher.update();
2522 AmendOutputFormatWithCodecSpecificData(
2523 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2524 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002525 }
2526 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002527 }
2528 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002529 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Songyue Han1e6769b2023-08-30 18:09:27 +00002530 // log metrics to MediaCodec
2531 if (mMetrics->countEntries() == 0) {
2532 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2533 const std::unique_ptr<Config> &config = *configLocked;
2534 uint32_t pf = PIXEL_FORMAT_UNKNOWN;
2535 if (!config->mInputSurface) {
2536 pf = mChannel->getBuffersPixelFormat(config->mDomain & Config::IS_ENCODER);
Songyue Hanad01f6a2023-08-17 05:45:35 +00002537 } else {
2538 pf = config->mInputSurface->getPixelFormat();
Songyue Han1e6769b2023-08-30 18:09:27 +00002539 }
2540 if (pf != PIXEL_FORMAT_UNKNOWN) {
2541 mMetrics->setInt64(kCodecPixelFormat, pf);
2542 mCallback->onMetricsUpdated(mMetrics);
2543 }
2544 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002545 break;
2546 }
2547 case kWhatWatch: {
2548 // watch message already posted; no-op.
2549 break;
2550 }
2551 default: {
2552 ALOGE("unrecognized message");
2553 break;
2554 }
2555 }
2556 setDeadline(TimePoint::max(), 0ms, "none");
2557}
2558
2559void CCodec::setDeadline(
2560 const TimePoint &now,
2561 const std::chrono::milliseconds &timeout,
2562 const char *name) {
2563 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2564 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2565 deadline->set(now + (timeout * mult), name);
2566}
2567
ted.sun765db4d2020-06-23 14:03:41 +08002568status_t CCodec::configureTunneledVideoPlayback(
2569 std::shared_ptr<Codec2Client::Component> comp,
2570 sp<NativeHandle> *sidebandHandle,
2571 const sp<AMessage> &msg) {
2572 std::vector<std::unique_ptr<C2SettingResult>> failures;
2573
2574 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2575 C2PortTunneledModeTuning::output::AllocUnique(
2576 1,
2577 C2PortTunneledModeTuning::Struct::SIDEBAND,
2578 C2PortTunneledModeTuning::Struct::REALTIME,
2579 0);
2580 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2581 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2582 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2583 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2584 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2585 } else {
2586 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2587 tunneledPlayback->setFlexCount(0);
2588 }
2589 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2590 if (c2err != C2_OK) {
2591 return UNKNOWN_ERROR;
2592 }
2593
Houxiang Dai5a97b472021-03-22 17:56:04 +08002594 if (sidebandHandle == nullptr) {
2595 return OK;
2596 }
2597
ted.sun765db4d2020-06-23 14:03:41 +08002598 std::vector<std::unique_ptr<C2Param>> params;
2599 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2600 if (c2err == C2_OK && params.size() == 1u) {
2601 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2602 C2PortTunnelHandleTuning::output::From(params[0].get());
2603 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2604 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2605 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2606 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2607 memcpy(handle->data, videoTunnelSideband->m.values,
2608 sizeof(int32_t) * videoTunnelSideband->flexCount());
2609 return OK;
2610 } else {
2611 return NO_MEMORY;
2612 }
2613 }
2614 return UNKNOWN_ERROR;
2615}
2616
Pawin Vongmasa36653902018-11-15 00:10:25 -08002617void CCodec::initiateReleaseIfStuck() {
Shrikara B3b87a532022-08-26 14:18:14 +05302618 std::string name;
2619 bool pendingDeadline = false;
2620 {
2621 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2622 if (deadline->get() < std::chrono::steady_clock::now()) {
2623 name = deadline->getName();
2624 }
2625 if (deadline->get() != TimePoint::max()) {
2626 pendingDeadline = true;
2627 }
2628 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002629 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002630 // We're not stuck.
2631 if (pendingDeadline) {
2632 // If we are not stuck yet but still has deadline coming up,
2633 // post watch message to check back later.
2634 (new AMessage(kWhatWatch, this))->post();
2635 }
2636 return;
2637 }
2638
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002639 C2String compName;
2640 {
2641 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002642 if (!state->comp) {
2643 ALOGD("previous call to %s exceeded timeout "
2644 "and the component is already released", name.c_str());
2645 return;
2646 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002647 compName = state->comp->getName();
2648 }
2649 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2650
Pawin Vongmasa36653902018-11-15 00:10:25 -08002651 initiateRelease(false);
2652 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2653}
2654
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002655// static
2656PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002657 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002658 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002659 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002660 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2661 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002662 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002663 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2664 sp<IGraphicBufferProducer> gbp;
2665 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2666 status_t err = gbs->initCheck();
2667 if (err != OK) {
2668 ALOGE("Failed to create persistent input surface: error %d", err);
2669 return nullptr;
2670 }
2671 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002672 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002673 } else {
2674 return nullptr;
2675 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002676 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002677 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002678 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002679 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002680 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002681}
2682
Wonsik Kimffb889a2020-05-28 11:32:25 -07002683class IntfCache {
2684public:
2685 IntfCache() = default;
2686
2687 status_t init(const std::string &name) {
2688 std::shared_ptr<Codec2Client::Interface> intf{
2689 Codec2Client::CreateInterfaceByName(name.c_str())};
2690 if (!intf) {
2691 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2692 mInitStatus = NO_INIT;
2693 return NO_INIT;
2694 }
2695 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2696 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2697 C2ParamField{&sUsage, &sUsage.value}));
2698 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2699 if (err != C2_OK) {
2700 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2701 name.c_str(), err);
2702 mFields[0].status = err;
2703 }
2704 std::vector<std::unique_ptr<C2Param>> params;
2705 err = intf->query(
2706 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09002707 {
2708 C2StreamBufferTypeSetting::input::PARAM_TYPE,
2709 C2PortAllocatorsTuning::input::PARAM_TYPE
2710 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07002711 C2_MAY_BLOCK,
2712 &params);
2713 if (err != C2_OK && err != C2_BAD_INDEX) {
2714 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2715 name.c_str(), err);
2716 }
2717 while (!params.empty()) {
2718 C2Param *param = params.back().release();
2719 params.pop_back();
2720 if (!param) {
2721 continue;
2722 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002723 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
2724 mInputStreamFormat.reset(
2725 C2StreamBufferTypeSetting::input::From(param));
2726 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002727 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002728 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002729 }
2730 }
2731 mInitStatus = OK;
2732 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002733 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002734
2735 status_t initCheck() const { return mInitStatus; }
2736
2737 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2738 CHECK_EQ(1u, mFields.size());
2739 return mFields[0];
2740 }
2741
2742 const C2ApiFeaturesSetting &getApiFeatures() const {
2743 return mApiFeatures;
2744 }
2745
Taehwan Kim900b49c2021-12-13 11:16:22 +09002746 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
2747 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
2748 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
2749 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
2750 param->invalidate();
2751 return param;
2752 }();
2753 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
2754 }
2755
Wonsik Kimffb889a2020-05-28 11:32:25 -07002756 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2757 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2758 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2759 C2PortAllocatorsTuning::input::AllocUnique(0);
2760 param->invalidate();
2761 return param;
2762 }();
2763 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2764 }
2765
2766private:
2767 status_t mInitStatus{NO_INIT};
2768
2769 std::vector<C2FieldSupportedValuesQuery> mFields;
2770 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09002771 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002772 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2773};
2774
2775static const IntfCache &GetIntfCache(const std::string &name) {
2776 static IntfCache sNullIntfCache;
2777 static std::mutex sMutex;
2778 static std::map<std::string, IntfCache> sCache;
2779 std::unique_lock<std::mutex> lock{sMutex};
2780 auto it = sCache.find(name);
2781 if (it == sCache.end()) {
2782 lock.unlock();
2783 IntfCache intfCache;
2784 status_t err = intfCache.init(name);
2785 if (err != OK) {
2786 return sNullIntfCache;
2787 }
2788 lock.lock();
2789 it = sCache.insert({name, std::move(intfCache)}).first;
2790 }
2791 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002792}
2793
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002794static status_t GetCommonAllocatorIds(
2795 const std::vector<std::string> &names,
2796 C2Allocator::type_t type,
2797 std::set<C2Allocator::id_t> *ids) {
2798 int poolMask = GetCodec2PoolMask();
2799 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2800 C2Allocator::id_t defaultAllocatorId =
2801 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2802
2803 ids->clear();
2804 if (names.empty()) {
2805 return OK;
2806 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002807 bool firstIteration = true;
2808 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002809 const IntfCache &intfCache = GetIntfCache(name);
2810 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002811 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002812 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002813 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
2814 if (streamFormat) {
2815 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
2816 if (streamFormat.value == C2BufferData::GRAPHIC
2817 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
2818 allocatorType = C2Allocator::GRAPHIC;
2819 }
2820
2821 if (type != allocatorType) {
2822 // requested type is not supported at input allocators
2823 ids->clear();
2824 ids->insert(defaultAllocatorId);
2825 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
2826 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
2827 break;
2828 }
2829 }
2830
Wonsik Kimffb889a2020-05-28 11:32:25 -07002831 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002832 if (firstIteration) {
2833 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002834 if (allocators && allocators.flexCount() > 0) {
2835 ids->insert(allocators.m.values,
2836 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002837 }
2838 if (ids->empty()) {
2839 // The component does not advertise allocators. Use default.
2840 ids->insert(defaultAllocatorId);
2841 }
2842 continue;
2843 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002844 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002845 if (allocators && allocators.flexCount() > 0) {
2846 filtered = true;
2847 for (auto it = ids->begin(); it != ids->end(); ) {
2848 bool found = false;
2849 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2850 if (allocators.m.values[j] == *it) {
2851 found = true;
2852 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002853 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002854 }
2855 if (found) {
2856 ++it;
2857 } else {
2858 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002859 }
2860 }
2861 }
2862 if (!filtered) {
2863 // The component does not advertise supported allocators. Use default.
2864 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2865 if (ids->size() != (containsDefault ? 1 : 0)) {
2866 ids->clear();
2867 if (containsDefault) {
2868 ids->insert(defaultAllocatorId);
2869 }
2870 }
2871 }
2872 }
2873 // Finally, filter with pool masks
2874 for (auto it = ids->begin(); it != ids->end(); ) {
2875 if ((poolMask >> *it) & 1) {
2876 ++it;
2877 } else {
2878 it = ids->erase(it);
2879 }
2880 }
2881 return OK;
2882}
2883
2884static status_t CalculateMinMaxUsage(
2885 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2886 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2887 *minUsage = 0;
2888 *maxUsage = ~0ull;
2889 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002890 const IntfCache &intfCache = GetIntfCache(name);
2891 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002892 continue;
2893 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002894 const C2FieldSupportedValuesQuery &usageSupportedValues =
2895 intfCache.getUsageSupportedValues();
2896 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002897 continue;
2898 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002899 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002900 if (supported.type != C2FieldSupportedValues::FLAGS) {
2901 continue;
2902 }
2903 if (supported.values.empty()) {
2904 *maxUsage = 0;
2905 continue;
2906 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08002907 if (supported.values.size() > 1) {
2908 *minUsage |= supported.values[1].u64;
2909 } else {
2910 *minUsage |= supported.values[0].u64;
2911 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002912 int64_t currentMaxUsage = 0;
2913 for (const C2Value::Primitive &flags : supported.values) {
2914 currentMaxUsage |= flags.u64;
2915 }
2916 *maxUsage &= currentMaxUsage;
2917 }
2918 return OK;
2919}
2920
2921// static
2922status_t CCodec::CanFetchLinearBlock(
2923 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002924 for (const std::string &name : names) {
2925 const IntfCache &intfCache = GetIntfCache(name);
2926 if (intfCache.initCheck() != OK) {
2927 continue;
2928 }
2929 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2930 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2931 *isCompatible = false;
2932 return OK;
2933 }
2934 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002935 std::set<C2Allocator::id_t> allocators;
2936 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2937 if (allocators.empty()) {
2938 *isCompatible = false;
2939 return OK;
2940 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002941
2942 uint64_t minUsage = 0;
2943 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002944 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002945 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002946 *isCompatible = ((maxUsage & minUsage) == minUsage);
2947 return OK;
2948}
2949
2950static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2951 static std::mutex sMutex{};
2952 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2953 std::unique_lock<std::mutex> lock{sMutex};
2954 std::shared_ptr<C2BlockPool> pool;
2955 auto it = sPools.find(allocId);
2956 if (it == sPools.end()) {
2957 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2958 if (err == OK) {
2959 sPools.emplace(allocId, pool);
2960 } else {
2961 pool.reset();
2962 }
2963 } else {
2964 pool = it->second;
2965 }
2966 return pool;
2967}
2968
2969// static
2970std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2971 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002972 std::set<C2Allocator::id_t> allocators;
2973 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2974 if (allocators.empty()) {
2975 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2976 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002977
2978 uint64_t minUsage = 0;
2979 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002980 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002981 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002982 if ((maxUsage & minUsage) != minUsage) {
2983 allocators.clear();
2984 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2985 }
2986 std::shared_ptr<C2LinearBlock> block;
2987 for (C2Allocator::id_t allocId : allocators) {
2988 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2989 if (!pool) {
2990 continue;
2991 }
2992 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2993 if (err != C2_OK || !block) {
2994 block.reset();
2995 continue;
2996 }
2997 break;
2998 }
2999 return block;
3000}
3001
3002// static
3003status_t CCodec::CanFetchGraphicBlock(
3004 const std::vector<std::string> &names, bool *isCompatible) {
3005 uint64_t minUsage = 0;
3006 uint64_t maxUsage = ~0ull;
3007 std::set<C2Allocator::id_t> allocators;
3008 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3009 if (allocators.empty()) {
3010 *isCompatible = false;
3011 return OK;
3012 }
3013 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3014 *isCompatible = ((maxUsage & minUsage) == minUsage);
3015 return OK;
3016}
3017
3018// static
3019std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
3020 int32_t width,
3021 int32_t height,
3022 int32_t format,
3023 uint64_t usage,
3024 const std::vector<std::string> &names) {
3025 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
3026 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
3027 ALOGD("Unrecognized pixel format: %d", format);
3028 return nullptr;
3029 }
3030 uint64_t minUsage = 0;
3031 uint64_t maxUsage = ~0ull;
3032 std::set<C2Allocator::id_t> allocators;
3033 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3034 if (allocators.empty()) {
3035 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3036 }
3037 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3038 minUsage |= usage;
3039 if ((maxUsage & minUsage) != minUsage) {
3040 allocators.clear();
3041 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3042 }
3043 std::shared_ptr<C2GraphicBlock> block;
3044 for (C2Allocator::id_t allocId : allocators) {
3045 std::shared_ptr<C2BlockPool> pool;
3046 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3047 if (err != C2_OK || !pool) {
3048 continue;
3049 }
3050 err = pool->fetchGraphicBlock(
3051 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
3052 if (err != C2_OK || !block) {
3053 block.reset();
3054 continue;
3055 }
3056 break;
3057 }
3058 return block;
3059}
3060
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003061} // namespace android