blob: 8013f8e9be9d84da2c7a4a43fce4d55477668bda [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodec"
19#include <utils/Log.h>
20
21#include <sstream>
22#include <thread>
23
24#include <C2Config.h>
25#include <C2Debug.h>
26#include <C2ParamInternal.h>
27#include <C2PlatformSupport.h>
28
Pawin Vongmasa36653902018-11-15 00:10:25 -080029#include <android/IOMXBufferSource.h>
Pawin Vongmasabf69de92019-10-29 06:21:27 -070030#include <android/hardware/media/c2/1.0/IInputSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080031#include <android/hardware/media/omx/1.0/IGraphicBufferSource.h>
32#include <android/hardware/media/omx/1.0/IOmx.h>
Wonsik Kim50811882022-04-28 15:57:27 -070033#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080034#include <android-base/stringprintf.h>
35#include <cutils/properties.h>
36#include <gui/IGraphicBufferProducer.h>
37#include <gui/Surface.h>
38#include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070039#include <media/omx/1.0/WOmxNode.h>
40#include <media/openmax/OMX_Core.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080041#include <media/openmax/OMX_IndexExt.h>
Wonsik Kim1f5063d2021-05-03 15:41:17 -070042#include <media/stagefright/foundation/avc_utils.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070043#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
44#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070045#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080046#include <media/stagefright/BufferProducerWrapper.h>
47#include <media/stagefright/MediaCodecConstants.h>
48#include <media/stagefright/PersistentSurface.h>
ted.sun765db4d2020-06-23 14:03:41 +080049#include <utils/NativeHandle.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080050
51#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080052#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070053#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080054#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080055#include "InputSurfaceWrapper.h"
56
57extern "C" android::PersistentSurface *CreateInputSurface();
58
59namespace android {
60
61using namespace std::chrono_literals;
62using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
63using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080064using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080065
Wonsik Kim9917d4a2019-10-24 12:56:38 -070066typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070067typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070068
Pawin Vongmasa36653902018-11-15 00:10:25 -080069namespace {
70
71class CCodecWatchdog : public AHandler {
72private:
73 enum {
74 kWhatWatch,
75 };
76 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
77
78public:
79 static sp<CCodecWatchdog> getInstance() {
80 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
81 static std::once_flag flag;
82 // Call Init() only once.
83 std::call_once(flag, Init, instance);
84 return instance;
85 }
86
87 ~CCodecWatchdog() = default;
88
89 void watch(sp<CCodec> codec) {
90 bool shouldPost = false;
91 {
92 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
93 // If a watch message is in flight, piggy-back this instance as well.
94 // Otherwise, post a new watch message.
95 shouldPost = codecs->empty();
96 codecs->emplace(codec);
97 }
98 if (shouldPost) {
99 ALOGV("posting watch message");
100 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
101 }
102 }
103
104protected:
105 void onMessageReceived(const sp<AMessage> &msg) {
106 switch (msg->what()) {
107 case kWhatWatch: {
108 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
109 ALOGV("watch for %zu codecs", codecs->size());
110 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
111 sp<CCodec> codec = it->promote();
112 if (codec == nullptr) {
113 continue;
114 }
115 codec->initiateReleaseIfStuck();
116 }
117 codecs->clear();
118 break;
119 }
120
121 default: {
122 TRESPASS("CCodecWatchdog: unrecognized message");
123 }
124 }
125 }
126
127private:
128 CCodecWatchdog() : mLooper(new ALooper) {}
129
130 static void Init(const sp<CCodecWatchdog> &thiz) {
131 ALOGV("Init");
132 thiz->mLooper->setName("CCodecWatchdog");
133 thiz->mLooper->registerHandler(thiz);
134 thiz->mLooper->start();
135 }
136
137 sp<ALooper> mLooper;
138
139 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
140};
141
142class C2InputSurfaceWrapper : public InputSurfaceWrapper {
143public:
144 explicit C2InputSurfaceWrapper(
145 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
146 mSurface(surface) {
147 }
148
149 ~C2InputSurfaceWrapper() override = default;
150
151 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
152 if (mConnection != nullptr) {
153 return ALREADY_EXISTS;
154 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800155 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800156 }
157
158 void disconnect() override {
159 if (mConnection != nullptr) {
160 mConnection->disconnect();
161 mConnection = nullptr;
162 }
163 }
164
165 status_t start() override {
166 // InputSurface does not distinguish started state
167 return OK;
168 }
169
170 status_t signalEndOfInputStream() override {
171 C2InputSurfaceEosTuning eos(true);
172 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800173 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800174 if (err != C2_OK) {
175 return UNKNOWN_ERROR;
176 }
177 return OK;
178 }
179
180 status_t configure(Config &config __unused) {
181 // TODO
182 return OK;
183 }
184
185private:
186 std::shared_ptr<Codec2Client::InputSurface> mSurface;
187 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
188};
189
190class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
191public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700192 typedef hardware::media::omx::V1_0::Status OmxStatus;
193
Pawin Vongmasa36653902018-11-15 00:10:25 -0800194 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700195 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800196 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700197 uint32_t height,
198 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800199 : mSource(source), mWidth(width), mHeight(height) {
200 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700201 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800202 }
203 ~GraphicBufferSourceWrapper() override = default;
204
205 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
206 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700207 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800208 mNode->setFrameSize(mWidth, mHeight);
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700209 // Usage is queried during configure(), so setting it beforehand.
Sungtak Leeb6caaf82023-02-02 00:59:01 +0000210 // 64 bit set parameter is existing only in C2OMXNode.
211 OMX_U64 usage64 = mConfig.mUsage;
212 status_t res = mNode->setParameter(
213 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits64,
214 &usage64, sizeof(usage64));
215
216 if (res != OK) {
217 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
218 (void)mNode->setParameter(
219 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
220 &usage, sizeof(usage));
221 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700222
Yanqiang Fanc56f3e62021-09-28 16:54:07 +0800223 return GetStatus(mSource->configure(
224 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800225 }
226
227 void disconnect() override {
228 if (mNode == nullptr) {
229 return;
230 }
231 sp<IOMXBufferSource> source = mNode->getSource();
232 if (source == nullptr) {
233 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
234 return;
235 }
236 source->onOmxIdle();
237 source->onOmxLoaded();
238 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700239 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800240 }
241
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700242 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
243 if (status.isOk()) {
244 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
245 } else if (status.isDeadObject()) {
246 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800247 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700248 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800249 }
250
251 status_t start() override {
252 sp<IOMXBufferSource> source = mNode->getSource();
253 if (source == nullptr) {
254 return NO_INIT;
255 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900256
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800257 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800258 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900259
Wonsik Kim34d66012021-03-01 16:40:33 -0800260 OMX_PARAM_PORTDEFINITIONTYPE param;
261 param.nPortIndex = kPortIndexInput;
262 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
263 &param, sizeof(param));
264 if (err == OK) {
265 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900266 }
267
268 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800269 source->onInputBufferAdded(i);
270 }
271
272 source->onOmxExecuting();
273 return OK;
274 }
275
276 status_t signalEndOfInputStream() override {
277 return GetStatus(mSource->signalEndOfInputStream());
278 }
279
280 status_t configure(Config &config) {
281 std::stringstream status;
282 status_t err = OK;
283
284 // handle each configuration granually, in case we need to handle part of the configuration
285 // elsewhere
286
287 // TRICKY: we do not unset frame delay repeating
288 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
289 int64_t us = 1e6 / config.mMinFps + 0.5;
290 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
291 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
292 if (res != OK) {
293 status << " (=> " << asString(res) << ")";
294 err = res;
295 }
296 mConfig.mMinFps = config.mMinFps;
297 }
298
299 // pts gap
300 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
301 if (mNode != nullptr) {
302 OMX_PARAM_U32TYPE ptrGapParam = {};
303 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700304 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800305 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
306 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700307 // float -> uint32_t is undefined if the value is negative.
308 // First convert to int32_t to ensure the expected behavior.
309 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800310 (void)mNode->setParameter(
311 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
312 &ptrGapParam, sizeof(ptrGapParam));
313 }
314 }
315
316 // max fps
317 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700318 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800319 && config.mMaxFps != mConfig.mMaxFps) {
320 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
321 status << " maxFps=" << config.mMaxFps;
322 if (res != OK) {
323 status << " (=> " << asString(res) << ")";
324 err = res;
325 }
326 mConfig.mMaxFps = config.mMaxFps;
327 }
328
329 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
330 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
331 status << " timeOffset " << config.mTimeOffsetUs << "us";
332 if (res != OK) {
333 status << " (=> " << asString(res) << ")";
334 err = res;
335 }
336 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
337 }
338
339 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
340 status_t res =
341 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
342 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
343 if (res != OK) {
344 status << " (=> " << asString(res) << ")";
345 err = res;
346 }
347 mConfig.mCaptureFps = config.mCaptureFps;
348 mConfig.mCodedFps = config.mCodedFps;
349 }
350
351 if (config.mStartAtUs != mConfig.mStartAtUs
352 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
353 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
354 status << " start at " << config.mStartAtUs << "us";
355 if (res != OK) {
356 status << " (=> " << asString(res) << ")";
357 err = res;
358 }
359 mConfig.mStartAtUs = config.mStartAtUs;
360 mConfig.mStopped = config.mStopped;
361 }
362
363 // suspend-resume
364 if (config.mSuspended != mConfig.mSuspended) {
365 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
366 status << " " << (config.mSuspended ? "suspend" : "resume")
367 << " at " << config.mSuspendAtUs << "us";
368 if (res != OK) {
369 status << " (=> " << asString(res) << ")";
370 err = res;
371 }
372 mConfig.mSuspended = config.mSuspended;
373 mConfig.mSuspendAtUs = config.mSuspendAtUs;
374 }
375
376 if (config.mStopped != mConfig.mStopped && config.mStopped) {
377 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
378 status << " stop at " << config.mStopAtUs << "us";
379 if (res != OK) {
380 status << " (=> " << asString(res) << ")";
381 err = res;
382 } else {
383 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700384 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
385 [&res, &delayUs = config.mInputDelayUs](
386 auto status, auto stopTimeOffsetUs) {
387 res = static_cast<status_t>(status);
388 delayUs = stopTimeOffsetUs;
389 });
390 if (!trans.isOk()) {
391 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
392 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800393 if (res != OK) {
394 status << " (=> " << asString(res) << ")";
395 } else {
396 status << "=" << config.mInputDelayUs << "us";
397 }
398 mConfig.mInputDelayUs = config.mInputDelayUs;
399 }
400 mConfig.mStopAtUs = config.mStopAtUs;
401 mConfig.mStopped = config.mStopped;
402 }
403
404 // color aspects (android._color-aspects)
405
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700406 // consumer usage is queried earlier.
407
Wonsik Kima1335e12021-04-22 16:28:29 -0700408 // priority
409 if (mConfig.mPriority != config.mPriority) {
410 if (config.mPriority != INT_MAX) {
411 mNode->setPriority(config.mPriority);
412 }
413 mConfig.mPriority = config.mPriority;
414 }
415
Wonsik Kimbd557932019-07-02 15:51:20 -0700416 if (status.str().empty()) {
417 ALOGD("ISConfig not changed");
418 } else {
419 ALOGD("ISConfig%s", status.str().c_str());
420 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800421 return err;
422 }
423
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700424 void onInputBufferDone(c2_cntr64_t index) override {
425 mNode->onInputBufferDone(index);
426 }
427
Wonsik Kim673dd192021-01-29 14:58:12 -0800428 android_dataspace getDataspace() override {
429 return mNode->getDataspace();
430 }
431
Pawin Vongmasa36653902018-11-15 00:10:25 -0800432private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700433 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800434 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700435 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800436 uint32_t mWidth;
437 uint32_t mHeight;
438 Config mConfig;
439};
440
441class Codec2ClientInterfaceWrapper : public C2ComponentStore {
442 std::shared_ptr<Codec2Client> mClient;
443
444public:
445 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
446 : mClient(client) { }
447
448 virtual ~Codec2ClientInterfaceWrapper() = default;
449
450 virtual c2_status_t config_sm(
451 const std::vector<C2Param *> &params,
452 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
453 return mClient->config(params, C2_MAY_BLOCK, failures);
454 };
455
456 virtual c2_status_t copyBuffer(
457 std::shared_ptr<C2GraphicBuffer>,
458 std::shared_ptr<C2GraphicBuffer>) {
459 return C2_OMITTED;
460 }
461
462 virtual c2_status_t createComponent(
463 C2String, std::shared_ptr<C2Component> *const component) {
464 component->reset();
465 return C2_OMITTED;
466 }
467
468 virtual c2_status_t createInterface(
469 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
470 interface->reset();
471 return C2_OMITTED;
472 }
473
474 virtual c2_status_t query_sm(
475 const std::vector<C2Param *> &stackParams,
476 const std::vector<C2Param::Index> &heapParamIndices,
477 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
478 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
479 }
480
481 virtual c2_status_t querySupportedParams_nb(
482 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
483 return mClient->querySupportedParams(params);
484 }
485
486 virtual c2_status_t querySupportedValues_sm(
487 std::vector<C2FieldSupportedValuesQuery> &fields) const {
488 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
489 }
490
491 virtual C2String getName() const {
492 return mClient->getName();
493 }
494
495 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
496 return mClient->getParamReflector();
497 }
498
499 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
500 return std::vector<std::shared_ptr<const C2Component::Traits>>();
501 }
502};
503
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800504void RevertOutputFormatIfNeeded(
505 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
506 // We used to not report changes to these keys to the client.
507 const static std::set<std::string> sIgnoredKeys({
508 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800509 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800510 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800511 KEY_MAX_WIDTH,
512 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800513 "csd-0",
514 "csd-1",
515 "csd-2",
516 });
517 if (currentFormat == oldFormat) {
518 return;
519 }
520 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
521 AMessage::Type type;
522 for (size_t i = diff->countEntries(); i > 0; --i) {
523 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
524 diff->removeEntryAt(i - 1);
525 }
526 }
527 if (diff->countEntries() == 0) {
528 currentFormat = oldFormat;
529 }
530}
531
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700532void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700533 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700534 const sp<AMessage> &outputFormat) {
535 if (mediaType == MIMETYPE_VIDEO_AVC) {
536 // Codec specific data should be SPS and PPS in a single buffer,
537 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
538 // We separate the two and put them into the output format
539 // under the keys "csd-0" and "csd-1".
540
541 unsigned csdIndex = 0;
542
543 const uint8_t *nalStart;
544 size_t nalSize;
545 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
546 sp<ABuffer> csd = new ABuffer(nalSize + 4);
547 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
548 memcpy(csd->data() + 4, nalStart, nalSize);
549
550 outputFormat->setBuffer(
551 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
552
553 ++csdIndex;
554 }
555
556 if (csdIndex != 2) {
557 ALOGW("Expected two NAL units from AVC codec config, but %u found",
558 csdIndex);
559 }
560 } else {
561 // For everything else we just stash the codec specific data into
562 // the output format as a single piece of csd under "csd-0".
563 sp<ABuffer> csd = new ABuffer(size);
564 memcpy(csd->data(), data, size);
565 csd->setRange(0, size);
566 outputFormat->setBuffer("csd-0", csd);
567 }
568}
569
Pawin Vongmasa36653902018-11-15 00:10:25 -0800570} // namespace
571
572// CCodec::ClientListener
573
574struct CCodec::ClientListener : public Codec2Client::Listener {
575
576 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
577
578 virtual void onWorkDone(
579 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800580 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800581 (void)component;
582 sp<CCodec> codec(mCodec.promote());
583 if (!codec) {
584 return;
585 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800586 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800587 }
588
589 virtual void onTripped(
590 const std::weak_ptr<Codec2Client::Component>& component,
591 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
592 ) override {
593 // TODO
594 (void)component;
595 (void)settingResult;
596 }
597
598 virtual void onError(
599 const std::weak_ptr<Codec2Client::Component>& component,
600 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800601 {
602 // Component is only used for reporting as we use a separate listener for each instance
603 std::shared_ptr<Codec2Client::Component> comp = component.lock();
604 if (!comp) {
605 ALOGD("Component died with error: 0x%x", errorCode);
606 } else {
607 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
608 }
609 }
610
611 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800612 // Note: for now we do not propagate the error code to MediaCodec
613 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800614 sp<CCodec> codec(mCodec.promote());
615 if (!codec || !codec->mCallback) {
616 return;
617 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800618 codec->mCallback->onError(
619 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
620 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800621 }
622
623 virtual void onDeath(
624 const std::weak_ptr<Codec2Client::Component>& component) override {
625 { // Log the death of the component.
626 std::shared_ptr<Codec2Client::Component> comp = component.lock();
627 if (!comp) {
628 ALOGE("Codec2 component died.");
629 } else {
630 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
631 }
632 }
633
634 // Report to MediaCodec.
635 sp<CCodec> codec(mCodec.promote());
636 if (!codec || !codec->mCallback) {
637 return;
638 }
639 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
640 }
641
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800642 virtual void onFrameRendered(uint64_t bufferQueueId,
643 int32_t slotId,
644 int64_t timestampNs) override {
645 // TODO: implement
646 (void)bufferQueueId;
647 (void)slotId;
648 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800649 }
650
651 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800652 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800653 sp<CCodec> codec(mCodec.promote());
654 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800655 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800656 }
657 }
658
659private:
660 wp<CCodec> mCodec;
661};
662
663// CCodecCallbackImpl
664
665class CCodecCallbackImpl : public CCodecCallback {
666public:
667 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
668 ~CCodecCallbackImpl() override = default;
669
670 void onError(status_t err, enum ActionCode actionCode) override {
671 mCodec->mCallback->onError(err, actionCode);
672 }
673
674 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
675 mCodec->mCallback->onOutputFramesRendered(
676 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
677 }
678
Pawin Vongmasa36653902018-11-15 00:10:25 -0800679 void onOutputBuffersChanged() override {
680 mCodec->mCallback->onOutputBuffersChanged();
681 }
682
Guillaume Chelfi5ffbcb32021-04-12 14:23:43 +0200683 void onFirstTunnelFrameReady() override {
684 mCodec->mCallback->onFirstTunnelFrameReady();
685 }
686
Pawin Vongmasa36653902018-11-15 00:10:25 -0800687private:
688 CCodec *mCodec;
689};
690
691// CCodec
692
693CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700694 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
695 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800696}
697
698CCodec::~CCodec() {
699}
700
701std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
702 return mChannel;
703}
704
705status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
706 status_t err = job();
707 if (err != C2_OK) {
708 mCallback->onError(err, ACTION_CODE_FATAL);
709 }
710 return err;
711}
712
713void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
714 auto setAllocating = [this] {
715 Mutexed<State>::Locked state(mState);
716 if (state->get() != RELEASED) {
717 return INVALID_OPERATION;
718 }
719 state->set(ALLOCATING);
720 return OK;
721 };
722 if (tryAndReportOnError(setAllocating) != OK) {
723 return;
724 }
725
726 sp<RefBase> codecInfo;
727 CHECK(msg->findObject("codecInfo", &codecInfo));
728 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
729
730 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
731 allocMsg->setObject("codecInfo", codecInfo);
732 allocMsg->post();
733}
734
735void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
736 if (codecInfo == nullptr) {
737 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
738 return;
739 }
740 ALOGD("allocate(%s)", codecInfo->getCodecName());
741 mClientListener.reset(new ClientListener(this));
742
743 AString componentName = codecInfo->getCodecName();
744 std::shared_ptr<Codec2Client> client;
745
746 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700747 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800749 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800750 SetPreferredCodec2ComponentStore(
751 std::make_shared<Codec2ClientInterfaceWrapper>(client));
752 }
753
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900754 std::shared_ptr<Codec2Client::Component> comp;
755 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800756 componentName.c_str(),
757 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900758 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900760 if (status != C2_OK) {
761 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800762 Mutexed<State>::Locked state(mState);
763 state->set(RELEASED);
764 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900765 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800766 state.lock();
767 return;
768 }
769 ALOGI("Created component [%s]", componentName.c_str());
770 mChannel->setComponent(comp);
771 auto setAllocated = [this, comp, client] {
772 Mutexed<State>::Locked state(mState);
773 if (state->get() != ALLOCATING) {
774 state->set(RELEASED);
775 return UNKNOWN_ERROR;
776 }
777 state->set(ALLOCATED);
778 state->comp = comp;
779 mClient = client;
780 return OK;
781 };
782 if (tryAndReportOnError(setAllocated) != OK) {
783 return;
784 }
785
786 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700787 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
788 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800789 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800790 if (err != OK) {
791 ALOGW("Failed to initialize configuration support");
792 // TODO: report error once we complete implementation.
793 }
794 config->queryConfiguration(comp);
795
796 mCallback->onComponentAllocated(componentName.c_str());
797}
798
799void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
800 auto checkAllocated = [this] {
801 Mutexed<State>::Locked state(mState);
802 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
803 };
804 if (tryAndReportOnError(checkAllocated) != OK) {
805 return;
806 }
807
808 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
809 msg->setMessage("format", format);
810 msg->post();
811}
812
813void CCodec::configure(const sp<AMessage> &msg) {
814 std::shared_ptr<Codec2Client::Component> comp;
815 auto checkAllocated = [this, &comp] {
816 Mutexed<State>::Locked state(mState);
817 if (state->get() != ALLOCATED) {
818 state->set(RELEASED);
819 return UNKNOWN_ERROR;
820 }
821 comp = state->comp;
822 return OK;
823 };
824 if (tryAndReportOnError(checkAllocated) != OK) {
825 return;
826 }
827
828 auto doConfig = [msg, comp, this]() -> status_t {
829 AString mime;
830 if (!msg->findString("mime", &mime)) {
831 return BAD_VALUE;
832 }
833
834 int32_t encoder;
835 if (!msg->findInt32("encoder", &encoder)) {
836 encoder = false;
837 }
838
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800839 int32_t flags;
840 if (!msg->findInt32("flags", &flags)) {
841 return BAD_VALUE;
842 }
843
Pawin Vongmasa36653902018-11-15 00:10:25 -0800844 // TODO: read from intf()
845 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
846 return UNKNOWN_ERROR;
847 }
848
849 int32_t storeMeta;
850 if (encoder
851 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
852 && storeMeta != kMetadataBufferTypeInvalid) {
853 if (storeMeta != kMetadataBufferTypeANWBuffer) {
854 ALOGD("Only ANW buffers are supported for legacy metadata mode");
855 return BAD_VALUE;
856 }
857 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
858 }
859
ted.sun765db4d2020-06-23 14:03:41 +0800860 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800861 sp<RefBase> obj;
862 sp<Surface> surface;
863 if (msg->findObject("native-window", &obj)) {
864 surface = static_cast<Surface *>(obj.get());
ted.sun765db4d2020-06-23 14:03:41 +0800865 // setup tunneled playback
866 if (surface != nullptr) {
867 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
868 const std::unique_ptr<Config> &config = *configLocked;
869 if ((config->mDomain & Config::IS_DECODER)
870 && (config->mDomain & Config::IS_VIDEO)) {
871 int32_t tunneled;
872 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
873 ALOGI("Configuring TUNNELED video playback.");
874
875 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
876 if (err != OK) {
877 ALOGE("configureTunneledVideoPlayback failed!");
878 return err;
879 }
880 config->mTunneled = true;
881 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +0100882
883 int32_t pushBlankBuffersOnStop = 0;
884 if (msg->findInt32(KEY_PUSH_BLANK_BUFFERS_ON_STOP, &pushBlankBuffersOnStop)) {
885 config->mPushBlankBuffersOnStop = pushBlankBuffersOnStop == 1;
886 }
shuanglong.wang480a8362023-02-17 20:55:51 +0800887 // secure compoment or protected content default with
888 // "push-blank-buffers-on-shutdown" flag
889 if (!config->mPushBlankBuffersOnStop) {
890 int32_t usageProtected;
891 if (comp->getName().find(".secure") != std::string::npos) {
892 config->mPushBlankBuffersOnStop = true;
893 } else if (msg->findInt32("protected", &usageProtected) && usageProtected) {
894 config->mPushBlankBuffersOnStop = true;
895 }
896 }
ted.sun765db4d2020-06-23 14:03:41 +0800897 }
898 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800899 setSurface(surface);
900 }
901
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700902 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
903 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800904 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800905 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
906 ALOGD("[%s] buffers are %sbound to CCodec for this session",
907 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800908
Wonsik Kim1114eea2019-02-25 14:35:24 -0800909 // Enforce required parameters
910 int32_t i32;
911 float flt;
912 if (config->mDomain & Config::IS_AUDIO) {
913 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
914 ALOGD("sample rate is missing, which is required for audio components.");
915 return BAD_VALUE;
916 }
917 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
918 ALOGD("channel count is missing, which is required for audio components.");
919 return BAD_VALUE;
920 }
921 if ((config->mDomain & Config::IS_ENCODER)
922 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
923 && !msg->findInt32(KEY_BIT_RATE, &i32)
924 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
925 ALOGD("bitrate is missing, which is required for audio encoders.");
926 return BAD_VALUE;
927 }
928 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800929 int32_t width = 0;
930 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800931 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800932 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800933 ALOGD("width is missing, which is required for image/video components.");
934 return BAD_VALUE;
935 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800936 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800937 ALOGD("height is missing, which is required for image/video components.");
938 return BAD_VALUE;
939 }
940 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700941 int32_t mode = BITRATE_MODE_VBR;
942 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700943 if (!msg->findInt32(KEY_QUALITY, &i32)) {
944 ALOGD("quality is missing, which is required for video encoders in CQ.");
945 return BAD_VALUE;
946 }
947 } else {
948 if (!msg->findInt32(KEY_BIT_RATE, &i32)
949 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
950 ALOGD("bitrate is missing, which is required for video encoders.");
951 return BAD_VALUE;
952 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800953 }
954 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
955 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
956 ALOGD("I frame interval is missing, which is required for video encoders.");
957 return BAD_VALUE;
958 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700959 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
960 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
961 ALOGD("frame rate is missing, which is required for video encoders.");
962 return BAD_VALUE;
963 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800964 }
965 }
966
Pawin Vongmasa36653902018-11-15 00:10:25 -0800967 /*
968 * Handle input surface configuration
969 */
970 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
971 && (config->mDomain & Config::IS_ENCODER)) {
972 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
973 {
974 config->mISConfig->mMinFps = 0;
975 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800976 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800977 config->mISConfig->mMinFps = 1e6 / value;
978 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700979 if (!msg->findFloat(
980 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
981 config->mISConfig->mMaxFps = -1;
982 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800983 config->mISConfig->mMinAdjustedFps = 0;
984 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800985 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800986 if (value < 0 && value >= INT32_MIN) {
987 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700988 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800989 } else if (value > 0 && value <= INT32_MAX) {
990 config->mISConfig->mMinAdjustedFps = 1e6 / value;
991 }
992 }
993 }
994
995 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700996 bool captureFpsFound = false;
997 double timeLapseFps;
998 float captureRate;
999 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
1000 config->mISConfig->mCaptureFps = timeLapseFps;
1001 captureFpsFound = true;
1002 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
1003 config->mISConfig->mCaptureFps = captureRate;
1004 captureFpsFound = true;
1005 }
1006 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001007 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
1008 }
1009 }
1010
1011 {
1012 config->mISConfig->mSuspended = false;
1013 config->mISConfig->mSuspendAtUs = -1;
1014 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001015 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001016 config->mISConfig->mSuspended = true;
1017 }
1018 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001019 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -07001020 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001021 }
1022
1023 /*
1024 * Handle desired color format.
1025 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001026 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001027 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001028 int32_t format = 0;
1029 // Query vendor format for Flexible YUV
1030 std::vector<std::unique_ptr<C2Param>> heapParams;
1031 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
Wonsik Kim50811882022-04-28 15:57:27 -07001032 int vendorSdkVersion = base::GetIntProperty(
1033 "ro.vendor.build.version.sdk", android_get_device_api_level());
guochuang709b48b2022-10-25 20:40:42 +08001034 if (mClient->query(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001035 {},
1036 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1037 C2_MAY_BLOCK,
1038 &heapParams) == C2_OK
1039 && heapParams.size() == 1u) {
1040 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1041 heapParams[0].get());
1042 } else {
1043 pixelFormatInfo = nullptr;
1044 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001045 // bit depth -> format
1046 std::map<uint32_t, uint32_t> flexPixelFormat;
1047 std::map<uint32_t, uint32_t> flexPlanarPixelFormat;
1048 std::map<uint32_t, uint32_t> flexSemiPlanarPixelFormat;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001049 if (pixelFormatInfo && *pixelFormatInfo) {
1050 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1051 const C2FlexiblePixelFormatDescriptorStruct &desc =
1052 pixelFormatInfo->m.values[i];
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001053 if (desc.subsampling != C2Color::YUV_420
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001054 // TODO(b/180076105): some device report wrong layout
1055 // || desc.layout == C2Color::INTERLEAVED_PACKED
1056 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1057 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1058 continue;
1059 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001060 if (flexPixelFormat.count(desc.bitDepth) == 0) {
1061 flexPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001062 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001063 if (desc.layout == C2Color::PLANAR_PACKED
1064 && flexPlanarPixelFormat.count(desc.bitDepth) == 0) {
1065 flexPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001066 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001067 if (desc.layout == C2Color::SEMIPLANAR_PACKED
1068 && flexSemiPlanarPixelFormat.count(desc.bitDepth) == 0) {
1069 flexSemiPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001070 }
1071 }
1072 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001073 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001074 // Also handle default color format (encoders require color format, so this is only
1075 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001076 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001077 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001078 const char *prefix = "";
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001079 if (flexSemiPlanarPixelFormat.count(8) != 0) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001080 format = COLOR_FormatYUV420SemiPlanar;
1081 prefix = "semi-";
1082 } else {
1083 format = COLOR_FormatYUV420Planar;
1084 }
1085 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1086 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001087 } else {
1088 format = COLOR_FormatSurface;
1089 }
1090 defaultColorFormat = format;
1091 }
1092 } else {
1093 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001094 if (vendorSdkVersion < __ANDROID_API_S__ &&
Taehwan Kim43e715d2022-09-22 12:04:59 +09001095 (format == COLOR_FormatYUV420Planar ||
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001096 format == COLOR_FormatYUV420PackedPlanar ||
1097 format == COLOR_FormatYUV420SemiPlanar ||
1098 format == COLOR_FormatYUV420PackedSemiPlanar)) {
1099 // pre-S framework used to map these color formats into YV12.
1100 // Codecs from older vendor partition may be relying on
1101 // this assumption.
1102 format = HAL_PIXEL_FORMAT_YV12;
1103 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001104 switch (format) {
1105 case COLOR_FormatYUV420Flexible:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001106 format = COLOR_FormatYUV420Planar;
1107 if (flexPixelFormat.count(8) != 0) {
1108 format = flexPixelFormat[8];
1109 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001110 break;
1111 case COLOR_FormatYUV420Planar:
1112 case COLOR_FormatYUV420PackedPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001113 if (flexPlanarPixelFormat.count(8) != 0) {
1114 format = flexPlanarPixelFormat[8];
1115 } else if (flexPixelFormat.count(8) != 0) {
1116 format = flexPixelFormat[8];
1117 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001118 break;
1119 case COLOR_FormatYUV420SemiPlanar:
1120 case COLOR_FormatYUV420PackedSemiPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001121 if (flexSemiPlanarPixelFormat.count(8) != 0) {
1122 format = flexSemiPlanarPixelFormat[8];
1123 } else if (flexPixelFormat.count(8) != 0) {
1124 format = flexPixelFormat[8];
1125 }
1126 break;
1127 case COLOR_FormatYUVP010:
1128 format = COLOR_FormatYUVP010;
1129 if (flexSemiPlanarPixelFormat.count(10) != 0) {
1130 format = flexSemiPlanarPixelFormat[10];
1131 } else if (flexPixelFormat.count(10) != 0) {
1132 format = flexPixelFormat[10];
1133 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001134 break;
1135 default:
1136 // No-op
1137 break;
1138 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001139 }
1140 }
1141
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001142 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001143 msg->setInt32("android._color-format", format);
1144 }
1145 }
1146
Wonsik Kim77e97c72021-01-20 10:33:22 -08001147 /*
1148 * Handle dataspace
1149 */
1150 int32_t usingRecorder;
1151 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1152 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1153 int32_t width, height;
1154 if (msg->findInt32("width", &width)
1155 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001156 ColorAspects aspects;
1157 getColorAspectsFromFormat(msg, aspects);
1158 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001159 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001160 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1161 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001162 }
1163 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1164 ALOGD("setting dataspace to %x", dataSpace);
1165 }
1166
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001167 int32_t subscribeToAllVendorParams;
1168 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1169 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1170 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1171 }
1172 }
1173
Pawin Vongmasa36653902018-11-15 00:10:25 -08001174 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001175 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1176 // the behavior here.
1177 sp<AMessage> sdkParams = msg;
1178 int32_t videoBitrate;
1179 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1180 sdkParams = msg->dup();
1181 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1182 }
ted.sun765db4d2020-06-23 14:03:41 +08001183 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001184 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001185 if (err != OK) {
1186 ALOGW("failed to convert configuration to c2 params");
1187 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001188
1189 int32_t maxBframes = 0;
1190 if ((config->mDomain & Config::IS_ENCODER)
1191 && (config->mDomain & Config::IS_VIDEO)
1192 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1193 && maxBframes > 0) {
1194 std::unique_ptr<C2StreamGopTuning::output> gop =
1195 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1196 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1197 gop->m.values[1] = {
1198 C2Config::picture_type_t(P_FRAME | B_FRAME),
1199 uint32_t(maxBframes)
1200 };
1201 configUpdate.push_back(std::move(gop));
1202 }
1203
Ray Essicka0ae6972021-03-10 19:40:01 -08001204 if ((config->mDomain & Config::IS_ENCODER)
1205 && (config->mDomain & Config::IS_VIDEO)) {
1206 // we may not use all 3 of these entries
1207 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1208 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1209 0u /* stream */);
1210
1211 int ix = 0;
1212
1213 int32_t iMax = INT32_MAX;
1214 int32_t iMin = INT32_MIN;
1215 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1216 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1217 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1218 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1219 }
1220
1221 int32_t pMax = INT32_MAX;
1222 int32_t pMin = INT32_MIN;
1223 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1224 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1225 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1226 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1227 }
1228
1229 int32_t bMax = INT32_MAX;
1230 int32_t bMin = INT32_MIN;
1231 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1232 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1233 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1234 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1235 }
1236
1237 // adjust to reflect actual use.
1238 qp->setFlexCount(ix);
1239
1240 configUpdate.push_back(std::move(qp));
1241 }
1242
Wonsik Kima1335e12021-04-22 16:28:29 -07001243 int32_t background = 0;
1244 if ((config->mDomain & Config::IS_VIDEO)
1245 && msg->findInt32("android._background-mode", &background)
1246 && background) {
1247 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1248 if (config->mISConfig) {
1249 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1250 }
1251 }
1252
Pawin Vongmasa36653902018-11-15 00:10:25 -08001253 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1254 if (err != OK) {
1255 ALOGW("failed to configure c2 params");
1256 return err;
1257 }
1258
1259 std::vector<std::unique_ptr<C2Param>> params;
1260 C2StreamUsageTuning::input usage(0u, 0u);
1261 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001262 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001263
Wonsik Kim3baecda2021-02-07 22:19:56 -08001264 C2Param::Index colorAspectsRequestIndex =
1265 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001266 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001267 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001268 };
Chaejung Lim86c22dc2021-12-23 00:41:05 -08001269 int32_t colorTransferRequest = 0;
1270 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1271 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1272 colorTransferRequest = 0;
1273 }
1274 c2_status_t c2err = C2_OK;
1275 if (colorTransferRequest != 0) {
1276 c2err = comp->query(
1277 { &usage, &maxInputSize, &prepend },
1278 indices,
1279 C2_DONT_BLOCK,
1280 &params);
1281 } else {
1282 c2err = comp->query(
1283 { &usage, &maxInputSize, &prepend },
1284 {},
1285 C2_DONT_BLOCK,
1286 &params);
1287 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001288 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1289 ALOGE("Failed to query component interface: %d", c2err);
1290 return UNKNOWN_ERROR;
1291 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001292 if (usage) {
1293 if (usage.value & C2MemoryUsage::CPU_READ) {
1294 config->mInputFormat->setInt32("using-sw-read-often", true);
1295 }
1296 if (config->mISConfig) {
1297 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1298 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1299 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001300 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001301 }
1302
1303 // NOTE: we don't blindly use client specified input size if specified as clients
1304 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1305 // client specified size is only used to ask for bigger buffers than component suggested
1306 // size.
1307 int32_t clientInputSize = 0;
1308 bool clientSpecifiedInputSize =
1309 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1310 // TEMP: enforce minimum buffer size of 1MB for video decoders
1311 // and 16K / 4K for audio encoders/decoders
1312 if (maxInputSize.value == 0) {
1313 if (config->mDomain & Config::IS_AUDIO) {
1314 maxInputSize.value = encoder ? 16384 : 4096;
1315 } else if (!encoder) {
1316 maxInputSize.value = 1048576u;
1317 }
1318 }
1319
1320 // verify that CSD fits into this size (if defined)
1321 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1322 sp<ABuffer> csd;
1323 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1324 if (csd && csd->size() > maxInputSize.value) {
1325 maxInputSize.value = csd->size();
1326 }
1327 }
1328 }
1329
1330 // TODO: do this based on component requiring linear allocator for input
1331 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1332 if (clientSpecifiedInputSize) {
1333 // Warn that we're overriding client's max input size if necessary.
1334 if ((uint32_t)clientInputSize < maxInputSize.value) {
1335 ALOGD("client requested max input size %d, which is smaller than "
1336 "what component recommended (%u); overriding with component "
1337 "recommendation.", clientInputSize, maxInputSize.value);
1338 ALOGW("This behavior is subject to change. It is recommended that "
1339 "app developers double check whether the requested "
1340 "max input size is in reasonable range.");
1341 } else {
1342 maxInputSize.value = clientInputSize;
1343 }
1344 }
1345 // Pass max input size on input format to the buffer channel (if supplied by the
1346 // component or by a default)
1347 if (maxInputSize.value) {
1348 config->mInputFormat->setInt32(
1349 KEY_MAX_INPUT_SIZE,
1350 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1351 }
1352 }
1353
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001354 int32_t clientPrepend;
1355 if ((config->mDomain & Config::IS_VIDEO)
1356 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001357 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001358 && clientPrepend
1359 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001360 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001361 return BAD_VALUE;
1362 }
1363
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001364 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001365 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1366 // propagate HDR static info to output format for both encoders and decoders
1367 // if component supports this info, we will update from component, but only the raw port,
1368 // so don't propagate if component already filled it in.
1369 sp<ABuffer> hdrInfo;
1370 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1371 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1372 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1373 }
1374
1375 // Set desired color format from configuration parameter
1376 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001377 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1378 format = defaultColorFormat;
1379 }
1380 if (config->mDomain & Config::IS_ENCODER) {
1381 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001382 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1383 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001384 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001385 } else {
1386 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001387 }
1388 }
1389
1390 // propagate encoder delay and padding to output format
1391 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1392 int delay = 0;
1393 if (msg->findInt32("encoder-delay", &delay)) {
1394 config->mOutputFormat->setInt32("encoder-delay", delay);
1395 }
1396 int padding = 0;
1397 if (msg->findInt32("encoder-padding", &padding)) {
1398 config->mOutputFormat->setInt32("encoder-padding", padding);
1399 }
1400 }
1401
Pawin Vongmasa36653902018-11-15 00:10:25 -08001402 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001403 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001404 int32_t mask;
1405 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1406 if (config->mDomain & Config::IS_ENCODER) {
1407 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1408 } else {
1409 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1410 }
1411 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001412
1413 // set PCM encoding
1414 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1415 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1416 if (encoder) {
1417 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1418 } else {
1419 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1420 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001421 }
1422
Wonsik Kim3baecda2021-02-07 22:19:56 -08001423 std::unique_ptr<C2Param> colorTransferRequestParam;
1424 for (std::unique_ptr<C2Param> &param : params) {
1425 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1426 ALOGI("found color transfer request param");
1427 colorTransferRequestParam = std::move(param);
1428 }
1429 }
Wonsik Kim3baecda2021-02-07 22:19:56 -08001430
1431 if (colorTransferRequest != 0) {
1432 if (colorTransferRequestParam && *colorTransferRequestParam) {
1433 C2StreamColorAspectsInfo::output *info =
1434 static_cast<C2StreamColorAspectsInfo::output *>(
1435 colorTransferRequestParam.get());
1436 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1437 colorTransferRequest = 0;
1438 }
1439 } else {
1440 colorTransferRequest = 0;
1441 }
1442 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1443 }
1444
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001445 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1446 // Need to get stride/vstride
1447 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1448 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1449 // TODO: retrieve these values without allocating a buffer.
1450 // Currently allocating a buffer is necessary to retrieve the layout.
1451 int64_t blockUsage =
1452 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1453 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
Taehwan Kim2772e1c2022-03-31 17:15:08 +09001454 width, height, componentColorFormat, blockUsage, {comp->getName()});
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001455 sp<GraphicBlockBuffer> buffer;
1456 if (block) {
1457 buffer = GraphicBlockBuffer::Allocate(
1458 config->mInputFormat,
1459 block,
1460 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1461 } else {
1462 ALOGD("Failed to allocate a graphic block "
1463 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1464 width, height, pixelFormat, (long long)blockUsage);
1465 // This means that byte buffer mode is not supported in this configuration
1466 // anyway. Skip setting stride/vstride to input format.
1467 }
1468 if (buffer) {
1469 sp<ABuffer> imageData = buffer->getImageData();
1470 MediaImage2 *img = nullptr;
1471 if (imageData && imageData->data()
1472 && imageData->size() >= sizeof(MediaImage2)) {
1473 img = (MediaImage2*)imageData->data();
1474 }
1475 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1476 int32_t stride = img->mPlane[0].mRowInc;
1477 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1478 if (img->mNumPlanes > 1 && stride > 0) {
1479 int64_t offsetDelta =
1480 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1481 if (offsetDelta % stride == 0) {
1482 int32_t vstride = int32_t(offsetDelta / stride);
1483 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1484 } else {
1485 ALOGD("Cannot report accurate slice height: "
1486 "offsetDelta = %lld stride = %d",
1487 (long long)offsetDelta, stride);
1488 }
1489 }
1490 }
1491 }
1492 }
1493 }
1494
Wonsik Kimec585c32021-10-01 01:11:00 -07001495 if (config->mTunneled) {
1496 config->mOutputFormat->setInt32("android._tunneled", 1);
1497 }
1498
Yushin Cho91873b52021-12-21 04:08:35 -08001499 // Convert an encoding statistics level to corresponding encoding statistics
1500 // kinds
1501 int32_t encodingStatisticsLevel = VIDEO_ENCODING_STATISTICS_LEVEL_NONE;
1502 if ((config->mDomain & Config::IS_ENCODER)
1503 && (config->mDomain & Config::IS_VIDEO)
1504 && msg->findInt32(KEY_VIDEO_ENCODING_STATISTICS_LEVEL, &encodingStatisticsLevel)) {
1505 // Higher level include all the enc stats belong to lower level.
1506 switch (encodingStatisticsLevel) {
1507 // case VIDEO_ENCODING_STATISTICS_LEVEL_2: // reserved for the future level 2
1508 // with more enc stat kinds
1509 // Future extended encoding statistics for the level 2 should be added here
1510 case VIDEO_ENCODING_STATISTICS_LEVEL_1:
Wonsik Kimeebab652022-06-02 13:01:55 -07001511 config->subscribeToConfigUpdate(
1512 comp,
1513 {
1514 C2AndroidStreamAverageBlockQuantizationInfo::output::PARAM_TYPE,
1515 C2StreamPictureTypeInfo::output::PARAM_TYPE,
1516 });
Yushin Cho91873b52021-12-21 04:08:35 -08001517 break;
1518 case VIDEO_ENCODING_STATISTICS_LEVEL_NONE:
1519 break;
1520 }
1521 }
1522 ALOGD("encoding statistics level = %d", encodingStatisticsLevel);
1523
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001524 ALOGD("setup formats input: %s",
1525 config->mInputFormat->debugString().c_str());
1526 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001527 config->mOutputFormat->debugString().c_str());
1528 return OK;
1529 };
1530 if (tryAndReportOnError(doConfig) != OK) {
1531 return;
1532 }
1533
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001534 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1535 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001536
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001537 config->queryConfiguration(comp);
1538
Pawin Vongmasa36653902018-11-15 00:10:25 -08001539 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1540}
1541
1542void CCodec::initiateCreateInputSurface() {
1543 status_t err = [this] {
1544 Mutexed<State>::Locked state(mState);
1545 if (state->get() != ALLOCATED) {
1546 return UNKNOWN_ERROR;
1547 }
1548 // TODO: read it from intf() properly.
1549 if (state->comp->getName().find("encoder") == std::string::npos) {
1550 return INVALID_OPERATION;
1551 }
1552 return OK;
1553 }();
1554 if (err != OK) {
1555 mCallback->onInputSurfaceCreationFailed(err);
1556 return;
1557 }
1558
1559 (new AMessage(kWhatCreateInputSurface, this))->post();
1560}
1561
Lajos Molnar47118272019-01-31 16:28:04 -08001562sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1563 using namespace android::hardware::media::omx::V1_0;
1564 using namespace android::hardware::media::omx::V1_0::utils;
1565 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1566 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1567 android::sp<IOmx> omx = IOmx::getService();
Sungtak Lee47dcb482022-04-15 10:47:08 -07001568 if (omx == nullptr) {
1569 return nullptr;
1570 }
Lajos Molnar47118272019-01-31 16:28:04 -08001571 typedef android::hardware::graphics::bufferqueue::V1_0::
1572 IGraphicBufferProducer HGraphicBufferProducer;
1573 typedef android::hardware::media::omx::V1_0::
1574 IGraphicBufferSource HGraphicBufferSource;
1575 OmxStatus s;
1576 android::sp<HGraphicBufferProducer> gbp;
1577 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001578
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001579 using ::android::hardware::Return;
1580 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001581 [&s, &gbp, &gbs](
1582 OmxStatus status,
1583 const android::sp<HGraphicBufferProducer>& producer,
1584 const android::sp<HGraphicBufferSource>& source) {
1585 s = status;
1586 gbp = producer;
1587 gbs = source;
1588 });
1589 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001590 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001591 }
1592
1593 return nullptr;
1594}
1595
1596sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1597 sp<PersistentSurface> surface(CreateInputSurface());
1598
1599 if (surface == nullptr) {
1600 surface = CreateOmxInputSurface();
1601 }
1602
1603 return surface;
1604}
1605
Pawin Vongmasa36653902018-11-15 00:10:25 -08001606void CCodec::createInputSurface() {
1607 status_t err;
1608 sp<IGraphicBufferProducer> bufferProducer;
1609
Pawin Vongmasa36653902018-11-15 00:10:25 -08001610 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001611 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001612 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001613 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1614 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001615 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001616 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001617 }
1618
Lajos Molnar47118272019-01-31 16:28:04 -08001619 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001620 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1621 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1622 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001623
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001624 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001625 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1626 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001627 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001628 inputSurface));
1629 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001630 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001631 int32_t width = 0;
1632 (void)outputFormat->findInt32("width", &width);
1633 int32_t height = 0;
1634 (void)outputFormat->findInt32("height", &height);
1635 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001636 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001637 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001638 } else {
1639 ALOGE("Corrupted input surface");
1640 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1641 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001642 }
1643
1644 if (err != OK) {
1645 ALOGE("Failed to set up input surface: %d", err);
1646 mCallback->onInputSurfaceCreationFailed(err);
1647 return;
1648 }
1649
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001650 // Formats can change after setupInputSurface
1651 sp<AMessage> inputFormat;
1652 {
1653 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1654 const std::unique_ptr<Config> &config = *configLocked;
1655 inputFormat = config->mInputFormat;
1656 outputFormat = config->mOutputFormat;
1657 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001658 mCallback->onInputSurfaceCreated(
1659 inputFormat,
1660 outputFormat,
1661 new BufferProducerWrapper(bufferProducer));
1662}
1663
1664status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001665 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1666 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001667 config->mUsingSurface = true;
1668
1669 // we are now using surface - apply default color aspects to input format - as well as
1670 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001671 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001672
1673 // configure dataspace
1674 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
Wonsik Kim66b19552021-08-02 16:07:49 -07001675
1676 // The output format contains app-configured color aspects, and the input format
1677 // has the default color aspects. Use the default for the unspecified params.
1678 ColorAspects inputColorAspects, colorAspects;
1679 getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
1680 getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
1681 if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
1682 colorAspects.mRange = inputColorAspects.mRange;
1683 }
1684 if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
1685 colorAspects.mPrimaries = inputColorAspects.mPrimaries;
1686 }
1687 if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
1688 colorAspects.mTransfer = inputColorAspects.mTransfer;
1689 }
1690 if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
1691 colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
1692 }
1693 android_dataspace dataSpace = getDataSpaceForColorAspects(
1694 colorAspects, /* mayExtend = */ false);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001695 surface->setDataSpace(dataSpace);
Wonsik Kim66b19552021-08-02 16:07:49 -07001696 setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
1697 config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
1698
1699 ALOGD("input format %s to %s",
1700 inputFormatChanged ? "changed" : "unchanged",
1701 config->mInputFormat->debugString().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001702
1703 status_t err = mChannel->setInputSurface(surface);
1704 if (err != OK) {
1705 // undo input format update
1706 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001707 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001708 return err;
1709 }
1710 config->mInputSurface = surface;
1711
1712 if (config->mISConfig) {
1713 surface->configure(*config->mISConfig);
1714 } else {
1715 ALOGD("ISConfig: no configuration");
1716 }
1717
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001718 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001719}
1720
1721void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1722 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1723 msg->setObject("surface", surface);
1724 msg->post();
1725}
1726
1727void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001728 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001729 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001730 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001731 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1732 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001733 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001734 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001735 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001736 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1737 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1738 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1739 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001740 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1741 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1742 if (err != OK) {
1743 ALOGE("Failed to set up input surface: %d", err);
1744 mCallback->onInputSurfaceDeclined(err);
1745 return;
1746 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001747 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001748 int32_t width = 0;
1749 (void)outputFormat->findInt32("width", &width);
1750 int32_t height = 0;
1751 (void)outputFormat->findInt32("height", &height);
1752 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001753 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001754 if (err != OK) {
1755 ALOGE("Failed to set up input surface: %d", err);
1756 mCallback->onInputSurfaceDeclined(err);
1757 return;
1758 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001759 } else {
1760 ALOGE("Failed to set input surface: Corrupted surface.");
1761 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1762 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001763 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001764 // Formats can change after setupInputSurface
1765 sp<AMessage> inputFormat;
1766 {
1767 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1768 const std::unique_ptr<Config> &config = *configLocked;
1769 inputFormat = config->mInputFormat;
1770 outputFormat = config->mOutputFormat;
1771 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001772 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1773}
1774
1775void CCodec::initiateStart() {
1776 auto setStarting = [this] {
1777 Mutexed<State>::Locked state(mState);
1778 if (state->get() != ALLOCATED) {
1779 return UNKNOWN_ERROR;
1780 }
1781 state->set(STARTING);
1782 return OK;
1783 };
1784 if (tryAndReportOnError(setStarting) != OK) {
1785 return;
1786 }
1787
1788 (new AMessage(kWhatStart, this))->post();
1789}
1790
1791void CCodec::start() {
1792 std::shared_ptr<Codec2Client::Component> comp;
1793 auto checkStarting = [this, &comp] {
1794 Mutexed<State>::Locked state(mState);
1795 if (state->get() != STARTING) {
1796 return UNKNOWN_ERROR;
1797 }
1798 comp = state->comp;
1799 return OK;
1800 };
1801 if (tryAndReportOnError(checkStarting) != OK) {
1802 return;
1803 }
1804
1805 c2_status_t err = comp->start();
1806 if (err != C2_OK) {
1807 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1808 ACTION_CODE_FATAL);
1809 return;
1810 }
Wonsik Kimd86c96b2023-06-22 14:42:17 -07001811
1812 // clear the deadline after the component starts
1813 setDeadline(TimePoint::max(), 0ms, "none");
1814
Pawin Vongmasa36653902018-11-15 00:10:25 -08001815 sp<AMessage> inputFormat;
1816 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001817 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001818 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001819 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001820 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1821 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001822 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001823 // start triggers format dup
1824 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001825 if (config->mInputSurface) {
1826 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001827 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001828 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001829 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001830 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001831 if (err2 != OK) {
1832 mCallback->onError(err2, ACTION_CODE_FATAL);
1833 return;
1834 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001835 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001836 if (err2 != OK) {
1837 mCallback->onError(err2, ACTION_CODE_FATAL);
1838 return;
1839 }
1840
1841 auto setRunning = [this] {
1842 Mutexed<State>::Locked state(mState);
1843 if (state->get() != STARTING) {
1844 return UNKNOWN_ERROR;
1845 }
1846 state->set(RUNNING);
1847 return OK;
1848 };
1849 if (tryAndReportOnError(setRunning) != OK) {
1850 return;
1851 }
Arun Johnson5997bb02022-04-01 19:35:44 +00001852
Wonsik Kim34b28b42022-05-20 15:49:32 -07001853 // preparation of input buffers may not succeed due to the lack of
1854 // memory; returning correct error code (NO_MEMORY) as an error allows
1855 // MediaCodec to try reclaim and restart codec gracefully.
1856 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
1857 err2 = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
1858 if (err2 != OK) {
1859 ALOGE("Initial preparation for Input Buffers failed");
1860 mCallback->onError(err2, ACTION_CODE_FATAL);
1861 return;
1862 }
1863
Pawin Vongmasa36653902018-11-15 00:10:25 -08001864 mCallback->onStartCompleted();
1865
Wonsik Kim34b28b42022-05-20 15:49:32 -07001866 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001867}
1868
1869void CCodec::initiateShutdown(bool keepComponentAllocated) {
1870 if (keepComponentAllocated) {
1871 initiateStop();
1872 } else {
1873 initiateRelease();
1874 }
1875}
1876
1877void CCodec::initiateStop() {
1878 {
1879 Mutexed<State>::Locked state(mState);
1880 if (state->get() == ALLOCATED
1881 || state->get() == RELEASED
1882 || state->get() == STOPPING
1883 || state->get() == RELEASING) {
1884 // We're already stopped, released, or doing it right now.
1885 state.unlock();
1886 mCallback->onStopCompleted();
1887 state.lock();
1888 return;
1889 }
1890 state->set(STOPPING);
1891 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001892 mChannel->reset();
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001893 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
1894 sp<AMessage> stopMessage(new AMessage(kWhatStop, this));
1895 stopMessage->setInt32("pushBlankBuffer", pushBlankBuffer);
1896 stopMessage->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001897}
1898
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001899void CCodec::stop(bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001900 std::shared_ptr<Codec2Client::Component> comp;
1901 {
1902 Mutexed<State>::Locked state(mState);
1903 if (state->get() == RELEASING) {
1904 state.unlock();
1905 // We're already stopped or release is in progress.
1906 mCallback->onStopCompleted();
1907 state.lock();
1908 return;
1909 } else if (state->get() != STOPPING) {
1910 state.unlock();
1911 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1912 state.lock();
1913 return;
1914 }
1915 comp = state->comp;
1916 }
1917 status_t err = comp->stop();
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001918 mChannel->stopUseOutputSurface(pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001919 if (err != C2_OK) {
1920 // TODO: convert err into status_t
1921 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1922 }
1923
1924 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001925 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1926 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001927 if (config->mInputSurface) {
1928 config->mInputSurface->disconnect();
1929 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001930 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001931 }
1932 }
1933 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001934 Mutexed<State>::Locked state(mState);
1935 if (state->get() == STOPPING) {
1936 state->set(ALLOCATED);
1937 }
1938 }
1939 mCallback->onStopCompleted();
1940}
1941
1942void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001943 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001944 {
1945 Mutexed<State>::Locked state(mState);
1946 if (state->get() == RELEASED || state->get() == RELEASING) {
1947 // We're already released or doing it right now.
1948 if (sendCallback) {
1949 state.unlock();
1950 mCallback->onReleaseCompleted();
1951 state.lock();
1952 }
1953 return;
1954 }
1955 if (state->get() == ALLOCATING) {
1956 state->set(RELEASING);
1957 // With the altered state allocate() would fail and clean up.
1958 if (sendCallback) {
1959 state.unlock();
1960 mCallback->onReleaseCompleted();
1961 state.lock();
1962 }
1963 return;
1964 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001965 if (state->get() == STARTING
1966 || state->get() == RUNNING
1967 || state->get() == STOPPING) {
1968 // Input surface may have been started, so clean up is needed.
1969 clearInputSurfaceIfNeeded = true;
1970 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001971 state->set(RELEASING);
1972 }
1973
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001974 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001975 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1976 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001977 if (config->mInputSurface) {
1978 config->mInputSurface->disconnect();
1979 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001980 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001981 }
1982 }
1983
Wonsik Kim936a89c2020-05-08 16:07:50 -07001984 mChannel->reset();
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001985 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001986 // thiz holds strong ref to this while the thread is running.
1987 sp<CCodec> thiz(this);
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001988 std::thread([thiz, sendCallback, pushBlankBuffer]
1989 { thiz->release(sendCallback, pushBlankBuffer); }).detach();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001990}
1991
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001992void CCodec::release(bool sendCallback, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001993 std::shared_ptr<Codec2Client::Component> comp;
1994 {
1995 Mutexed<State>::Locked state(mState);
1996 if (state->get() == RELEASED) {
1997 if (sendCallback) {
1998 state.unlock();
1999 mCallback->onReleaseCompleted();
2000 state.lock();
2001 }
2002 return;
2003 }
2004 comp = state->comp;
2005 }
2006 comp->release();
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002007 mChannel->stopUseOutputSurface(pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002008
2009 {
2010 Mutexed<State>::Locked state(mState);
2011 state->set(RELEASED);
2012 state->comp.reset();
2013 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002014 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002015 if (sendCallback) {
2016 mCallback->onReleaseCompleted();
2017 }
2018}
2019
2020status_t CCodec::setSurface(const sp<Surface> &surface) {
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002021 bool pushBlankBuffer = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002022 {
2023 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2024 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002025 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
2026 status_t err = OK;
2027
Wonsik Kim75e22f42021-04-14 23:34:51 -07002028 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002029 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07002030 nativeWindow.get(),
2031 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
2032 if (err != OK) {
2033 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
2034 nativeWindow.get(), config->mSidebandHandle->handle(), err);
2035 return err;
2036 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002037 } else {
2038 // Explicitly reset the sideband handle of the window for
2039 // non-tunneled video in case the window was previously used
2040 // for a tunneled video playback.
2041 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
2042 if (err != OK) {
2043 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
2044 return err;
2045 }
ted.sun765db4d2020-06-23 14:03:41 +08002046 }
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002047 pushBlankBuffer = config->mPushBlankBuffersOnStop;
ted.sun765db4d2020-06-23 14:03:41 +08002048 }
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002049 return mChannel->setSurface(surface, pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002050}
2051
2052void CCodec::signalFlush() {
2053 status_t err = [this] {
2054 Mutexed<State>::Locked state(mState);
2055 if (state->get() == FLUSHED) {
2056 return ALREADY_EXISTS;
2057 }
2058 if (state->get() != RUNNING) {
2059 return UNKNOWN_ERROR;
2060 }
2061 state->set(FLUSHING);
2062 return OK;
2063 }();
2064 switch (err) {
2065 case ALREADY_EXISTS:
2066 mCallback->onFlushCompleted();
2067 return;
2068 case OK:
2069 break;
2070 default:
2071 mCallback->onError(err, ACTION_CODE_FATAL);
2072 return;
2073 }
2074
2075 mChannel->stop();
2076 (new AMessage(kWhatFlush, this))->post();
2077}
2078
2079void CCodec::flush() {
2080 std::shared_ptr<Codec2Client::Component> comp;
2081 auto checkFlushing = [this, &comp] {
2082 Mutexed<State>::Locked state(mState);
2083 if (state->get() != FLUSHING) {
2084 return UNKNOWN_ERROR;
2085 }
2086 comp = state->comp;
2087 return OK;
2088 };
2089 if (tryAndReportOnError(checkFlushing) != OK) {
2090 return;
2091 }
2092
2093 std::list<std::unique_ptr<C2Work>> flushedWork;
2094 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2095 {
2096 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2097 flushedWork.splice(flushedWork.end(), *queue);
2098 }
2099 if (err != C2_OK) {
2100 // TODO: convert err into status_t
2101 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2102 }
2103
2104 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002105
2106 {
2107 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002108 if (state->get() == FLUSHING) {
2109 state->set(FLUSHED);
2110 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002111 }
2112 mCallback->onFlushCompleted();
2113}
2114
2115void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002116 std::shared_ptr<Codec2Client::Component> comp;
2117 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002118 Mutexed<State>::Locked state(mState);
2119 if (state->get() != FLUSHED) {
2120 return UNKNOWN_ERROR;
2121 }
2122 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002123 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002124 return OK;
2125 };
2126 if (tryAndReportOnError(setResuming) != OK) {
2127 return;
2128 }
2129
Wonsik Kime75a5da2020-02-14 17:29:03 -08002130 {
2131 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2132 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002133 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002134 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002135 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002136 }
2137
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002138 (void)mChannel->start(nullptr, nullptr, [&]{
2139 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2140 const std::unique_ptr<Config> &config = *configLocked;
2141 return config->mBuffersBoundToCodec;
2142 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002143
2144 {
2145 Mutexed<State>::Locked state(mState);
2146 if (state->get() != RESUMING) {
2147 state.unlock();
2148 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2149 state.lock();
2150 return;
2151 }
2152 state->set(RUNNING);
2153 }
2154
Wonsik Kim34b28b42022-05-20 15:49:32 -07002155 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
2156 status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
Wonsik Kim944b0a52022-08-18 17:06:33 -07002157 // FIXME(b/237656746)
2158 if (err != OK && err != NO_MEMORY) {
Wonsik Kima027bf72022-05-09 19:45:57 -07002159 ALOGE("Resume request for Input Buffers failed");
2160 mCallback->onError(err, ACTION_CODE_FATAL);
Wonsik Kim34b28b42022-05-20 15:49:32 -07002161 return;
Wonsik Kima027bf72022-05-09 19:45:57 -07002162 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07002163 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002164}
2165
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002166void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002167 std::shared_ptr<Codec2Client::Component> comp;
2168 auto checkState = [this, &comp] {
2169 Mutexed<State>::Locked state(mState);
2170 if (state->get() == RELEASED) {
2171 return INVALID_OPERATION;
2172 }
2173 comp = state->comp;
2174 return OK;
2175 };
2176 if (tryAndReportOnError(checkState) != OK) {
2177 return;
2178 }
2179
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002180 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2181 // the behavior here.
2182 sp<AMessage> params = msg;
2183 int32_t bitrate;
2184 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2185 params = msg->dup();
2186 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2187 }
2188
Houxiang Dai5a97b472021-03-22 17:56:04 +08002189 int32_t syncId = 0;
2190 if (params->findInt32("audio-hw-sync", &syncId)
2191 || params->findInt32("hw-av-sync-id", &syncId)) {
2192 configureTunneledVideoPlayback(comp, nullptr, params);
2193 }
2194
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002195 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2196 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002197
2198 /**
2199 * Handle input surface parameters
2200 */
2201 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002202 && (config->mDomain & Config::IS_ENCODER)
2203 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002204 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002205
2206 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2207 config->mISConfig->mStopped = false;
2208 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2209 config->mISConfig->mStopped = true;
2210 }
2211
2212 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002213 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002214 config->mISConfig->mSuspended = value;
2215 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002216 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002217 }
2218
2219 (void)config->mInputSurface->configure(*config->mISConfig);
2220 if (config->mISConfig->mStopped) {
2221 config->mInputFormat->setInt64(
2222 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2223 }
2224 }
2225
2226 std::vector<std::unique_ptr<C2Param>> configUpdate;
2227 (void)config->getConfigUpdateFromSdkParams(
2228 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2229 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2230 // Parameter synchronization is not defined when using input surface. For now, route
2231 // these directly to the component.
2232 if (config->mInputSurface == nullptr
2233 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2234 || comp->getName().find("c2.android.") == 0)) {
2235 mChannel->setParameters(configUpdate);
2236 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002237 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002238 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002239 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002240 }
2241}
2242
2243void CCodec::signalEndOfInputStream() {
2244 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2245}
2246
2247void CCodec::signalRequestIDRFrame() {
2248 std::shared_ptr<Codec2Client::Component> comp;
2249 {
2250 Mutexed<State>::Locked state(mState);
2251 if (state->get() == RELEASED) {
2252 ALOGD("no IDR request sent since component is released");
2253 return;
2254 }
2255 comp = state->comp;
2256 }
2257 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002258 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2259 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002260 std::vector<std::unique_ptr<C2Param>> params;
2261 params.push_back(
2262 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2263 config->setParameters(comp, params, C2_MAY_BLOCK);
2264}
2265
Wonsik Kim874ad382021-03-12 09:59:36 -08002266status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2267 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2268 const std::unique_ptr<Config> &config = *configLocked;
2269 return config->querySupportedParameters(names);
2270}
2271
2272status_t CCodec::describeParameter(
2273 const std::string &name, CodecParameterDescriptor *desc) {
2274 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2275 const std::unique_ptr<Config> &config = *configLocked;
2276 return config->describe(name, desc);
2277}
2278
2279status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2280 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2281 if (!comp) {
2282 return INVALID_OPERATION;
2283 }
2284 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2285 const std::unique_ptr<Config> &config = *configLocked;
2286 return config->subscribeToVendorConfigUpdate(comp, names);
2287}
2288
2289status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2290 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2291 if (!comp) {
2292 return INVALID_OPERATION;
2293 }
2294 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2295 const std::unique_ptr<Config> &config = *configLocked;
2296 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2297}
2298
Wonsik Kimab34ed62019-01-31 15:28:46 -08002299void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002300 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002301 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2302 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002303 }
2304 (new AMessage(kWhatWorkDone, this))->post();
2305}
2306
Wonsik Kimab34ed62019-01-31 15:28:46 -08002307void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2308 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002309 if (arrayIndex == 0) {
2310 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002311 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2312 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002313 if (config->mInputSurface) {
2314 config->mInputSurface->onInputBufferDone(frameIndex);
2315 }
2316 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002317}
2318
2319void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2320 TimePoint now = std::chrono::steady_clock::now();
2321 CCodecWatchdog::getInstance()->watch(this);
2322 switch (msg->what()) {
2323 case kWhatAllocate: {
2324 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002325 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002326 sp<RefBase> obj;
2327 CHECK(msg->findObject("codecInfo", &obj));
2328 allocate((MediaCodecInfo *)obj.get());
2329 break;
2330 }
2331 case kWhatConfigure: {
2332 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002333 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002334 sp<AMessage> format;
2335 CHECK(msg->findMessage("format", &format));
2336 configure(format);
2337 break;
2338 }
2339 case kWhatStart: {
2340 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002341 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002342 start();
2343 break;
2344 }
2345 case kWhatStop: {
2346 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002347 setDeadline(now, 1500ms, "stop");
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002348 int32_t pushBlankBuffer;
2349 if (!msg->findInt32("pushBlankBuffer", &pushBlankBuffer)) {
2350 pushBlankBuffer = 0;
2351 }
2352 stop(static_cast<bool>(pushBlankBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002353 break;
2354 }
2355 case kWhatFlush: {
2356 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002357 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002358 flush();
2359 break;
2360 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002361 case kWhatRelease: {
2362 mChannel->release();
2363 mClient.reset();
2364 mClientListener.reset();
2365 break;
2366 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002367 case kWhatCreateInputSurface: {
2368 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002369 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002370 createInputSurface();
2371 break;
2372 }
2373 case kWhatSetInputSurface: {
2374 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002375 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002376 sp<RefBase> obj;
2377 CHECK(msg->findObject("surface", &obj));
2378 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2379 setInputSurface(surface);
2380 break;
2381 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002382 case kWhatWorkDone: {
2383 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002384 bool shouldPost = false;
2385 {
2386 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2387 if (queue->empty()) {
2388 break;
2389 }
2390 work.swap(queue->front());
2391 queue->pop_front();
2392 shouldPost = !queue->empty();
2393 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002394 if (shouldPost) {
2395 (new AMessage(kWhatWorkDone, this))->post();
2396 }
2397
Pawin Vongmasa36653902018-11-15 00:10:25 -08002398 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002399 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002400 sp<AMessage> outputFormat = nullptr;
2401 {
2402 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2403 const std::unique_ptr<Config> &config = *configLocked;
2404 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2405 config->watch<C2StreamInitDataInfo::output>();
2406 if (!work->worklets.empty()
2407 && (work->worklets.front()->output.flags
2408 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002409
Wonsik Kim75e22f42021-04-14 23:34:51 -07002410 // copy buffer info to config
2411 std::vector<std::unique_ptr<C2Param>> updates;
2412 for (const std::unique_ptr<C2Param> &param
2413 : work->worklets.front()->output.configUpdate) {
2414 updates.push_back(C2Param::Copy(*param));
2415 }
2416 unsigned stream = 0;
2417 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2418 work->worklets.front()->output.buffers;
2419 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2420 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2421 // move all info into output-stream #0 domain
2422 updates.emplace_back(
2423 C2Param::CopyAsStream(*info, true /* output */, stream));
2424 }
2425
2426 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2427 // for now only do the first block
2428 if (!blocks.empty()) {
2429 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2430 // block.crop().left, block.crop().top,
2431 // block.crop().width, block.crop().height,
2432 // block.width(), block.height());
2433 const C2ConstGraphicBlock &block = blocks[0];
2434 updates.emplace_back(new C2StreamCropRectInfo::output(
2435 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002436 }
2437 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002438 }
George Burgess IVc813a592020-02-22 22:54:44 -08002439
Wonsik Kim75e22f42021-04-14 23:34:51 -07002440 sp<AMessage> oldFormat = config->mOutputFormat;
2441 config->updateConfiguration(updates, config->mOutputDomain);
2442 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002443
Wonsik Kim75e22f42021-04-14 23:34:51 -07002444 // copy standard infos to graphic buffers if not already present (otherwise, we
2445 // may overwrite the actual intermediate value with a final value)
2446 stream = 0;
2447 const static C2Param::Index stdGfxInfos[] = {
2448 C2StreamRotationInfo::output::PARAM_TYPE,
2449 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2450 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2451 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Taehwan Kim2d222b82022-05-12 14:19:26 +09002452 C2StreamHdr10PlusInfo::output::PARAM_TYPE, // will be deprecated
2453 C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE,
Wonsik Kim75e22f42021-04-14 23:34:51 -07002454 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2455 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2456 };
2457 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2458 if (buf->data().graphicBlocks().size()) {
2459 for (C2Param::Index ix : stdGfxInfos) {
2460 if (!buf->hasInfo(ix)) {
2461 const C2Param *param =
2462 config->getConfigParameterValue(ix.withStream(stream));
2463 if (param) {
2464 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2465 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2466 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002467 }
2468 }
2469 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002470 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002471 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002472 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002473 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302474 if (work->worklets.empty()
2475 || !work->worklets.back()
2476 || (work->worklets.back()->output.flags
2477 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2478 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2479 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002480 }
2481 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002482 initData = initDataWatcher.update();
2483 AmendOutputFormatWithCodecSpecificData(
2484 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2485 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002486 }
2487 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002488 }
2489 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002490 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002491 break;
2492 }
2493 case kWhatWatch: {
2494 // watch message already posted; no-op.
2495 break;
2496 }
2497 default: {
2498 ALOGE("unrecognized message");
2499 break;
2500 }
2501 }
2502 setDeadline(TimePoint::max(), 0ms, "none");
2503}
2504
2505void CCodec::setDeadline(
2506 const TimePoint &now,
2507 const std::chrono::milliseconds &timeout,
2508 const char *name) {
2509 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2510 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2511 deadline->set(now + (timeout * mult), name);
2512}
2513
ted.sun765db4d2020-06-23 14:03:41 +08002514status_t CCodec::configureTunneledVideoPlayback(
2515 std::shared_ptr<Codec2Client::Component> comp,
2516 sp<NativeHandle> *sidebandHandle,
2517 const sp<AMessage> &msg) {
2518 std::vector<std::unique_ptr<C2SettingResult>> failures;
2519
2520 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2521 C2PortTunneledModeTuning::output::AllocUnique(
2522 1,
2523 C2PortTunneledModeTuning::Struct::SIDEBAND,
2524 C2PortTunneledModeTuning::Struct::REALTIME,
2525 0);
2526 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2527 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2528 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2529 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2530 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2531 } else {
2532 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2533 tunneledPlayback->setFlexCount(0);
2534 }
2535 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2536 if (c2err != C2_OK) {
2537 return UNKNOWN_ERROR;
2538 }
2539
Houxiang Dai5a97b472021-03-22 17:56:04 +08002540 if (sidebandHandle == nullptr) {
2541 return OK;
2542 }
2543
ted.sun765db4d2020-06-23 14:03:41 +08002544 std::vector<std::unique_ptr<C2Param>> params;
2545 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2546 if (c2err == C2_OK && params.size() == 1u) {
2547 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2548 C2PortTunnelHandleTuning::output::From(params[0].get());
2549 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2550 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2551 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2552 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2553 memcpy(handle->data, videoTunnelSideband->m.values,
2554 sizeof(int32_t) * videoTunnelSideband->flexCount());
2555 return OK;
2556 } else {
2557 return NO_MEMORY;
2558 }
2559 }
2560 return UNKNOWN_ERROR;
2561}
2562
Pawin Vongmasa36653902018-11-15 00:10:25 -08002563void CCodec::initiateReleaseIfStuck() {
Shrikara B3b87a532022-08-26 14:18:14 +05302564 std::string name;
2565 bool pendingDeadline = false;
2566 {
2567 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2568 if (deadline->get() < std::chrono::steady_clock::now()) {
2569 name = deadline->getName();
2570 }
2571 if (deadline->get() != TimePoint::max()) {
2572 pendingDeadline = true;
2573 }
2574 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002575 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002576 // We're not stuck.
2577 if (pendingDeadline) {
2578 // If we are not stuck yet but still has deadline coming up,
2579 // post watch message to check back later.
2580 (new AMessage(kWhatWatch, this))->post();
2581 }
2582 return;
2583 }
2584
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002585 C2String compName;
2586 {
2587 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002588 if (!state->comp) {
2589 ALOGD("previous call to %s exceeded timeout "
2590 "and the component is already released", name.c_str());
2591 return;
2592 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002593 compName = state->comp->getName();
2594 }
2595 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2596
Pawin Vongmasa36653902018-11-15 00:10:25 -08002597 initiateRelease(false);
2598 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2599}
2600
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002601// static
2602PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002603 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002604 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002605 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002606 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2607 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002608 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002609 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2610 sp<IGraphicBufferProducer> gbp;
2611 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2612 status_t err = gbs->initCheck();
2613 if (err != OK) {
2614 ALOGE("Failed to create persistent input surface: error %d", err);
2615 return nullptr;
2616 }
2617 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002618 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002619 } else {
2620 return nullptr;
2621 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002622 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002623 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002624 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002625 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002626 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002627}
2628
Wonsik Kimffb889a2020-05-28 11:32:25 -07002629class IntfCache {
2630public:
2631 IntfCache() = default;
2632
2633 status_t init(const std::string &name) {
2634 std::shared_ptr<Codec2Client::Interface> intf{
2635 Codec2Client::CreateInterfaceByName(name.c_str())};
2636 if (!intf) {
2637 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2638 mInitStatus = NO_INIT;
2639 return NO_INIT;
2640 }
2641 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2642 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2643 C2ParamField{&sUsage, &sUsage.value}));
2644 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2645 if (err != C2_OK) {
2646 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2647 name.c_str(), err);
2648 mFields[0].status = err;
2649 }
2650 std::vector<std::unique_ptr<C2Param>> params;
2651 err = intf->query(
2652 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09002653 {
2654 C2StreamBufferTypeSetting::input::PARAM_TYPE,
2655 C2PortAllocatorsTuning::input::PARAM_TYPE
2656 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07002657 C2_MAY_BLOCK,
2658 &params);
2659 if (err != C2_OK && err != C2_BAD_INDEX) {
2660 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2661 name.c_str(), err);
2662 }
2663 while (!params.empty()) {
2664 C2Param *param = params.back().release();
2665 params.pop_back();
2666 if (!param) {
2667 continue;
2668 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002669 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
2670 mInputStreamFormat.reset(
2671 C2StreamBufferTypeSetting::input::From(param));
2672 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002673 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002674 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002675 }
2676 }
2677 mInitStatus = OK;
2678 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002679 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002680
2681 status_t initCheck() const { return mInitStatus; }
2682
2683 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2684 CHECK_EQ(1u, mFields.size());
2685 return mFields[0];
2686 }
2687
2688 const C2ApiFeaturesSetting &getApiFeatures() const {
2689 return mApiFeatures;
2690 }
2691
Taehwan Kim900b49c2021-12-13 11:16:22 +09002692 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
2693 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
2694 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
2695 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
2696 param->invalidate();
2697 return param;
2698 }();
2699 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
2700 }
2701
Wonsik Kimffb889a2020-05-28 11:32:25 -07002702 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2703 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2704 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2705 C2PortAllocatorsTuning::input::AllocUnique(0);
2706 param->invalidate();
2707 return param;
2708 }();
2709 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2710 }
2711
2712private:
2713 status_t mInitStatus{NO_INIT};
2714
2715 std::vector<C2FieldSupportedValuesQuery> mFields;
2716 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09002717 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002718 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2719};
2720
2721static const IntfCache &GetIntfCache(const std::string &name) {
2722 static IntfCache sNullIntfCache;
2723 static std::mutex sMutex;
2724 static std::map<std::string, IntfCache> sCache;
2725 std::unique_lock<std::mutex> lock{sMutex};
2726 auto it = sCache.find(name);
2727 if (it == sCache.end()) {
2728 lock.unlock();
2729 IntfCache intfCache;
2730 status_t err = intfCache.init(name);
2731 if (err != OK) {
2732 return sNullIntfCache;
2733 }
2734 lock.lock();
2735 it = sCache.insert({name, std::move(intfCache)}).first;
2736 }
2737 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002738}
2739
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002740static status_t GetCommonAllocatorIds(
2741 const std::vector<std::string> &names,
2742 C2Allocator::type_t type,
2743 std::set<C2Allocator::id_t> *ids) {
2744 int poolMask = GetCodec2PoolMask();
2745 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2746 C2Allocator::id_t defaultAllocatorId =
2747 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2748
2749 ids->clear();
2750 if (names.empty()) {
2751 return OK;
2752 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002753 bool firstIteration = true;
2754 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002755 const IntfCache &intfCache = GetIntfCache(name);
2756 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002757 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002758 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002759 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
2760 if (streamFormat) {
2761 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
2762 if (streamFormat.value == C2BufferData::GRAPHIC
2763 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
2764 allocatorType = C2Allocator::GRAPHIC;
2765 }
2766
2767 if (type != allocatorType) {
2768 // requested type is not supported at input allocators
2769 ids->clear();
2770 ids->insert(defaultAllocatorId);
2771 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
2772 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
2773 break;
2774 }
2775 }
2776
Wonsik Kimffb889a2020-05-28 11:32:25 -07002777 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002778 if (firstIteration) {
2779 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002780 if (allocators && allocators.flexCount() > 0) {
2781 ids->insert(allocators.m.values,
2782 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002783 }
2784 if (ids->empty()) {
2785 // The component does not advertise allocators. Use default.
2786 ids->insert(defaultAllocatorId);
2787 }
2788 continue;
2789 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002790 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002791 if (allocators && allocators.flexCount() > 0) {
2792 filtered = true;
2793 for (auto it = ids->begin(); it != ids->end(); ) {
2794 bool found = false;
2795 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2796 if (allocators.m.values[j] == *it) {
2797 found = true;
2798 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002799 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002800 }
2801 if (found) {
2802 ++it;
2803 } else {
2804 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002805 }
2806 }
2807 }
2808 if (!filtered) {
2809 // The component does not advertise supported allocators. Use default.
2810 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2811 if (ids->size() != (containsDefault ? 1 : 0)) {
2812 ids->clear();
2813 if (containsDefault) {
2814 ids->insert(defaultAllocatorId);
2815 }
2816 }
2817 }
2818 }
2819 // Finally, filter with pool masks
2820 for (auto it = ids->begin(); it != ids->end(); ) {
2821 if ((poolMask >> *it) & 1) {
2822 ++it;
2823 } else {
2824 it = ids->erase(it);
2825 }
2826 }
2827 return OK;
2828}
2829
2830static status_t CalculateMinMaxUsage(
2831 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2832 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2833 *minUsage = 0;
2834 *maxUsage = ~0ull;
2835 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002836 const IntfCache &intfCache = GetIntfCache(name);
2837 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002838 continue;
2839 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002840 const C2FieldSupportedValuesQuery &usageSupportedValues =
2841 intfCache.getUsageSupportedValues();
2842 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002843 continue;
2844 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002845 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002846 if (supported.type != C2FieldSupportedValues::FLAGS) {
2847 continue;
2848 }
2849 if (supported.values.empty()) {
2850 *maxUsage = 0;
2851 continue;
2852 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08002853 if (supported.values.size() > 1) {
2854 *minUsage |= supported.values[1].u64;
2855 } else {
2856 *minUsage |= supported.values[0].u64;
2857 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002858 int64_t currentMaxUsage = 0;
2859 for (const C2Value::Primitive &flags : supported.values) {
2860 currentMaxUsage |= flags.u64;
2861 }
2862 *maxUsage &= currentMaxUsage;
2863 }
2864 return OK;
2865}
2866
2867// static
2868status_t CCodec::CanFetchLinearBlock(
2869 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002870 for (const std::string &name : names) {
2871 const IntfCache &intfCache = GetIntfCache(name);
2872 if (intfCache.initCheck() != OK) {
2873 continue;
2874 }
2875 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2876 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2877 *isCompatible = false;
2878 return OK;
2879 }
2880 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002881 std::set<C2Allocator::id_t> allocators;
2882 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2883 if (allocators.empty()) {
2884 *isCompatible = false;
2885 return OK;
2886 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002887
2888 uint64_t minUsage = 0;
2889 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002890 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002891 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002892 *isCompatible = ((maxUsage & minUsage) == minUsage);
2893 return OK;
2894}
2895
2896static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2897 static std::mutex sMutex{};
2898 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2899 std::unique_lock<std::mutex> lock{sMutex};
2900 std::shared_ptr<C2BlockPool> pool;
2901 auto it = sPools.find(allocId);
2902 if (it == sPools.end()) {
2903 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2904 if (err == OK) {
2905 sPools.emplace(allocId, pool);
2906 } else {
2907 pool.reset();
2908 }
2909 } else {
2910 pool = it->second;
2911 }
2912 return pool;
2913}
2914
2915// static
2916std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2917 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002918 std::set<C2Allocator::id_t> allocators;
2919 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2920 if (allocators.empty()) {
2921 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2922 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002923
2924 uint64_t minUsage = 0;
2925 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002926 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002927 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002928 if ((maxUsage & minUsage) != minUsage) {
2929 allocators.clear();
2930 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2931 }
2932 std::shared_ptr<C2LinearBlock> block;
2933 for (C2Allocator::id_t allocId : allocators) {
2934 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2935 if (!pool) {
2936 continue;
2937 }
2938 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2939 if (err != C2_OK || !block) {
2940 block.reset();
2941 continue;
2942 }
2943 break;
2944 }
2945 return block;
2946}
2947
2948// static
2949status_t CCodec::CanFetchGraphicBlock(
2950 const std::vector<std::string> &names, bool *isCompatible) {
2951 uint64_t minUsage = 0;
2952 uint64_t maxUsage = ~0ull;
2953 std::set<C2Allocator::id_t> allocators;
2954 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2955 if (allocators.empty()) {
2956 *isCompatible = false;
2957 return OK;
2958 }
2959 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2960 *isCompatible = ((maxUsage & minUsage) == minUsage);
2961 return OK;
2962}
2963
2964// static
2965std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2966 int32_t width,
2967 int32_t height,
2968 int32_t format,
2969 uint64_t usage,
2970 const std::vector<std::string> &names) {
2971 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2972 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2973 ALOGD("Unrecognized pixel format: %d", format);
2974 return nullptr;
2975 }
2976 uint64_t minUsage = 0;
2977 uint64_t maxUsage = ~0ull;
2978 std::set<C2Allocator::id_t> allocators;
2979 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2980 if (allocators.empty()) {
2981 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2982 }
2983 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2984 minUsage |= usage;
2985 if ((maxUsage & minUsage) != minUsage) {
2986 allocators.clear();
2987 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2988 }
2989 std::shared_ptr<C2GraphicBlock> block;
2990 for (C2Allocator::id_t allocId : allocators) {
2991 std::shared_ptr<C2BlockPool> pool;
2992 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2993 if (err != C2_OK || !pool) {
2994 continue;
2995 }
2996 err = pool->fetchGraphicBlock(
2997 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2998 if (err != C2_OK || !block) {
2999 block.reset();
3000 continue;
3001 }
3002 break;
3003 }
3004 return block;
3005}
3006
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003007} // namespace android