blob: c102c4bb42769dd7006044bfba26176dca9d465c [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);
Ian Kasprzak50990272023-08-11 16:31:50 +0000209 // Usage is queried during configure(), so setting it beforehand.
Sungtak Lee46a69d62023-08-12 07:24:24 +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());
Sungtak Lee214ce612023-11-01 10:01:13 +0000865 int32_t generation;
866 (void)msg->findInt32("native-window-generation", &generation);
ted.sun765db4d2020-06-23 14:03:41 +0800867 // setup tunneled playback
868 if (surface != nullptr) {
869 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
870 const std::unique_ptr<Config> &config = *configLocked;
871 if ((config->mDomain & Config::IS_DECODER)
872 && (config->mDomain & Config::IS_VIDEO)) {
873 int32_t tunneled;
874 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
875 ALOGI("Configuring TUNNELED video playback.");
876
877 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
878 if (err != OK) {
879 ALOGE("configureTunneledVideoPlayback failed!");
880 return err;
881 }
882 config->mTunneled = true;
883 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +0100884
885 int32_t pushBlankBuffersOnStop = 0;
886 if (msg->findInt32(KEY_PUSH_BLANK_BUFFERS_ON_STOP, &pushBlankBuffersOnStop)) {
887 config->mPushBlankBuffersOnStop = pushBlankBuffersOnStop == 1;
888 }
shuanglong.wang480a8362023-02-17 20:55:51 +0800889 // secure compoment or protected content default with
890 // "push-blank-buffers-on-shutdown" flag
891 if (!config->mPushBlankBuffersOnStop) {
892 int32_t usageProtected;
893 if (comp->getName().find(".secure") != std::string::npos) {
894 config->mPushBlankBuffersOnStop = true;
895 } else if (msg->findInt32("protected", &usageProtected) && usageProtected) {
896 config->mPushBlankBuffersOnStop = true;
897 }
898 }
ted.sun765db4d2020-06-23 14:03:41 +0800899 }
900 }
Sungtak Lee214ce612023-11-01 10:01:13 +0000901 setSurface(surface, (uint32_t)generation);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800902 }
903
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700904 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
905 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800906 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800907 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
908 ALOGD("[%s] buffers are %sbound to CCodec for this session",
909 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800910
Wonsik Kim1114eea2019-02-25 14:35:24 -0800911 // Enforce required parameters
912 int32_t i32;
913 float flt;
914 if (config->mDomain & Config::IS_AUDIO) {
915 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
916 ALOGD("sample rate is missing, which is required for audio components.");
917 return BAD_VALUE;
918 }
919 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
920 ALOGD("channel count is missing, which is required for audio components.");
921 return BAD_VALUE;
922 }
923 if ((config->mDomain & Config::IS_ENCODER)
924 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
925 && !msg->findInt32(KEY_BIT_RATE, &i32)
926 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
927 ALOGD("bitrate is missing, which is required for audio encoders.");
928 return BAD_VALUE;
929 }
930 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800931 int32_t width = 0;
932 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800933 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800934 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800935 ALOGD("width is missing, which is required for image/video components.");
936 return BAD_VALUE;
937 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800938 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800939 ALOGD("height is missing, which is required for image/video components.");
940 return BAD_VALUE;
941 }
942 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700943 int32_t mode = BITRATE_MODE_VBR;
944 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700945 if (!msg->findInt32(KEY_QUALITY, &i32)) {
946 ALOGD("quality is missing, which is required for video encoders in CQ.");
947 return BAD_VALUE;
948 }
949 } else {
950 if (!msg->findInt32(KEY_BIT_RATE, &i32)
951 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
952 ALOGD("bitrate is missing, which is required for video encoders.");
953 return BAD_VALUE;
954 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800955 }
956 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
957 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
958 ALOGD("I frame interval is missing, which is required for video encoders.");
959 return BAD_VALUE;
960 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700961 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
962 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
963 ALOGD("frame rate is missing, which is required for video encoders.");
964 return BAD_VALUE;
965 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800966 }
967 }
968
Pawin Vongmasa36653902018-11-15 00:10:25 -0800969 /*
970 * Handle input surface configuration
971 */
972 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
973 && (config->mDomain & Config::IS_ENCODER)) {
974 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
975 {
976 config->mISConfig->mMinFps = 0;
977 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800978 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800979 config->mISConfig->mMinFps = 1e6 / value;
980 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700981 if (!msg->findFloat(
982 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
983 config->mISConfig->mMaxFps = -1;
984 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800985 config->mISConfig->mMinAdjustedFps = 0;
986 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800987 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800988 if (value < 0 && value >= INT32_MIN) {
989 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700990 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800991 } else if (value > 0 && value <= INT32_MAX) {
992 config->mISConfig->mMinAdjustedFps = 1e6 / value;
993 }
994 }
995 }
996
997 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700998 bool captureFpsFound = false;
999 double timeLapseFps;
1000 float captureRate;
1001 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
1002 config->mISConfig->mCaptureFps = timeLapseFps;
1003 captureFpsFound = true;
1004 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
1005 config->mISConfig->mCaptureFps = captureRate;
1006 captureFpsFound = true;
1007 }
1008 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001009 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
1010 }
1011 }
1012
1013 {
1014 config->mISConfig->mSuspended = false;
1015 config->mISConfig->mSuspendAtUs = -1;
1016 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001017 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001018 config->mISConfig->mSuspended = true;
1019 }
1020 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001021 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -07001022 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001023 }
1024
1025 /*
1026 * Handle desired color format.
1027 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001028 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001029 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001030 int32_t format = 0;
1031 // Query vendor format for Flexible YUV
1032 std::vector<std::unique_ptr<C2Param>> heapParams;
1033 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
Wonsik Kim50811882022-04-28 15:57:27 -07001034 int vendorSdkVersion = base::GetIntProperty(
1035 "ro.vendor.build.version.sdk", android_get_device_api_level());
guochuang709b48b2022-10-25 20:40:42 +08001036 if (mClient->query(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001037 {},
1038 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1039 C2_MAY_BLOCK,
1040 &heapParams) == C2_OK
1041 && heapParams.size() == 1u) {
1042 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1043 heapParams[0].get());
1044 } else {
1045 pixelFormatInfo = nullptr;
1046 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001047 // bit depth -> format
1048 std::map<uint32_t, uint32_t> flexPixelFormat;
1049 std::map<uint32_t, uint32_t> flexPlanarPixelFormat;
1050 std::map<uint32_t, uint32_t> flexSemiPlanarPixelFormat;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001051 if (pixelFormatInfo && *pixelFormatInfo) {
1052 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1053 const C2FlexiblePixelFormatDescriptorStruct &desc =
1054 pixelFormatInfo->m.values[i];
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001055 if (desc.subsampling != C2Color::YUV_420
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001056 // TODO(b/180076105): some device report wrong layout
1057 // || desc.layout == C2Color::INTERLEAVED_PACKED
1058 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1059 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1060 continue;
1061 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001062 if (flexPixelFormat.count(desc.bitDepth) == 0) {
1063 flexPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001064 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001065 if (desc.layout == C2Color::PLANAR_PACKED
1066 && flexPlanarPixelFormat.count(desc.bitDepth) == 0) {
1067 flexPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001068 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001069 if (desc.layout == C2Color::SEMIPLANAR_PACKED
1070 && flexSemiPlanarPixelFormat.count(desc.bitDepth) == 0) {
1071 flexSemiPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001072 }
1073 }
1074 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001075 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001076 // Also handle default color format (encoders require color format, so this is only
1077 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001078 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001079 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001080 const char *prefix = "";
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001081 if (flexSemiPlanarPixelFormat.count(8) != 0) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001082 format = COLOR_FormatYUV420SemiPlanar;
1083 prefix = "semi-";
1084 } else {
1085 format = COLOR_FormatYUV420Planar;
1086 }
1087 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1088 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001089 } else {
1090 format = COLOR_FormatSurface;
1091 }
1092 defaultColorFormat = format;
1093 }
1094 } else {
1095 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001096 if (vendorSdkVersion < __ANDROID_API_S__ &&
Taehwan Kim43e715d2022-09-22 12:04:59 +09001097 (format == COLOR_FormatYUV420Planar ||
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001098 format == COLOR_FormatYUV420PackedPlanar ||
1099 format == COLOR_FormatYUV420SemiPlanar ||
1100 format == COLOR_FormatYUV420PackedSemiPlanar)) {
1101 // pre-S framework used to map these color formats into YV12.
1102 // Codecs from older vendor partition may be relying on
1103 // this assumption.
1104 format = HAL_PIXEL_FORMAT_YV12;
1105 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001106 switch (format) {
1107 case COLOR_FormatYUV420Flexible:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001108 format = COLOR_FormatYUV420Planar;
1109 if (flexPixelFormat.count(8) != 0) {
1110 format = flexPixelFormat[8];
1111 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001112 break;
1113 case COLOR_FormatYUV420Planar:
1114 case COLOR_FormatYUV420PackedPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001115 if (flexPlanarPixelFormat.count(8) != 0) {
1116 format = flexPlanarPixelFormat[8];
1117 } else if (flexPixelFormat.count(8) != 0) {
1118 format = flexPixelFormat[8];
1119 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001120 break;
1121 case COLOR_FormatYUV420SemiPlanar:
1122 case COLOR_FormatYUV420PackedSemiPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001123 if (flexSemiPlanarPixelFormat.count(8) != 0) {
1124 format = flexSemiPlanarPixelFormat[8];
1125 } else if (flexPixelFormat.count(8) != 0) {
1126 format = flexPixelFormat[8];
1127 }
1128 break;
1129 case COLOR_FormatYUVP010:
1130 format = COLOR_FormatYUVP010;
1131 if (flexSemiPlanarPixelFormat.count(10) != 0) {
1132 format = flexSemiPlanarPixelFormat[10];
1133 } else if (flexPixelFormat.count(10) != 0) {
1134 format = flexPixelFormat[10];
1135 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001136 break;
1137 default:
1138 // No-op
1139 break;
1140 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001141 }
1142 }
1143
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001144 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001145 msg->setInt32("android._color-format", format);
1146 }
1147 }
1148
Wonsik Kim77e97c72021-01-20 10:33:22 -08001149 /*
1150 * Handle dataspace
1151 */
1152 int32_t usingRecorder;
1153 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1154 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1155 int32_t width, height;
1156 if (msg->findInt32("width", &width)
1157 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001158 ColorAspects aspects;
1159 getColorAspectsFromFormat(msg, aspects);
1160 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001161 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001162 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1163 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001164 }
1165 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1166 ALOGD("setting dataspace to %x", dataSpace);
1167 }
1168
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001169 int32_t subscribeToAllVendorParams;
1170 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1171 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1172 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1173 }
1174 }
1175
Pawin Vongmasa36653902018-11-15 00:10:25 -08001176 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001177 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1178 // the behavior here.
1179 sp<AMessage> sdkParams = msg;
1180 int32_t videoBitrate;
1181 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1182 sdkParams = msg->dup();
1183 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1184 }
ted.sun765db4d2020-06-23 14:03:41 +08001185 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001186 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001187 if (err != OK) {
1188 ALOGW("failed to convert configuration to c2 params");
1189 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001190
1191 int32_t maxBframes = 0;
1192 if ((config->mDomain & Config::IS_ENCODER)
1193 && (config->mDomain & Config::IS_VIDEO)
1194 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1195 && maxBframes > 0) {
1196 std::unique_ptr<C2StreamGopTuning::output> gop =
1197 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1198 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1199 gop->m.values[1] = {
1200 C2Config::picture_type_t(P_FRAME | B_FRAME),
1201 uint32_t(maxBframes)
1202 };
1203 configUpdate.push_back(std::move(gop));
1204 }
1205
Ray Essicka0ae6972021-03-10 19:40:01 -08001206 if ((config->mDomain & Config::IS_ENCODER)
1207 && (config->mDomain & Config::IS_VIDEO)) {
1208 // we may not use all 3 of these entries
1209 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1210 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1211 0u /* stream */);
1212
1213 int ix = 0;
1214
1215 int32_t iMax = INT32_MAX;
1216 int32_t iMin = INT32_MIN;
1217 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1218 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1219 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1220 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1221 }
1222
1223 int32_t pMax = INT32_MAX;
1224 int32_t pMin = INT32_MIN;
1225 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1226 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1227 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1228 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1229 }
1230
1231 int32_t bMax = INT32_MAX;
1232 int32_t bMin = INT32_MIN;
1233 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1234 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1235 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1236 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1237 }
1238
1239 // adjust to reflect actual use.
1240 qp->setFlexCount(ix);
1241
1242 configUpdate.push_back(std::move(qp));
1243 }
1244
Wonsik Kima1335e12021-04-22 16:28:29 -07001245 int32_t background = 0;
1246 if ((config->mDomain & Config::IS_VIDEO)
1247 && msg->findInt32("android._background-mode", &background)
1248 && background) {
1249 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1250 if (config->mISConfig) {
1251 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1252 }
1253 }
1254
Pawin Vongmasa36653902018-11-15 00:10:25 -08001255 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1256 if (err != OK) {
1257 ALOGW("failed to configure c2 params");
1258 return err;
1259 }
1260
1261 std::vector<std::unique_ptr<C2Param>> params;
1262 C2StreamUsageTuning::input usage(0u, 0u);
1263 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001264 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001265
Wonsik Kim3baecda2021-02-07 22:19:56 -08001266 C2Param::Index colorAspectsRequestIndex =
1267 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001268 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001269 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001270 };
Chaejung Lim86c22dc2021-12-23 00:41:05 -08001271 int32_t colorTransferRequest = 0;
1272 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1273 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1274 colorTransferRequest = 0;
1275 }
1276 c2_status_t c2err = C2_OK;
1277 if (colorTransferRequest != 0) {
1278 c2err = comp->query(
1279 { &usage, &maxInputSize, &prepend },
1280 indices,
1281 C2_DONT_BLOCK,
1282 &params);
1283 } else {
1284 c2err = comp->query(
1285 { &usage, &maxInputSize, &prepend },
1286 {},
1287 C2_DONT_BLOCK,
1288 &params);
1289 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001290 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1291 ALOGE("Failed to query component interface: %d", c2err);
1292 return UNKNOWN_ERROR;
1293 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001294 if (usage) {
1295 if (usage.value & C2MemoryUsage::CPU_READ) {
1296 config->mInputFormat->setInt32("using-sw-read-often", true);
1297 }
1298 if (config->mISConfig) {
1299 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1300 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1301 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001302 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001303 }
1304
1305 // NOTE: we don't blindly use client specified input size if specified as clients
1306 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1307 // client specified size is only used to ask for bigger buffers than component suggested
1308 // size.
1309 int32_t clientInputSize = 0;
1310 bool clientSpecifiedInputSize =
1311 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1312 // TEMP: enforce minimum buffer size of 1MB for video decoders
1313 // and 16K / 4K for audio encoders/decoders
1314 if (maxInputSize.value == 0) {
1315 if (config->mDomain & Config::IS_AUDIO) {
1316 maxInputSize.value = encoder ? 16384 : 4096;
1317 } else if (!encoder) {
1318 maxInputSize.value = 1048576u;
1319 }
1320 }
1321
1322 // verify that CSD fits into this size (if defined)
1323 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1324 sp<ABuffer> csd;
1325 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1326 if (csd && csd->size() > maxInputSize.value) {
1327 maxInputSize.value = csd->size();
1328 }
1329 }
1330 }
1331
1332 // TODO: do this based on component requiring linear allocator for input
1333 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1334 if (clientSpecifiedInputSize) {
1335 // Warn that we're overriding client's max input size if necessary.
1336 if ((uint32_t)clientInputSize < maxInputSize.value) {
1337 ALOGD("client requested max input size %d, which is smaller than "
1338 "what component recommended (%u); overriding with component "
1339 "recommendation.", clientInputSize, maxInputSize.value);
1340 ALOGW("This behavior is subject to change. It is recommended that "
1341 "app developers double check whether the requested "
1342 "max input size is in reasonable range.");
1343 } else {
1344 maxInputSize.value = clientInputSize;
1345 }
1346 }
1347 // Pass max input size on input format to the buffer channel (if supplied by the
1348 // component or by a default)
1349 if (maxInputSize.value) {
1350 config->mInputFormat->setInt32(
1351 KEY_MAX_INPUT_SIZE,
1352 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1353 }
1354 }
1355
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001356 int32_t clientPrepend;
1357 if ((config->mDomain & Config::IS_VIDEO)
1358 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001359 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001360 && clientPrepend
1361 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001362 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001363 return BAD_VALUE;
1364 }
1365
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001366 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001367 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1368 // propagate HDR static info to output format for both encoders and decoders
1369 // if component supports this info, we will update from component, but only the raw port,
1370 // so don't propagate if component already filled it in.
1371 sp<ABuffer> hdrInfo;
1372 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1373 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1374 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1375 }
1376
1377 // Set desired color format from configuration parameter
1378 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001379 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1380 format = defaultColorFormat;
1381 }
1382 if (config->mDomain & Config::IS_ENCODER) {
1383 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001384 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1385 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001386 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001387 } else {
1388 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001389 }
1390 }
1391
1392 // propagate encoder delay and padding to output format
1393 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1394 int delay = 0;
1395 if (msg->findInt32("encoder-delay", &delay)) {
1396 config->mOutputFormat->setInt32("encoder-delay", delay);
1397 }
1398 int padding = 0;
1399 if (msg->findInt32("encoder-padding", &padding)) {
1400 config->mOutputFormat->setInt32("encoder-padding", padding);
1401 }
1402 }
1403
Pawin Vongmasa36653902018-11-15 00:10:25 -08001404 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001405 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001406 int32_t mask;
1407 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1408 if (config->mDomain & Config::IS_ENCODER) {
1409 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1410 } else {
1411 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1412 }
1413 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001414
1415 // set PCM encoding
1416 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1417 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1418 if (encoder) {
1419 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1420 } else {
1421 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1422 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001423 }
1424
Wonsik Kim3baecda2021-02-07 22:19:56 -08001425 std::unique_ptr<C2Param> colorTransferRequestParam;
1426 for (std::unique_ptr<C2Param> &param : params) {
1427 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1428 ALOGI("found color transfer request param");
1429 colorTransferRequestParam = std::move(param);
1430 }
1431 }
Wonsik Kim3baecda2021-02-07 22:19:56 -08001432
1433 if (colorTransferRequest != 0) {
1434 if (colorTransferRequestParam && *colorTransferRequestParam) {
1435 C2StreamColorAspectsInfo::output *info =
1436 static_cast<C2StreamColorAspectsInfo::output *>(
1437 colorTransferRequestParam.get());
1438 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1439 colorTransferRequest = 0;
1440 }
1441 } else {
1442 colorTransferRequest = 0;
1443 }
1444 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1445 }
1446
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001447 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1448 // Need to get stride/vstride
1449 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1450 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1451 // TODO: retrieve these values without allocating a buffer.
1452 // Currently allocating a buffer is necessary to retrieve the layout.
1453 int64_t blockUsage =
1454 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1455 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
Taehwan Kim2772e1c2022-03-31 17:15:08 +09001456 width, height, componentColorFormat, blockUsage, {comp->getName()});
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001457 sp<GraphicBlockBuffer> buffer;
1458 if (block) {
1459 buffer = GraphicBlockBuffer::Allocate(
1460 config->mInputFormat,
1461 block,
1462 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1463 } else {
1464 ALOGD("Failed to allocate a graphic block "
1465 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1466 width, height, pixelFormat, (long long)blockUsage);
1467 // This means that byte buffer mode is not supported in this configuration
1468 // anyway. Skip setting stride/vstride to input format.
1469 }
1470 if (buffer) {
1471 sp<ABuffer> imageData = buffer->getImageData();
1472 MediaImage2 *img = nullptr;
1473 if (imageData && imageData->data()
1474 && imageData->size() >= sizeof(MediaImage2)) {
1475 img = (MediaImage2*)imageData->data();
1476 }
1477 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1478 int32_t stride = img->mPlane[0].mRowInc;
1479 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1480 if (img->mNumPlanes > 1 && stride > 0) {
1481 int64_t offsetDelta =
1482 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1483 if (offsetDelta % stride == 0) {
1484 int32_t vstride = int32_t(offsetDelta / stride);
1485 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1486 } else {
1487 ALOGD("Cannot report accurate slice height: "
1488 "offsetDelta = %lld stride = %d",
1489 (long long)offsetDelta, stride);
1490 }
1491 }
1492 }
1493 }
1494 }
1495 }
1496
Wonsik Kimec585c32021-10-01 01:11:00 -07001497 if (config->mTunneled) {
1498 config->mOutputFormat->setInt32("android._tunneled", 1);
1499 }
1500
Yushin Cho91873b52021-12-21 04:08:35 -08001501 // Convert an encoding statistics level to corresponding encoding statistics
1502 // kinds
1503 int32_t encodingStatisticsLevel = VIDEO_ENCODING_STATISTICS_LEVEL_NONE;
1504 if ((config->mDomain & Config::IS_ENCODER)
1505 && (config->mDomain & Config::IS_VIDEO)
1506 && msg->findInt32(KEY_VIDEO_ENCODING_STATISTICS_LEVEL, &encodingStatisticsLevel)) {
1507 // Higher level include all the enc stats belong to lower level.
1508 switch (encodingStatisticsLevel) {
1509 // case VIDEO_ENCODING_STATISTICS_LEVEL_2: // reserved for the future level 2
1510 // with more enc stat kinds
1511 // Future extended encoding statistics for the level 2 should be added here
1512 case VIDEO_ENCODING_STATISTICS_LEVEL_1:
Wonsik Kimeebab652022-06-02 13:01:55 -07001513 config->subscribeToConfigUpdate(
1514 comp,
1515 {
1516 C2AndroidStreamAverageBlockQuantizationInfo::output::PARAM_TYPE,
1517 C2StreamPictureTypeInfo::output::PARAM_TYPE,
1518 });
Yushin Cho91873b52021-12-21 04:08:35 -08001519 break;
1520 case VIDEO_ENCODING_STATISTICS_LEVEL_NONE:
1521 break;
1522 }
1523 }
1524 ALOGD("encoding statistics level = %d", encodingStatisticsLevel);
1525
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001526 ALOGD("setup formats input: %s",
1527 config->mInputFormat->debugString().c_str());
1528 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001529 config->mOutputFormat->debugString().c_str());
1530 return OK;
1531 };
1532 if (tryAndReportOnError(doConfig) != OK) {
1533 return;
1534 }
1535
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001536 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1537 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001538
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001539 config->queryConfiguration(comp);
1540
Pawin Vongmasa36653902018-11-15 00:10:25 -08001541 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1542}
1543
1544void CCodec::initiateCreateInputSurface() {
1545 status_t err = [this] {
1546 Mutexed<State>::Locked state(mState);
1547 if (state->get() != ALLOCATED) {
1548 return UNKNOWN_ERROR;
1549 }
1550 // TODO: read it from intf() properly.
1551 if (state->comp->getName().find("encoder") == std::string::npos) {
1552 return INVALID_OPERATION;
1553 }
1554 return OK;
1555 }();
1556 if (err != OK) {
1557 mCallback->onInputSurfaceCreationFailed(err);
1558 return;
1559 }
1560
1561 (new AMessage(kWhatCreateInputSurface, this))->post();
1562}
1563
Lajos Molnar47118272019-01-31 16:28:04 -08001564sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1565 using namespace android::hardware::media::omx::V1_0;
1566 using namespace android::hardware::media::omx::V1_0::utils;
1567 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1568 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1569 android::sp<IOmx> omx = IOmx::getService();
Sungtak Lee47dcb482022-04-15 10:47:08 -07001570 if (omx == nullptr) {
1571 return nullptr;
1572 }
Lajos Molnar47118272019-01-31 16:28:04 -08001573 typedef android::hardware::graphics::bufferqueue::V1_0::
1574 IGraphicBufferProducer HGraphicBufferProducer;
1575 typedef android::hardware::media::omx::V1_0::
1576 IGraphicBufferSource HGraphicBufferSource;
1577 OmxStatus s;
1578 android::sp<HGraphicBufferProducer> gbp;
1579 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001580
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001581 using ::android::hardware::Return;
1582 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001583 [&s, &gbp, &gbs](
1584 OmxStatus status,
1585 const android::sp<HGraphicBufferProducer>& producer,
1586 const android::sp<HGraphicBufferSource>& source) {
1587 s = status;
1588 gbp = producer;
1589 gbs = source;
1590 });
1591 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001592 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001593 }
1594
1595 return nullptr;
1596}
1597
1598sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1599 sp<PersistentSurface> surface(CreateInputSurface());
1600
1601 if (surface == nullptr) {
1602 surface = CreateOmxInputSurface();
1603 }
1604
1605 return surface;
1606}
1607
Pawin Vongmasa36653902018-11-15 00:10:25 -08001608void CCodec::createInputSurface() {
1609 status_t err;
1610 sp<IGraphicBufferProducer> bufferProducer;
1611
Pawin Vongmasa36653902018-11-15 00:10:25 -08001612 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001613 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001614 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001615 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1616 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001617 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001618 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001619 }
1620
Lajos Molnar47118272019-01-31 16:28:04 -08001621 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001622 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1623 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1624 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001625
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001626 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001627 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1628 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001629 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001630 inputSurface));
1631 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001632 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001633 int32_t width = 0;
1634 (void)outputFormat->findInt32("width", &width);
1635 int32_t height = 0;
1636 (void)outputFormat->findInt32("height", &height);
1637 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001638 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001639 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001640 } else {
1641 ALOGE("Corrupted input surface");
1642 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1643 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001644 }
1645
1646 if (err != OK) {
1647 ALOGE("Failed to set up input surface: %d", err);
1648 mCallback->onInputSurfaceCreationFailed(err);
1649 return;
1650 }
1651
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001652 // Formats can change after setupInputSurface
1653 sp<AMessage> inputFormat;
1654 {
1655 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1656 const std::unique_ptr<Config> &config = *configLocked;
1657 inputFormat = config->mInputFormat;
1658 outputFormat = config->mOutputFormat;
1659 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001660 mCallback->onInputSurfaceCreated(
1661 inputFormat,
1662 outputFormat,
1663 new BufferProducerWrapper(bufferProducer));
1664}
1665
1666status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001667 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1668 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001669 config->mUsingSurface = true;
1670
1671 // we are now using surface - apply default color aspects to input format - as well as
1672 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001673 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001674
1675 // configure dataspace
1676 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
Wonsik Kim66b19552021-08-02 16:07:49 -07001677
1678 // The output format contains app-configured color aspects, and the input format
1679 // has the default color aspects. Use the default for the unspecified params.
1680 ColorAspects inputColorAspects, colorAspects;
1681 getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
1682 getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
1683 if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
1684 colorAspects.mRange = inputColorAspects.mRange;
1685 }
1686 if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
1687 colorAspects.mPrimaries = inputColorAspects.mPrimaries;
1688 }
1689 if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
1690 colorAspects.mTransfer = inputColorAspects.mTransfer;
1691 }
1692 if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
1693 colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
1694 }
1695 android_dataspace dataSpace = getDataSpaceForColorAspects(
1696 colorAspects, /* mayExtend = */ false);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001697 surface->setDataSpace(dataSpace);
Wonsik Kim66b19552021-08-02 16:07:49 -07001698 setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
1699 config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
1700
1701 ALOGD("input format %s to %s",
1702 inputFormatChanged ? "changed" : "unchanged",
1703 config->mInputFormat->debugString().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001704
1705 status_t err = mChannel->setInputSurface(surface);
1706 if (err != OK) {
1707 // undo input format update
1708 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001709 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001710 return err;
1711 }
1712 config->mInputSurface = surface;
1713
1714 if (config->mISConfig) {
1715 surface->configure(*config->mISConfig);
1716 } else {
1717 ALOGD("ISConfig: no configuration");
1718 }
1719
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001720 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001721}
1722
1723void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1724 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1725 msg->setObject("surface", surface);
1726 msg->post();
1727}
1728
1729void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001730 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001731 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001732 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001733 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1734 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001735 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001736 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001737 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001738 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1739 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1740 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1741 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001742 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1743 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1744 if (err != OK) {
1745 ALOGE("Failed to set up input surface: %d", err);
1746 mCallback->onInputSurfaceDeclined(err);
1747 return;
1748 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001749 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001750 int32_t width = 0;
1751 (void)outputFormat->findInt32("width", &width);
1752 int32_t height = 0;
1753 (void)outputFormat->findInt32("height", &height);
1754 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001755 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001756 if (err != OK) {
1757 ALOGE("Failed to set up input surface: %d", err);
1758 mCallback->onInputSurfaceDeclined(err);
1759 return;
1760 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001761 } else {
1762 ALOGE("Failed to set input surface: Corrupted surface.");
1763 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1764 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001765 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001766 // Formats can change after setupInputSurface
1767 sp<AMessage> inputFormat;
1768 {
1769 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1770 const std::unique_ptr<Config> &config = *configLocked;
1771 inputFormat = config->mInputFormat;
1772 outputFormat = config->mOutputFormat;
1773 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001774 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1775}
1776
1777void CCodec::initiateStart() {
1778 auto setStarting = [this] {
1779 Mutexed<State>::Locked state(mState);
1780 if (state->get() != ALLOCATED) {
1781 return UNKNOWN_ERROR;
1782 }
1783 state->set(STARTING);
1784 return OK;
1785 };
1786 if (tryAndReportOnError(setStarting) != OK) {
1787 return;
1788 }
1789
1790 (new AMessage(kWhatStart, this))->post();
1791}
1792
1793void CCodec::start() {
1794 std::shared_ptr<Codec2Client::Component> comp;
1795 auto checkStarting = [this, &comp] {
1796 Mutexed<State>::Locked state(mState);
1797 if (state->get() != STARTING) {
1798 return UNKNOWN_ERROR;
1799 }
1800 comp = state->comp;
1801 return OK;
1802 };
1803 if (tryAndReportOnError(checkStarting) != OK) {
1804 return;
1805 }
1806
1807 c2_status_t err = comp->start();
1808 if (err != C2_OK) {
1809 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1810 ACTION_CODE_FATAL);
1811 return;
1812 }
Wonsik Kimd86c96b2023-06-22 14:42:17 -07001813
1814 // clear the deadline after the component starts
1815 setDeadline(TimePoint::max(), 0ms, "none");
1816
Pawin Vongmasa36653902018-11-15 00:10:25 -08001817 sp<AMessage> inputFormat;
1818 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001819 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001820 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001821 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001822 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1823 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001824 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001825 // start triggers format dup
1826 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001827 if (config->mInputSurface) {
1828 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001829 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001830 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001831 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001832 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001833 if (err2 != OK) {
1834 mCallback->onError(err2, ACTION_CODE_FATAL);
1835 return;
1836 }
Arun Johnson106fe7a2023-04-26 17:49:43 +00001837
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001838 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001839 if (err2 != OK) {
1840 mCallback->onError(err2, ACTION_CODE_FATAL);
1841 return;
1842 }
1843
1844 auto setRunning = [this] {
1845 Mutexed<State>::Locked state(mState);
1846 if (state->get() != STARTING) {
1847 return UNKNOWN_ERROR;
1848 }
1849 state->set(RUNNING);
1850 return OK;
1851 };
1852 if (tryAndReportOnError(setRunning) != OK) {
1853 return;
1854 }
Arun Johnson5997bb02022-04-01 19:35:44 +00001855
Wonsik Kim34b28b42022-05-20 15:49:32 -07001856 // preparation of input buffers may not succeed due to the lack of
1857 // memory; returning correct error code (NO_MEMORY) as an error allows
1858 // MediaCodec to try reclaim and restart codec gracefully.
1859 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
1860 err2 = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
1861 if (err2 != OK) {
1862 ALOGE("Initial preparation for Input Buffers failed");
1863 mCallback->onError(err2, ACTION_CODE_FATAL);
1864 return;
1865 }
1866
Pawin Vongmasa36653902018-11-15 00:10:25 -08001867 mCallback->onStartCompleted();
1868
Wonsik Kim34b28b42022-05-20 15:49:32 -07001869 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001870}
1871
1872void CCodec::initiateShutdown(bool keepComponentAllocated) {
1873 if (keepComponentAllocated) {
1874 initiateStop();
1875 } else {
1876 initiateRelease();
1877 }
1878}
1879
1880void CCodec::initiateStop() {
1881 {
1882 Mutexed<State>::Locked state(mState);
1883 if (state->get() == ALLOCATED
1884 || state->get() == RELEASED
1885 || state->get() == STOPPING
1886 || state->get() == RELEASING) {
1887 // We're already stopped, released, or doing it right now.
1888 state.unlock();
1889 mCallback->onStopCompleted();
1890 state.lock();
1891 return;
1892 }
1893 state->set(STOPPING);
1894 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001895 mChannel->reset();
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001896 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
1897 sp<AMessage> stopMessage(new AMessage(kWhatStop, this));
1898 stopMessage->setInt32("pushBlankBuffer", pushBlankBuffer);
1899 stopMessage->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001900}
1901
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001902void CCodec::stop(bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001903 std::shared_ptr<Codec2Client::Component> comp;
1904 {
1905 Mutexed<State>::Locked state(mState);
1906 if (state->get() == RELEASING) {
1907 state.unlock();
1908 // We're already stopped or release is in progress.
1909 mCallback->onStopCompleted();
1910 state.lock();
1911 return;
1912 } else if (state->get() != STOPPING) {
1913 state.unlock();
1914 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1915 state.lock();
1916 return;
1917 }
1918 comp = state->comp;
1919 }
Sungtak Leec0c05962023-10-25 08:14:13 +00001920
1921 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->stop().
1922 // But in the case some HAL implementations hang forever on comp->stop().
1923 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
1924 // completing stop()).
1925 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
1926 // prior to comp->stop().
1927 // See also b/300350761.
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001928 mChannel->stopUseOutputSurface(pushBlankBuffer);
Sungtak Leec0c05962023-10-25 08:14:13 +00001929 status_t err = comp->stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001930 if (err != C2_OK) {
1931 // TODO: convert err into status_t
1932 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1933 }
1934
1935 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001936 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1937 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001938 if (config->mInputSurface) {
1939 config->mInputSurface->disconnect();
1940 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001941 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001942 }
1943 }
1944 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001945 Mutexed<State>::Locked state(mState);
1946 if (state->get() == STOPPING) {
1947 state->set(ALLOCATED);
1948 }
1949 }
1950 mCallback->onStopCompleted();
1951}
1952
1953void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001954 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001955 {
1956 Mutexed<State>::Locked state(mState);
1957 if (state->get() == RELEASED || state->get() == RELEASING) {
1958 // We're already released or doing it right now.
1959 if (sendCallback) {
1960 state.unlock();
1961 mCallback->onReleaseCompleted();
1962 state.lock();
1963 }
1964 return;
1965 }
1966 if (state->get() == ALLOCATING) {
1967 state->set(RELEASING);
1968 // With the altered state allocate() would fail and clean up.
1969 if (sendCallback) {
1970 state.unlock();
1971 mCallback->onReleaseCompleted();
1972 state.lock();
1973 }
1974 return;
1975 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001976 if (state->get() == STARTING
1977 || state->get() == RUNNING
1978 || state->get() == STOPPING) {
1979 // Input surface may have been started, so clean up is needed.
1980 clearInputSurfaceIfNeeded = true;
1981 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001982 state->set(RELEASING);
1983 }
1984
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001985 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001986 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1987 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001988 if (config->mInputSurface) {
1989 config->mInputSurface->disconnect();
1990 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001991 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001992 }
1993 }
1994
Wonsik Kim936a89c2020-05-08 16:07:50 -07001995 mChannel->reset();
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001996 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001997 // thiz holds strong ref to this while the thread is running.
1998 sp<CCodec> thiz(this);
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00001999 std::thread([thiz, sendCallback, pushBlankBuffer]
2000 { thiz->release(sendCallback, pushBlankBuffer); }).detach();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002001}
2002
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002003void CCodec::release(bool sendCallback, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002004 std::shared_ptr<Codec2Client::Component> comp;
2005 {
2006 Mutexed<State>::Locked state(mState);
2007 if (state->get() == RELEASED) {
2008 if (sendCallback) {
2009 state.unlock();
2010 mCallback->onReleaseCompleted();
2011 state.lock();
2012 }
2013 return;
2014 }
2015 comp = state->comp;
2016 }
Sungtak Leec0c05962023-10-25 08:14:13 +00002017 // Note: Logically mChannel->stopUseOutputSurface() should be after comp->release().
2018 // But in the case some HAL implementations hang forever on comp->release().
2019 // (HAL is waiting for C2Fence until fetchGraphicBlock unblocks and not
2020 // completing release()).
2021 // So we reverse their order for stopUseOutputSurface() to notify C2Fence waiters
2022 // prior to comp->release().
2023 // See also b/300350761.
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002024 mChannel->stopUseOutputSurface(pushBlankBuffer);
Sungtak Leec0c05962023-10-25 08:14:13 +00002025 comp->release();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002026
2027 {
2028 Mutexed<State>::Locked state(mState);
2029 state->set(RELEASED);
2030 state->comp.reset();
2031 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002032 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002033 if (sendCallback) {
2034 mCallback->onReleaseCompleted();
2035 }
2036}
2037
Sungtak Lee214ce612023-11-01 10:01:13 +00002038status_t CCodec::setSurface(const sp<Surface> &surface, uint32_t generation) {
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002039 bool pushBlankBuffer = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002040 {
2041 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2042 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002043 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
2044 status_t err = OK;
2045
Wonsik Kim75e22f42021-04-14 23:34:51 -07002046 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002047 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07002048 nativeWindow.get(),
2049 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
2050 if (err != OK) {
2051 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
2052 nativeWindow.get(), config->mSidebandHandle->handle(), err);
2053 return err;
2054 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002055 } else {
2056 // Explicitly reset the sideband handle of the window for
2057 // non-tunneled video in case the window was previously used
2058 // for a tunneled video playback.
2059 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
2060 if (err != OK) {
2061 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
2062 return err;
2063 }
ted.sun765db4d2020-06-23 14:03:41 +08002064 }
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002065 pushBlankBuffer = config->mPushBlankBuffersOnStop;
ted.sun765db4d2020-06-23 14:03:41 +08002066 }
Sungtak Lee214ce612023-11-01 10:01:13 +00002067 return mChannel->setSurface(surface, generation, pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002068}
2069
2070void CCodec::signalFlush() {
2071 status_t err = [this] {
2072 Mutexed<State>::Locked state(mState);
2073 if (state->get() == FLUSHED) {
2074 return ALREADY_EXISTS;
2075 }
2076 if (state->get() != RUNNING) {
2077 return UNKNOWN_ERROR;
2078 }
2079 state->set(FLUSHING);
2080 return OK;
2081 }();
2082 switch (err) {
2083 case ALREADY_EXISTS:
2084 mCallback->onFlushCompleted();
2085 return;
2086 case OK:
2087 break;
2088 default:
2089 mCallback->onError(err, ACTION_CODE_FATAL);
2090 return;
2091 }
2092
2093 mChannel->stop();
2094 (new AMessage(kWhatFlush, this))->post();
2095}
2096
2097void CCodec::flush() {
2098 std::shared_ptr<Codec2Client::Component> comp;
2099 auto checkFlushing = [this, &comp] {
2100 Mutexed<State>::Locked state(mState);
2101 if (state->get() != FLUSHING) {
2102 return UNKNOWN_ERROR;
2103 }
2104 comp = state->comp;
2105 return OK;
2106 };
2107 if (tryAndReportOnError(checkFlushing) != OK) {
2108 return;
2109 }
2110
2111 std::list<std::unique_ptr<C2Work>> flushedWork;
2112 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2113 {
2114 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2115 flushedWork.splice(flushedWork.end(), *queue);
2116 }
2117 if (err != C2_OK) {
2118 // TODO: convert err into status_t
2119 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2120 }
2121
2122 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002123
2124 {
2125 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002126 if (state->get() == FLUSHING) {
2127 state->set(FLUSHED);
2128 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002129 }
2130 mCallback->onFlushCompleted();
2131}
2132
2133void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002134 std::shared_ptr<Codec2Client::Component> comp;
2135 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002136 Mutexed<State>::Locked state(mState);
2137 if (state->get() != FLUSHED) {
2138 return UNKNOWN_ERROR;
2139 }
2140 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002141 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002142 return OK;
2143 };
2144 if (tryAndReportOnError(setResuming) != OK) {
2145 return;
2146 }
2147
Wonsik Kime75a5da2020-02-14 17:29:03 -08002148 {
2149 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2150 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002151 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002152 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002153 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002154 }
2155
Arun Johnson106fe7a2023-04-26 17:49:43 +00002156 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
2157 status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
2158 if (err != OK) {
2159 if (err == NO_MEMORY) {
2160 // NO_MEMORY happens here when all the buffers are still
2161 // with the codec. That is not an error as it is momentarily
2162 // and the buffers are send to the client as soon as the codec
2163 // releases them
2164 ALOGI("Resuming with all input buffers still with codec");
2165 } else {
2166 ALOGE("Resume request for Input Buffers failed");
2167 mCallback->onError(err, ACTION_CODE_FATAL);
2168 return;
2169 }
2170 }
2171
2172 // channel start should be called after prepareInitialBuffers
2173 // Calling before can cause a failure during prepare when
2174 // buffers are sent to the client before preparation from onWorkDone
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002175 (void)mChannel->start(nullptr, nullptr, [&]{
2176 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2177 const std::unique_ptr<Config> &config = *configLocked;
2178 return config->mBuffersBoundToCodec;
2179 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002180
2181 {
2182 Mutexed<State>::Locked state(mState);
2183 if (state->get() != RESUMING) {
2184 state.unlock();
2185 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2186 state.lock();
2187 return;
2188 }
2189 state->set(RUNNING);
2190 }
2191
Wonsik Kim34b28b42022-05-20 15:49:32 -07002192 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002193}
2194
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002195void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002196 std::shared_ptr<Codec2Client::Component> comp;
2197 auto checkState = [this, &comp] {
2198 Mutexed<State>::Locked state(mState);
2199 if (state->get() == RELEASED) {
2200 return INVALID_OPERATION;
2201 }
2202 comp = state->comp;
2203 return OK;
2204 };
2205 if (tryAndReportOnError(checkState) != OK) {
2206 return;
2207 }
2208
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002209 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2210 // the behavior here.
2211 sp<AMessage> params = msg;
2212 int32_t bitrate;
2213 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2214 params = msg->dup();
2215 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2216 }
2217
Houxiang Dai5a97b472021-03-22 17:56:04 +08002218 int32_t syncId = 0;
2219 if (params->findInt32("audio-hw-sync", &syncId)
2220 || params->findInt32("hw-av-sync-id", &syncId)) {
2221 configureTunneledVideoPlayback(comp, nullptr, params);
2222 }
2223
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002224 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2225 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002226
2227 /**
2228 * Handle input surface parameters
2229 */
2230 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002231 && (config->mDomain & Config::IS_ENCODER)
2232 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002233 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002234
2235 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2236 config->mISConfig->mStopped = false;
2237 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2238 config->mISConfig->mStopped = true;
2239 }
2240
2241 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002242 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002243 config->mISConfig->mSuspended = value;
2244 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002245 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002246 }
2247
2248 (void)config->mInputSurface->configure(*config->mISConfig);
2249 if (config->mISConfig->mStopped) {
2250 config->mInputFormat->setInt64(
2251 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2252 }
2253 }
2254
2255 std::vector<std::unique_ptr<C2Param>> configUpdate;
2256 (void)config->getConfigUpdateFromSdkParams(
2257 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2258 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2259 // Parameter synchronization is not defined when using input surface. For now, route
2260 // these directly to the component.
2261 if (config->mInputSurface == nullptr
2262 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2263 || comp->getName().find("c2.android.") == 0)) {
2264 mChannel->setParameters(configUpdate);
2265 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002266 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002267 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002268 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002269 }
2270}
2271
2272void CCodec::signalEndOfInputStream() {
2273 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2274}
2275
2276void CCodec::signalRequestIDRFrame() {
2277 std::shared_ptr<Codec2Client::Component> comp;
2278 {
2279 Mutexed<State>::Locked state(mState);
2280 if (state->get() == RELEASED) {
2281 ALOGD("no IDR request sent since component is released");
2282 return;
2283 }
2284 comp = state->comp;
2285 }
2286 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002287 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2288 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002289 std::vector<std::unique_ptr<C2Param>> params;
2290 params.push_back(
2291 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2292 config->setParameters(comp, params, C2_MAY_BLOCK);
2293}
2294
Wonsik Kim874ad382021-03-12 09:59:36 -08002295status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2296 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2297 const std::unique_ptr<Config> &config = *configLocked;
2298 return config->querySupportedParameters(names);
2299}
2300
2301status_t CCodec::describeParameter(
2302 const std::string &name, CodecParameterDescriptor *desc) {
2303 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2304 const std::unique_ptr<Config> &config = *configLocked;
2305 return config->describe(name, desc);
2306}
2307
2308status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2309 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2310 if (!comp) {
2311 return INVALID_OPERATION;
2312 }
2313 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2314 const std::unique_ptr<Config> &config = *configLocked;
2315 return config->subscribeToVendorConfigUpdate(comp, names);
2316}
2317
2318status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2319 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2320 if (!comp) {
2321 return INVALID_OPERATION;
2322 }
2323 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2324 const std::unique_ptr<Config> &config = *configLocked;
2325 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2326}
2327
Wonsik Kimab34ed62019-01-31 15:28:46 -08002328void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002329 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002330 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002331 bool shouldPost = queue->empty();
Wonsik Kimab34ed62019-01-31 15:28:46 -08002332 queue->splice(queue->end(), workItems);
Houxiang Dai21e571f2022-05-09 21:35:39 +08002333 if (shouldPost) {
2334 (new AMessage(kWhatWorkDone, this))->post();
2335 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002336 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002337}
2338
Wonsik Kimab34ed62019-01-31 15:28:46 -08002339void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2340 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002341 if (arrayIndex == 0) {
2342 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002343 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2344 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002345 if (config->mInputSurface) {
2346 config->mInputSurface->onInputBufferDone(frameIndex);
2347 }
2348 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002349}
2350
2351void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2352 TimePoint now = std::chrono::steady_clock::now();
2353 CCodecWatchdog::getInstance()->watch(this);
2354 switch (msg->what()) {
2355 case kWhatAllocate: {
2356 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002357 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002358 sp<RefBase> obj;
2359 CHECK(msg->findObject("codecInfo", &obj));
2360 allocate((MediaCodecInfo *)obj.get());
2361 break;
2362 }
2363 case kWhatConfigure: {
2364 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002365 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002366 sp<AMessage> format;
2367 CHECK(msg->findMessage("format", &format));
2368 configure(format);
2369 break;
2370 }
2371 case kWhatStart: {
2372 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002373 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002374 start();
2375 break;
2376 }
2377 case kWhatStop: {
2378 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002379 setDeadline(now, 1500ms, "stop");
Sungtak Lee80c8e1e2023-01-26 11:03:14 +00002380 int32_t pushBlankBuffer;
2381 if (!msg->findInt32("pushBlankBuffer", &pushBlankBuffer)) {
2382 pushBlankBuffer = 0;
2383 }
2384 stop(static_cast<bool>(pushBlankBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002385 break;
2386 }
2387 case kWhatFlush: {
2388 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002389 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002390 flush();
2391 break;
2392 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002393 case kWhatRelease: {
2394 mChannel->release();
2395 mClient.reset();
2396 mClientListener.reset();
2397 break;
2398 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002399 case kWhatCreateInputSurface: {
2400 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002401 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002402 createInputSurface();
2403 break;
2404 }
2405 case kWhatSetInputSurface: {
2406 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002407 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002408 sp<RefBase> obj;
2409 CHECK(msg->findObject("surface", &obj));
2410 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2411 setInputSurface(surface);
2412 break;
2413 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002414 case kWhatWorkDone: {
2415 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002416 bool shouldPost = false;
2417 {
2418 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2419 if (queue->empty()) {
2420 break;
2421 }
2422 work.swap(queue->front());
2423 queue->pop_front();
2424 shouldPost = !queue->empty();
2425 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002426 if (shouldPost) {
2427 (new AMessage(kWhatWorkDone, this))->post();
2428 }
2429
Pawin Vongmasa36653902018-11-15 00:10:25 -08002430 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002431 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002432 sp<AMessage> outputFormat = nullptr;
2433 {
2434 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2435 const std::unique_ptr<Config> &config = *configLocked;
2436 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2437 config->watch<C2StreamInitDataInfo::output>();
2438 if (!work->worklets.empty()
2439 && (work->worklets.front()->output.flags
2440 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002441
Wonsik Kim75e22f42021-04-14 23:34:51 -07002442 // copy buffer info to config
2443 std::vector<std::unique_ptr<C2Param>> updates;
2444 for (const std::unique_ptr<C2Param> &param
2445 : work->worklets.front()->output.configUpdate) {
2446 updates.push_back(C2Param::Copy(*param));
2447 }
2448 unsigned stream = 0;
2449 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2450 work->worklets.front()->output.buffers;
2451 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2452 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2453 // move all info into output-stream #0 domain
2454 updates.emplace_back(
2455 C2Param::CopyAsStream(*info, true /* output */, stream));
2456 }
2457
2458 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2459 // for now only do the first block
2460 if (!blocks.empty()) {
2461 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2462 // block.crop().left, block.crop().top,
2463 // block.crop().width, block.crop().height,
2464 // block.width(), block.height());
2465 const C2ConstGraphicBlock &block = blocks[0];
2466 updates.emplace_back(new C2StreamCropRectInfo::output(
2467 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002468 }
2469 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002470 }
George Burgess IVc813a592020-02-22 22:54:44 -08002471
Wonsik Kim75e22f42021-04-14 23:34:51 -07002472 sp<AMessage> oldFormat = config->mOutputFormat;
2473 config->updateConfiguration(updates, config->mOutputDomain);
2474 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002475
Wonsik Kim75e22f42021-04-14 23:34:51 -07002476 // copy standard infos to graphic buffers if not already present (otherwise, we
2477 // may overwrite the actual intermediate value with a final value)
2478 stream = 0;
2479 const static C2Param::Index stdGfxInfos[] = {
2480 C2StreamRotationInfo::output::PARAM_TYPE,
2481 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2482 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2483 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Taehwan Kim2d222b82022-05-12 14:19:26 +09002484 C2StreamHdr10PlusInfo::output::PARAM_TYPE, // will be deprecated
2485 C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE,
Wonsik Kim75e22f42021-04-14 23:34:51 -07002486 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2487 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2488 };
2489 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2490 if (buf->data().graphicBlocks().size()) {
2491 for (C2Param::Index ix : stdGfxInfos) {
2492 if (!buf->hasInfo(ix)) {
2493 const C2Param *param =
2494 config->getConfigParameterValue(ix.withStream(stream));
2495 if (param) {
2496 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2497 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2498 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002499 }
2500 }
2501 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002502 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002503 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002504 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002505 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302506 if (work->worklets.empty()
2507 || !work->worklets.back()
2508 || (work->worklets.back()->output.flags
2509 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2510 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2511 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002512 }
2513 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002514 initData = initDataWatcher.update();
2515 AmendOutputFormatWithCodecSpecificData(
2516 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2517 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002518 }
2519 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002520 }
2521 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002522 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002523 break;
2524 }
2525 case kWhatWatch: {
2526 // watch message already posted; no-op.
2527 break;
2528 }
2529 default: {
2530 ALOGE("unrecognized message");
2531 break;
2532 }
2533 }
2534 setDeadline(TimePoint::max(), 0ms, "none");
2535}
2536
2537void CCodec::setDeadline(
2538 const TimePoint &now,
2539 const std::chrono::milliseconds &timeout,
2540 const char *name) {
2541 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2542 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2543 deadline->set(now + (timeout * mult), name);
2544}
2545
ted.sun765db4d2020-06-23 14:03:41 +08002546status_t CCodec::configureTunneledVideoPlayback(
2547 std::shared_ptr<Codec2Client::Component> comp,
2548 sp<NativeHandle> *sidebandHandle,
2549 const sp<AMessage> &msg) {
2550 std::vector<std::unique_ptr<C2SettingResult>> failures;
2551
2552 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2553 C2PortTunneledModeTuning::output::AllocUnique(
2554 1,
2555 C2PortTunneledModeTuning::Struct::SIDEBAND,
2556 C2PortTunneledModeTuning::Struct::REALTIME,
2557 0);
2558 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2559 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2560 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2561 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2562 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2563 } else {
2564 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2565 tunneledPlayback->setFlexCount(0);
2566 }
2567 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2568 if (c2err != C2_OK) {
2569 return UNKNOWN_ERROR;
2570 }
2571
Houxiang Dai5a97b472021-03-22 17:56:04 +08002572 if (sidebandHandle == nullptr) {
2573 return OK;
2574 }
2575
ted.sun765db4d2020-06-23 14:03:41 +08002576 std::vector<std::unique_ptr<C2Param>> params;
2577 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2578 if (c2err == C2_OK && params.size() == 1u) {
2579 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2580 C2PortTunnelHandleTuning::output::From(params[0].get());
2581 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2582 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2583 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2584 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2585 memcpy(handle->data, videoTunnelSideband->m.values,
2586 sizeof(int32_t) * videoTunnelSideband->flexCount());
2587 return OK;
2588 } else {
2589 return NO_MEMORY;
2590 }
2591 }
2592 return UNKNOWN_ERROR;
2593}
2594
Pawin Vongmasa36653902018-11-15 00:10:25 -08002595void CCodec::initiateReleaseIfStuck() {
Shrikara B3b87a532022-08-26 14:18:14 +05302596 std::string name;
2597 bool pendingDeadline = false;
2598 {
2599 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2600 if (deadline->get() < std::chrono::steady_clock::now()) {
2601 name = deadline->getName();
2602 }
2603 if (deadline->get() != TimePoint::max()) {
2604 pendingDeadline = true;
2605 }
2606 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002607 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002608 // We're not stuck.
2609 if (pendingDeadline) {
2610 // If we are not stuck yet but still has deadline coming up,
2611 // post watch message to check back later.
2612 (new AMessage(kWhatWatch, this))->post();
2613 }
2614 return;
2615 }
2616
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002617 C2String compName;
2618 {
2619 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002620 if (!state->comp) {
2621 ALOGD("previous call to %s exceeded timeout "
2622 "and the component is already released", name.c_str());
2623 return;
2624 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002625 compName = state->comp->getName();
2626 }
2627 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2628
Pawin Vongmasa36653902018-11-15 00:10:25 -08002629 initiateRelease(false);
2630 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2631}
2632
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002633// static
2634PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002635 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002636 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002637 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002638 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2639 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002640 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002641 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2642 sp<IGraphicBufferProducer> gbp;
2643 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2644 status_t err = gbs->initCheck();
2645 if (err != OK) {
2646 ALOGE("Failed to create persistent input surface: error %d", err);
2647 return nullptr;
2648 }
2649 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002650 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002651 } else {
2652 return nullptr;
2653 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002654 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002655 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002656 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002657 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002658 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002659}
2660
Wonsik Kimffb889a2020-05-28 11:32:25 -07002661class IntfCache {
2662public:
2663 IntfCache() = default;
2664
2665 status_t init(const std::string &name) {
2666 std::shared_ptr<Codec2Client::Interface> intf{
2667 Codec2Client::CreateInterfaceByName(name.c_str())};
2668 if (!intf) {
2669 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2670 mInitStatus = NO_INIT;
2671 return NO_INIT;
2672 }
2673 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2674 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2675 C2ParamField{&sUsage, &sUsage.value}));
2676 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2677 if (err != C2_OK) {
2678 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2679 name.c_str(), err);
2680 mFields[0].status = err;
2681 }
2682 std::vector<std::unique_ptr<C2Param>> params;
2683 err = intf->query(
2684 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09002685 {
2686 C2StreamBufferTypeSetting::input::PARAM_TYPE,
2687 C2PortAllocatorsTuning::input::PARAM_TYPE
2688 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07002689 C2_MAY_BLOCK,
2690 &params);
2691 if (err != C2_OK && err != C2_BAD_INDEX) {
2692 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2693 name.c_str(), err);
2694 }
2695 while (!params.empty()) {
2696 C2Param *param = params.back().release();
2697 params.pop_back();
2698 if (!param) {
2699 continue;
2700 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002701 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
2702 mInputStreamFormat.reset(
2703 C2StreamBufferTypeSetting::input::From(param));
2704 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002705 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002706 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002707 }
2708 }
2709 mInitStatus = OK;
2710 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002711 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002712
2713 status_t initCheck() const { return mInitStatus; }
2714
2715 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2716 CHECK_EQ(1u, mFields.size());
2717 return mFields[0];
2718 }
2719
2720 const C2ApiFeaturesSetting &getApiFeatures() const {
2721 return mApiFeatures;
2722 }
2723
Taehwan Kim900b49c2021-12-13 11:16:22 +09002724 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
2725 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
2726 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
2727 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
2728 param->invalidate();
2729 return param;
2730 }();
2731 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
2732 }
2733
Wonsik Kimffb889a2020-05-28 11:32:25 -07002734 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2735 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2736 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2737 C2PortAllocatorsTuning::input::AllocUnique(0);
2738 param->invalidate();
2739 return param;
2740 }();
2741 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2742 }
2743
2744private:
2745 status_t mInitStatus{NO_INIT};
2746
2747 std::vector<C2FieldSupportedValuesQuery> mFields;
2748 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09002749 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002750 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2751};
2752
2753static const IntfCache &GetIntfCache(const std::string &name) {
2754 static IntfCache sNullIntfCache;
2755 static std::mutex sMutex;
2756 static std::map<std::string, IntfCache> sCache;
2757 std::unique_lock<std::mutex> lock{sMutex};
2758 auto it = sCache.find(name);
2759 if (it == sCache.end()) {
2760 lock.unlock();
2761 IntfCache intfCache;
2762 status_t err = intfCache.init(name);
2763 if (err != OK) {
2764 return sNullIntfCache;
2765 }
2766 lock.lock();
2767 it = sCache.insert({name, std::move(intfCache)}).first;
2768 }
2769 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002770}
2771
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002772static status_t GetCommonAllocatorIds(
2773 const std::vector<std::string> &names,
2774 C2Allocator::type_t type,
2775 std::set<C2Allocator::id_t> *ids) {
2776 int poolMask = GetCodec2PoolMask();
2777 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2778 C2Allocator::id_t defaultAllocatorId =
2779 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2780
2781 ids->clear();
2782 if (names.empty()) {
2783 return OK;
2784 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002785 bool firstIteration = true;
2786 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002787 const IntfCache &intfCache = GetIntfCache(name);
2788 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002789 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002790 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002791 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
2792 if (streamFormat) {
2793 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
2794 if (streamFormat.value == C2BufferData::GRAPHIC
2795 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
2796 allocatorType = C2Allocator::GRAPHIC;
2797 }
2798
2799 if (type != allocatorType) {
2800 // requested type is not supported at input allocators
2801 ids->clear();
2802 ids->insert(defaultAllocatorId);
2803 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
2804 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
2805 break;
2806 }
2807 }
2808
Wonsik Kimffb889a2020-05-28 11:32:25 -07002809 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002810 if (firstIteration) {
2811 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002812 if (allocators && allocators.flexCount() > 0) {
2813 ids->insert(allocators.m.values,
2814 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002815 }
2816 if (ids->empty()) {
2817 // The component does not advertise allocators. Use default.
2818 ids->insert(defaultAllocatorId);
2819 }
2820 continue;
2821 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002822 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002823 if (allocators && allocators.flexCount() > 0) {
2824 filtered = true;
2825 for (auto it = ids->begin(); it != ids->end(); ) {
2826 bool found = false;
2827 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2828 if (allocators.m.values[j] == *it) {
2829 found = true;
2830 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002831 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002832 }
2833 if (found) {
2834 ++it;
2835 } else {
2836 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002837 }
2838 }
2839 }
2840 if (!filtered) {
2841 // The component does not advertise supported allocators. Use default.
2842 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2843 if (ids->size() != (containsDefault ? 1 : 0)) {
2844 ids->clear();
2845 if (containsDefault) {
2846 ids->insert(defaultAllocatorId);
2847 }
2848 }
2849 }
2850 }
2851 // Finally, filter with pool masks
2852 for (auto it = ids->begin(); it != ids->end(); ) {
2853 if ((poolMask >> *it) & 1) {
2854 ++it;
2855 } else {
2856 it = ids->erase(it);
2857 }
2858 }
2859 return OK;
2860}
2861
2862static status_t CalculateMinMaxUsage(
2863 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2864 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2865 *minUsage = 0;
2866 *maxUsage = ~0ull;
2867 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002868 const IntfCache &intfCache = GetIntfCache(name);
2869 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002870 continue;
2871 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002872 const C2FieldSupportedValuesQuery &usageSupportedValues =
2873 intfCache.getUsageSupportedValues();
2874 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002875 continue;
2876 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002877 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002878 if (supported.type != C2FieldSupportedValues::FLAGS) {
2879 continue;
2880 }
2881 if (supported.values.empty()) {
2882 *maxUsage = 0;
2883 continue;
2884 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08002885 if (supported.values.size() > 1) {
2886 *minUsage |= supported.values[1].u64;
2887 } else {
2888 *minUsage |= supported.values[0].u64;
2889 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002890 int64_t currentMaxUsage = 0;
2891 for (const C2Value::Primitive &flags : supported.values) {
2892 currentMaxUsage |= flags.u64;
2893 }
2894 *maxUsage &= currentMaxUsage;
2895 }
2896 return OK;
2897}
2898
2899// static
2900status_t CCodec::CanFetchLinearBlock(
2901 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002902 for (const std::string &name : names) {
2903 const IntfCache &intfCache = GetIntfCache(name);
2904 if (intfCache.initCheck() != OK) {
2905 continue;
2906 }
2907 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2908 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2909 *isCompatible = false;
2910 return OK;
2911 }
2912 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002913 std::set<C2Allocator::id_t> allocators;
2914 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2915 if (allocators.empty()) {
2916 *isCompatible = false;
2917 return OK;
2918 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002919
2920 uint64_t minUsage = 0;
2921 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002922 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002923 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002924 *isCompatible = ((maxUsage & minUsage) == minUsage);
2925 return OK;
2926}
2927
2928static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2929 static std::mutex sMutex{};
2930 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2931 std::unique_lock<std::mutex> lock{sMutex};
2932 std::shared_ptr<C2BlockPool> pool;
2933 auto it = sPools.find(allocId);
2934 if (it == sPools.end()) {
2935 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2936 if (err == OK) {
2937 sPools.emplace(allocId, pool);
2938 } else {
2939 pool.reset();
2940 }
2941 } else {
2942 pool = it->second;
2943 }
2944 return pool;
2945}
2946
2947// static
2948std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2949 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002950 std::set<C2Allocator::id_t> allocators;
2951 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2952 if (allocators.empty()) {
2953 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2954 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002955
2956 uint64_t minUsage = 0;
2957 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002958 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002959 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002960 if ((maxUsage & minUsage) != minUsage) {
2961 allocators.clear();
2962 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2963 }
2964 std::shared_ptr<C2LinearBlock> block;
2965 for (C2Allocator::id_t allocId : allocators) {
2966 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2967 if (!pool) {
2968 continue;
2969 }
2970 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2971 if (err != C2_OK || !block) {
2972 block.reset();
2973 continue;
2974 }
2975 break;
2976 }
2977 return block;
2978}
2979
2980// static
2981status_t CCodec::CanFetchGraphicBlock(
2982 const std::vector<std::string> &names, bool *isCompatible) {
2983 uint64_t minUsage = 0;
2984 uint64_t maxUsage = ~0ull;
2985 std::set<C2Allocator::id_t> allocators;
2986 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2987 if (allocators.empty()) {
2988 *isCompatible = false;
2989 return OK;
2990 }
2991 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2992 *isCompatible = ((maxUsage & minUsage) == minUsage);
2993 return OK;
2994}
2995
2996// static
2997std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2998 int32_t width,
2999 int32_t height,
3000 int32_t format,
3001 uint64_t usage,
3002 const std::vector<std::string> &names) {
3003 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
3004 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
3005 ALOGD("Unrecognized pixel format: %d", format);
3006 return nullptr;
3007 }
3008 uint64_t minUsage = 0;
3009 uint64_t maxUsage = ~0ull;
3010 std::set<C2Allocator::id_t> allocators;
3011 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3012 if (allocators.empty()) {
3013 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3014 }
3015 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3016 minUsage |= usage;
3017 if ((maxUsage & minUsage) != minUsage) {
3018 allocators.clear();
3019 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3020 }
3021 std::shared_ptr<C2GraphicBlock> block;
3022 for (C2Allocator::id_t allocId : allocators) {
3023 std::shared_ptr<C2BlockPool> pool;
3024 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3025 if (err != C2_OK || !pool) {
3026 continue;
3027 }
3028 err = pool->fetchGraphicBlock(
3029 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
3030 if (err != C2_OK || !block) {
3031 block.reset();
3032 continue;
3033 }
3034 break;
3035 }
3036 return block;
3037}
3038
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003039} // namespace android