blob: 05c4dde9bf72a8d6b096739c2653caa0ea765bf3 [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodec"
19#include <utils/Log.h>
20
21#include <sstream>
22#include <thread>
23
24#include <C2Config.h>
25#include <C2Debug.h>
26#include <C2ParamInternal.h>
27#include <C2PlatformSupport.h>
28
Pawin Vongmasa36653902018-11-15 00:10:25 -080029#include <android/IOMXBufferSource.h>
Pawin Vongmasabf69de92019-10-29 06:21:27 -070030#include <android/hardware/media/c2/1.0/IInputSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080031#include <android/hardware/media/omx/1.0/IGraphicBufferSource.h>
32#include <android/hardware/media/omx/1.0/IOmx.h>
Wonsik Kim50811882022-04-28 15:57:27 -070033#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080034#include <android-base/stringprintf.h>
35#include <cutils/properties.h>
36#include <gui/IGraphicBufferProducer.h>
37#include <gui/Surface.h>
38#include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070039#include <media/omx/1.0/WOmxNode.h>
40#include <media/openmax/OMX_Core.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080041#include <media/openmax/OMX_IndexExt.h>
Wonsik Kim1f5063d2021-05-03 15:41:17 -070042#include <media/stagefright/foundation/avc_utils.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070043#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
44#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070045#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080046#include <media/stagefright/BufferProducerWrapper.h>
47#include <media/stagefright/MediaCodecConstants.h>
48#include <media/stagefright/PersistentSurface.h>
ted.sun765db4d2020-06-23 14:03:41 +080049#include <utils/NativeHandle.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080050
51#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080052#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070053#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080054#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080055#include "InputSurfaceWrapper.h"
56
57extern "C" android::PersistentSurface *CreateInputSurface();
58
59namespace android {
60
61using namespace std::chrono_literals;
62using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
63using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080064using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080065
Wonsik Kim9917d4a2019-10-24 12:56:38 -070066typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070067typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070068
Pawin Vongmasa36653902018-11-15 00:10:25 -080069namespace {
70
71class CCodecWatchdog : public AHandler {
72private:
73 enum {
74 kWhatWatch,
75 };
76 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
77
78public:
79 static sp<CCodecWatchdog> getInstance() {
80 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
81 static std::once_flag flag;
82 // Call Init() only once.
83 std::call_once(flag, Init, instance);
84 return instance;
85 }
86
87 ~CCodecWatchdog() = default;
88
89 void watch(sp<CCodec> codec) {
90 bool shouldPost = false;
91 {
92 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
93 // If a watch message is in flight, piggy-back this instance as well.
94 // Otherwise, post a new watch message.
95 shouldPost = codecs->empty();
96 codecs->emplace(codec);
97 }
98 if (shouldPost) {
99 ALOGV("posting watch message");
100 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
101 }
102 }
103
104protected:
105 void onMessageReceived(const sp<AMessage> &msg) {
106 switch (msg->what()) {
107 case kWhatWatch: {
108 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
109 ALOGV("watch for %zu codecs", codecs->size());
110 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
111 sp<CCodec> codec = it->promote();
112 if (codec == nullptr) {
113 continue;
114 }
115 codec->initiateReleaseIfStuck();
116 }
117 codecs->clear();
118 break;
119 }
120
121 default: {
122 TRESPASS("CCodecWatchdog: unrecognized message");
123 }
124 }
125 }
126
127private:
128 CCodecWatchdog() : mLooper(new ALooper) {}
129
130 static void Init(const sp<CCodecWatchdog> &thiz) {
131 ALOGV("Init");
132 thiz->mLooper->setName("CCodecWatchdog");
133 thiz->mLooper->registerHandler(thiz);
134 thiz->mLooper->start();
135 }
136
137 sp<ALooper> mLooper;
138
139 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
140};
141
142class C2InputSurfaceWrapper : public InputSurfaceWrapper {
143public:
144 explicit C2InputSurfaceWrapper(
145 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
146 mSurface(surface) {
147 }
148
149 ~C2InputSurfaceWrapper() override = default;
150
151 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
152 if (mConnection != nullptr) {
153 return ALREADY_EXISTS;
154 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800155 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800156 }
157
158 void disconnect() override {
159 if (mConnection != nullptr) {
160 mConnection->disconnect();
161 mConnection = nullptr;
162 }
163 }
164
165 status_t start() override {
166 // InputSurface does not distinguish started state
167 return OK;
168 }
169
170 status_t signalEndOfInputStream() override {
171 C2InputSurfaceEosTuning eos(true);
172 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800173 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800174 if (err != C2_OK) {
175 return UNKNOWN_ERROR;
176 }
177 return OK;
178 }
179
180 status_t configure(Config &config __unused) {
181 // TODO
182 return OK;
183 }
184
185private:
186 std::shared_ptr<Codec2Client::InputSurface> mSurface;
187 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
188};
189
190class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
191public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700192 typedef hardware::media::omx::V1_0::Status OmxStatus;
193
Pawin Vongmasa36653902018-11-15 00:10:25 -0800194 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700195 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800196 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700197 uint32_t height,
198 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800199 : mSource(source), mWidth(width), mHeight(height) {
200 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700201 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800202 }
203 ~GraphicBufferSourceWrapper() override = default;
204
205 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
206 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700207 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800208 mNode->setFrameSize(mWidth, mHeight);
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700209 // Usage is queried during configure(), so setting it beforehand.
Sungtak Lee0cd4fbc2023-02-02 00:59:01 +0000210 // 64 bit set parameter is existing only in C2OMXNode.
211 OMX_U64 usage64 = mConfig.mUsage;
212 status_t res = mNode->setParameter(
213 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits64,
214 &usage64, sizeof(usage64));
215
216 if (res != OK) {
217 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
218 (void)mNode->setParameter(
219 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
220 &usage, sizeof(usage));
221 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700222
Yanqiang Fanc56f3e62021-09-28 16:54:07 +0800223 return GetStatus(mSource->configure(
224 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800225 }
226
227 void disconnect() override {
228 if (mNode == nullptr) {
229 return;
230 }
231 sp<IOMXBufferSource> source = mNode->getSource();
232 if (source == nullptr) {
233 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
234 return;
235 }
236 source->onOmxIdle();
237 source->onOmxLoaded();
238 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700239 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800240 }
241
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700242 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
243 if (status.isOk()) {
244 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
245 } else if (status.isDeadObject()) {
246 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800247 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700248 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800249 }
250
251 status_t start() override {
252 sp<IOMXBufferSource> source = mNode->getSource();
253 if (source == nullptr) {
254 return NO_INIT;
255 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900256
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800257 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800258 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900259
Wonsik Kim34d66012021-03-01 16:40:33 -0800260 OMX_PARAM_PORTDEFINITIONTYPE param;
261 param.nPortIndex = kPortIndexInput;
262 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
263 &param, sizeof(param));
264 if (err == OK) {
265 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900266 }
267
268 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800269 source->onInputBufferAdded(i);
270 }
271
272 source->onOmxExecuting();
273 return OK;
274 }
275
276 status_t signalEndOfInputStream() override {
277 return GetStatus(mSource->signalEndOfInputStream());
278 }
279
280 status_t configure(Config &config) {
281 std::stringstream status;
282 status_t err = OK;
283
284 // handle each configuration granually, in case we need to handle part of the configuration
285 // elsewhere
286
287 // TRICKY: we do not unset frame delay repeating
288 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
289 int64_t us = 1e6 / config.mMinFps + 0.5;
290 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
291 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
292 if (res != OK) {
293 status << " (=> " << asString(res) << ")";
294 err = res;
295 }
296 mConfig.mMinFps = config.mMinFps;
297 }
298
299 // pts gap
300 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
301 if (mNode != nullptr) {
302 OMX_PARAM_U32TYPE ptrGapParam = {};
303 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700304 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800305 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
306 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700307 // float -> uint32_t is undefined if the value is negative.
308 // First convert to int32_t to ensure the expected behavior.
309 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800310 (void)mNode->setParameter(
311 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
312 &ptrGapParam, sizeof(ptrGapParam));
313 }
314 }
315
316 // max fps
317 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700318 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800319 && config.mMaxFps != mConfig.mMaxFps) {
320 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
321 status << " maxFps=" << config.mMaxFps;
322 if (res != OK) {
323 status << " (=> " << asString(res) << ")";
324 err = res;
325 }
326 mConfig.mMaxFps = config.mMaxFps;
327 }
328
329 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
330 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
331 status << " timeOffset " << config.mTimeOffsetUs << "us";
332 if (res != OK) {
333 status << " (=> " << asString(res) << ")";
334 err = res;
335 }
336 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
337 }
338
339 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
340 status_t res =
341 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
342 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
343 if (res != OK) {
344 status << " (=> " << asString(res) << ")";
345 err = res;
346 }
347 mConfig.mCaptureFps = config.mCaptureFps;
348 mConfig.mCodedFps = config.mCodedFps;
349 }
350
351 if (config.mStartAtUs != mConfig.mStartAtUs
352 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
353 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
354 status << " start at " << config.mStartAtUs << "us";
355 if (res != OK) {
356 status << " (=> " << asString(res) << ")";
357 err = res;
358 }
359 mConfig.mStartAtUs = config.mStartAtUs;
360 mConfig.mStopped = config.mStopped;
361 }
362
363 // suspend-resume
364 if (config.mSuspended != mConfig.mSuspended) {
365 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
366 status << " " << (config.mSuspended ? "suspend" : "resume")
367 << " at " << config.mSuspendAtUs << "us";
368 if (res != OK) {
369 status << " (=> " << asString(res) << ")";
370 err = res;
371 }
372 mConfig.mSuspended = config.mSuspended;
373 mConfig.mSuspendAtUs = config.mSuspendAtUs;
374 }
375
376 if (config.mStopped != mConfig.mStopped && config.mStopped) {
377 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
378 status << " stop at " << config.mStopAtUs << "us";
379 if (res != OK) {
380 status << " (=> " << asString(res) << ")";
381 err = res;
382 } else {
383 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700384 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
385 [&res, &delayUs = config.mInputDelayUs](
386 auto status, auto stopTimeOffsetUs) {
387 res = static_cast<status_t>(status);
388 delayUs = stopTimeOffsetUs;
389 });
390 if (!trans.isOk()) {
391 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
392 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800393 if (res != OK) {
394 status << " (=> " << asString(res) << ")";
395 } else {
396 status << "=" << config.mInputDelayUs << "us";
397 }
398 mConfig.mInputDelayUs = config.mInputDelayUs;
399 }
400 mConfig.mStopAtUs = config.mStopAtUs;
401 mConfig.mStopped = config.mStopped;
402 }
403
404 // color aspects (android._color-aspects)
405
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700406 // consumer usage is queried earlier.
407
Wonsik Kima1335e12021-04-22 16:28:29 -0700408 // priority
409 if (mConfig.mPriority != config.mPriority) {
410 if (config.mPriority != INT_MAX) {
411 mNode->setPriority(config.mPriority);
412 }
413 mConfig.mPriority = config.mPriority;
414 }
415
Wonsik Kimbd557932019-07-02 15:51:20 -0700416 if (status.str().empty()) {
417 ALOGD("ISConfig not changed");
418 } else {
419 ALOGD("ISConfig%s", status.str().c_str());
420 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800421 return err;
422 }
423
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700424 void onInputBufferDone(c2_cntr64_t index) override {
425 mNode->onInputBufferDone(index);
426 }
427
Wonsik Kim673dd192021-01-29 14:58:12 -0800428 android_dataspace getDataspace() override {
429 return mNode->getDataspace();
430 }
431
Pawin Vongmasa36653902018-11-15 00:10:25 -0800432private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700433 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800434 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700435 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800436 uint32_t mWidth;
437 uint32_t mHeight;
438 Config mConfig;
439};
440
441class Codec2ClientInterfaceWrapper : public C2ComponentStore {
442 std::shared_ptr<Codec2Client> mClient;
443
444public:
445 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
446 : mClient(client) { }
447
448 virtual ~Codec2ClientInterfaceWrapper() = default;
449
450 virtual c2_status_t config_sm(
451 const std::vector<C2Param *> &params,
452 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
453 return mClient->config(params, C2_MAY_BLOCK, failures);
454 };
455
456 virtual c2_status_t copyBuffer(
457 std::shared_ptr<C2GraphicBuffer>,
458 std::shared_ptr<C2GraphicBuffer>) {
459 return C2_OMITTED;
460 }
461
462 virtual c2_status_t createComponent(
463 C2String, std::shared_ptr<C2Component> *const component) {
464 component->reset();
465 return C2_OMITTED;
466 }
467
468 virtual c2_status_t createInterface(
469 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
470 interface->reset();
471 return C2_OMITTED;
472 }
473
474 virtual c2_status_t query_sm(
475 const std::vector<C2Param *> &stackParams,
476 const std::vector<C2Param::Index> &heapParamIndices,
477 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
478 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
479 }
480
481 virtual c2_status_t querySupportedParams_nb(
482 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
483 return mClient->querySupportedParams(params);
484 }
485
486 virtual c2_status_t querySupportedValues_sm(
487 std::vector<C2FieldSupportedValuesQuery> &fields) const {
488 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
489 }
490
491 virtual C2String getName() const {
492 return mClient->getName();
493 }
494
495 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
496 return mClient->getParamReflector();
497 }
498
499 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
500 return std::vector<std::shared_ptr<const C2Component::Traits>>();
501 }
502};
503
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800504void RevertOutputFormatIfNeeded(
505 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
506 // We used to not report changes to these keys to the client.
507 const static std::set<std::string> sIgnoredKeys({
508 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800509 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800510 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800511 KEY_MAX_WIDTH,
512 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800513 "csd-0",
514 "csd-1",
515 "csd-2",
516 });
517 if (currentFormat == oldFormat) {
518 return;
519 }
520 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
521 AMessage::Type type;
522 for (size_t i = diff->countEntries(); i > 0; --i) {
523 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
524 diff->removeEntryAt(i - 1);
525 }
526 }
527 if (diff->countEntries() == 0) {
528 currentFormat = oldFormat;
529 }
530}
531
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700532void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700533 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700534 const sp<AMessage> &outputFormat) {
535 if (mediaType == MIMETYPE_VIDEO_AVC) {
536 // Codec specific data should be SPS and PPS in a single buffer,
537 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
538 // We separate the two and put them into the output format
539 // under the keys "csd-0" and "csd-1".
540
541 unsigned csdIndex = 0;
542
543 const uint8_t *nalStart;
544 size_t nalSize;
545 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
546 sp<ABuffer> csd = new ABuffer(nalSize + 4);
547 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
548 memcpy(csd->data() + 4, nalStart, nalSize);
549
550 outputFormat->setBuffer(
551 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
552
553 ++csdIndex;
554 }
555
556 if (csdIndex != 2) {
557 ALOGW("Expected two NAL units from AVC codec config, but %u found",
558 csdIndex);
559 }
560 } else {
561 // For everything else we just stash the codec specific data into
562 // the output format as a single piece of csd under "csd-0".
563 sp<ABuffer> csd = new ABuffer(size);
564 memcpy(csd->data(), data, size);
565 csd->setRange(0, size);
566 outputFormat->setBuffer("csd-0", csd);
567 }
568}
569
Pawin Vongmasa36653902018-11-15 00:10:25 -0800570} // namespace
571
572// CCodec::ClientListener
573
574struct CCodec::ClientListener : public Codec2Client::Listener {
575
576 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
577
578 virtual void onWorkDone(
579 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800580 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800581 (void)component;
582 sp<CCodec> codec(mCodec.promote());
583 if (!codec) {
584 return;
585 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800586 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800587 }
588
589 virtual void onTripped(
590 const std::weak_ptr<Codec2Client::Component>& component,
591 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
592 ) override {
593 // TODO
594 (void)component;
595 (void)settingResult;
596 }
597
598 virtual void onError(
599 const std::weak_ptr<Codec2Client::Component>& component,
600 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800601 {
602 // Component is only used for reporting as we use a separate listener for each instance
603 std::shared_ptr<Codec2Client::Component> comp = component.lock();
604 if (!comp) {
605 ALOGD("Component died with error: 0x%x", errorCode);
606 } else {
607 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
608 }
609 }
610
611 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800612 // Note: for now we do not propagate the error code to MediaCodec
613 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800614 sp<CCodec> codec(mCodec.promote());
615 if (!codec || !codec->mCallback) {
616 return;
617 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800618 codec->mCallback->onError(
619 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
620 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800621 }
622
623 virtual void onDeath(
624 const std::weak_ptr<Codec2Client::Component>& component) override {
625 { // Log the death of the component.
626 std::shared_ptr<Codec2Client::Component> comp = component.lock();
627 if (!comp) {
628 ALOGE("Codec2 component died.");
629 } else {
630 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
631 }
632 }
633
634 // Report to MediaCodec.
635 sp<CCodec> codec(mCodec.promote());
636 if (!codec || !codec->mCallback) {
637 return;
638 }
639 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
640 }
641
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800642 virtual void onFrameRendered(uint64_t bufferQueueId,
643 int32_t slotId,
644 int64_t timestampNs) override {
645 // TODO: implement
646 (void)bufferQueueId;
647 (void)slotId;
648 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800649 }
650
651 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800652 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800653 sp<CCodec> codec(mCodec.promote());
654 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800655 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800656 }
657 }
658
659private:
660 wp<CCodec> mCodec;
661};
662
663// CCodecCallbackImpl
664
665class CCodecCallbackImpl : public CCodecCallback {
666public:
667 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
668 ~CCodecCallbackImpl() override = default;
669
670 void onError(status_t err, enum ActionCode actionCode) override {
671 mCodec->mCallback->onError(err, actionCode);
672 }
673
674 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
675 mCodec->mCallback->onOutputFramesRendered(
676 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
677 }
678
Pawin Vongmasa36653902018-11-15 00:10:25 -0800679 void onOutputBuffersChanged() override {
680 mCodec->mCallback->onOutputBuffersChanged();
681 }
682
Guillaume Chelfi5ffbcb32021-04-12 14:23:43 +0200683 void onFirstTunnelFrameReady() override {
684 mCodec->mCallback->onFirstTunnelFrameReady();
685 }
686
Pawin Vongmasa36653902018-11-15 00:10:25 -0800687private:
688 CCodec *mCodec;
689};
690
691// CCodec
692
693CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700694 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
695 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800696}
697
698CCodec::~CCodec() {
699}
700
701std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
702 return mChannel;
703}
704
705status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
706 status_t err = job();
707 if (err != C2_OK) {
708 mCallback->onError(err, ACTION_CODE_FATAL);
709 }
710 return err;
711}
712
713void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
714 auto setAllocating = [this] {
715 Mutexed<State>::Locked state(mState);
716 if (state->get() != RELEASED) {
717 return INVALID_OPERATION;
718 }
719 state->set(ALLOCATING);
720 return OK;
721 };
722 if (tryAndReportOnError(setAllocating) != OK) {
723 return;
724 }
725
726 sp<RefBase> codecInfo;
727 CHECK(msg->findObject("codecInfo", &codecInfo));
728 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
729
730 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
731 allocMsg->setObject("codecInfo", codecInfo);
732 allocMsg->post();
733}
734
735void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
736 if (codecInfo == nullptr) {
737 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
738 return;
739 }
740 ALOGD("allocate(%s)", codecInfo->getCodecName());
741 mClientListener.reset(new ClientListener(this));
742
743 AString componentName = codecInfo->getCodecName();
744 std::shared_ptr<Codec2Client> client;
745
746 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700747 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800749 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800750 SetPreferredCodec2ComponentStore(
751 std::make_shared<Codec2ClientInterfaceWrapper>(client));
752 }
753
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900754 std::shared_ptr<Codec2Client::Component> comp;
755 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800756 componentName.c_str(),
757 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900758 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900760 if (status != C2_OK) {
761 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800762 Mutexed<State>::Locked state(mState);
763 state->set(RELEASED);
764 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900765 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800766 state.lock();
767 return;
768 }
769 ALOGI("Created component [%s]", componentName.c_str());
770 mChannel->setComponent(comp);
771 auto setAllocated = [this, comp, client] {
772 Mutexed<State>::Locked state(mState);
773 if (state->get() != ALLOCATING) {
774 state->set(RELEASED);
775 return UNKNOWN_ERROR;
776 }
777 state->set(ALLOCATED);
778 state->comp = comp;
779 mClient = client;
780 return OK;
781 };
782 if (tryAndReportOnError(setAllocated) != OK) {
783 return;
784 }
785
786 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700787 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
788 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800789 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800790 if (err != OK) {
791 ALOGW("Failed to initialize configuration support");
792 // TODO: report error once we complete implementation.
793 }
794 config->queryConfiguration(comp);
795
796 mCallback->onComponentAllocated(componentName.c_str());
797}
798
799void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
800 auto checkAllocated = [this] {
801 Mutexed<State>::Locked state(mState);
802 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
803 };
804 if (tryAndReportOnError(checkAllocated) != OK) {
805 return;
806 }
807
808 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
809 msg->setMessage("format", format);
810 msg->post();
811}
812
813void CCodec::configure(const sp<AMessage> &msg) {
814 std::shared_ptr<Codec2Client::Component> comp;
815 auto checkAllocated = [this, &comp] {
816 Mutexed<State>::Locked state(mState);
817 if (state->get() != ALLOCATED) {
818 state->set(RELEASED);
819 return UNKNOWN_ERROR;
820 }
821 comp = state->comp;
822 return OK;
823 };
824 if (tryAndReportOnError(checkAllocated) != OK) {
825 return;
826 }
827
828 auto doConfig = [msg, comp, this]() -> status_t {
829 AString mime;
830 if (!msg->findString("mime", &mime)) {
831 return BAD_VALUE;
832 }
833
834 int32_t encoder;
835 if (!msg->findInt32("encoder", &encoder)) {
836 encoder = false;
837 }
838
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800839 int32_t flags;
840 if (!msg->findInt32("flags", &flags)) {
841 return BAD_VALUE;
842 }
843
Pawin Vongmasa36653902018-11-15 00:10:25 -0800844 // TODO: read from intf()
845 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
846 return UNKNOWN_ERROR;
847 }
848
849 int32_t storeMeta;
850 if (encoder
851 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
852 && storeMeta != kMetadataBufferTypeInvalid) {
853 if (storeMeta != kMetadataBufferTypeANWBuffer) {
854 ALOGD("Only ANW buffers are supported for legacy metadata mode");
855 return BAD_VALUE;
856 }
857 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
858 }
859
ted.sun765db4d2020-06-23 14:03:41 +0800860 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800861 sp<RefBase> obj;
862 sp<Surface> surface;
863 if (msg->findObject("native-window", &obj)) {
864 surface = static_cast<Surface *>(obj.get());
ted.sun765db4d2020-06-23 14:03:41 +0800865 // setup tunneled playback
866 if (surface != nullptr) {
867 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
868 const std::unique_ptr<Config> &config = *configLocked;
869 if ((config->mDomain & Config::IS_DECODER)
870 && (config->mDomain & Config::IS_VIDEO)) {
871 int32_t tunneled;
872 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
873 ALOGI("Configuring TUNNELED video playback.");
874
875 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
876 if (err != OK) {
877 ALOGE("configureTunneledVideoPlayback failed!");
878 return err;
879 }
880 config->mTunneled = true;
881 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +0100882
883 int32_t pushBlankBuffersOnStop = 0;
884 if (msg->findInt32(KEY_PUSH_BLANK_BUFFERS_ON_STOP, &pushBlankBuffersOnStop)) {
885 config->mPushBlankBuffersOnStop = pushBlankBuffersOnStop == 1;
886 }
ted.sun765db4d2020-06-23 14:03:41 +0800887 }
888 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800889 setSurface(surface);
890 }
891
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700892 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
893 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800894 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800895 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
896 ALOGD("[%s] buffers are %sbound to CCodec for this session",
897 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800898
Wonsik Kim1114eea2019-02-25 14:35:24 -0800899 // Enforce required parameters
900 int32_t i32;
901 float flt;
902 if (config->mDomain & Config::IS_AUDIO) {
903 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
904 ALOGD("sample rate is missing, which is required for audio components.");
905 return BAD_VALUE;
906 }
907 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
908 ALOGD("channel count is missing, which is required for audio components.");
909 return BAD_VALUE;
910 }
911 if ((config->mDomain & Config::IS_ENCODER)
912 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
913 && !msg->findInt32(KEY_BIT_RATE, &i32)
914 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
915 ALOGD("bitrate is missing, which is required for audio encoders.");
916 return BAD_VALUE;
917 }
918 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800919 int32_t width = 0;
920 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800921 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800922 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800923 ALOGD("width is missing, which is required for image/video components.");
924 return BAD_VALUE;
925 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800926 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800927 ALOGD("height is missing, which is required for image/video components.");
928 return BAD_VALUE;
929 }
930 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700931 int32_t mode = BITRATE_MODE_VBR;
932 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700933 if (!msg->findInt32(KEY_QUALITY, &i32)) {
934 ALOGD("quality is missing, which is required for video encoders in CQ.");
935 return BAD_VALUE;
936 }
937 } else {
938 if (!msg->findInt32(KEY_BIT_RATE, &i32)
939 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
940 ALOGD("bitrate is missing, which is required for video encoders.");
941 return BAD_VALUE;
942 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800943 }
944 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
945 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
946 ALOGD("I frame interval is missing, which is required for video encoders.");
947 return BAD_VALUE;
948 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700949 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
950 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
951 ALOGD("frame rate is missing, which is required for video encoders.");
952 return BAD_VALUE;
953 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800954 }
955 }
956
Pawin Vongmasa36653902018-11-15 00:10:25 -0800957 /*
958 * Handle input surface configuration
959 */
960 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
961 && (config->mDomain & Config::IS_ENCODER)) {
962 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
963 {
964 config->mISConfig->mMinFps = 0;
965 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800966 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800967 config->mISConfig->mMinFps = 1e6 / value;
968 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700969 if (!msg->findFloat(
970 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
971 config->mISConfig->mMaxFps = -1;
972 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800973 config->mISConfig->mMinAdjustedFps = 0;
974 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800975 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800976 if (value < 0 && value >= INT32_MIN) {
977 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700978 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800979 } else if (value > 0 && value <= INT32_MAX) {
980 config->mISConfig->mMinAdjustedFps = 1e6 / value;
981 }
982 }
983 }
984
985 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700986 bool captureFpsFound = false;
987 double timeLapseFps;
988 float captureRate;
989 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
990 config->mISConfig->mCaptureFps = timeLapseFps;
991 captureFpsFound = true;
992 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
993 config->mISConfig->mCaptureFps = captureRate;
994 captureFpsFound = true;
995 }
996 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800997 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
998 }
999 }
1000
1001 {
1002 config->mISConfig->mSuspended = false;
1003 config->mISConfig->mSuspendAtUs = -1;
1004 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001005 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001006 config->mISConfig->mSuspended = true;
1007 }
1008 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001009 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -07001010 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001011 }
1012
1013 /*
1014 * Handle desired color format.
1015 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001016 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001017 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001018 int32_t format = 0;
1019 // Query vendor format for Flexible YUV
1020 std::vector<std::unique_ptr<C2Param>> heapParams;
1021 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
Wonsik Kim50811882022-04-28 15:57:27 -07001022 int vendorSdkVersion = base::GetIntProperty(
1023 "ro.vendor.build.version.sdk", android_get_device_api_level());
guochuang709b48b2022-10-25 20:40:42 +08001024 if (mClient->query(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001025 {},
1026 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1027 C2_MAY_BLOCK,
1028 &heapParams) == C2_OK
1029 && heapParams.size() == 1u) {
1030 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1031 heapParams[0].get());
1032 } else {
1033 pixelFormatInfo = nullptr;
1034 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001035 // bit depth -> format
1036 std::map<uint32_t, uint32_t> flexPixelFormat;
1037 std::map<uint32_t, uint32_t> flexPlanarPixelFormat;
1038 std::map<uint32_t, uint32_t> flexSemiPlanarPixelFormat;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001039 if (pixelFormatInfo && *pixelFormatInfo) {
1040 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1041 const C2FlexiblePixelFormatDescriptorStruct &desc =
1042 pixelFormatInfo->m.values[i];
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001043 if (desc.subsampling != C2Color::YUV_420
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001044 // TODO(b/180076105): some device report wrong layout
1045 // || desc.layout == C2Color::INTERLEAVED_PACKED
1046 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1047 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1048 continue;
1049 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001050 if (flexPixelFormat.count(desc.bitDepth) == 0) {
1051 flexPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001052 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001053 if (desc.layout == C2Color::PLANAR_PACKED
1054 && flexPlanarPixelFormat.count(desc.bitDepth) == 0) {
1055 flexPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001056 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001057 if (desc.layout == C2Color::SEMIPLANAR_PACKED
1058 && flexSemiPlanarPixelFormat.count(desc.bitDepth) == 0) {
1059 flexSemiPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001060 }
1061 }
1062 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001063 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001064 // Also handle default color format (encoders require color format, so this is only
1065 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001066 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001067 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001068 const char *prefix = "";
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001069 if (flexSemiPlanarPixelFormat.count(8) != 0) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001070 format = COLOR_FormatYUV420SemiPlanar;
1071 prefix = "semi-";
1072 } else {
1073 format = COLOR_FormatYUV420Planar;
1074 }
1075 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1076 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001077 } else {
1078 format = COLOR_FormatSurface;
1079 }
1080 defaultColorFormat = format;
1081 }
1082 } else {
1083 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001084 if (vendorSdkVersion < __ANDROID_API_S__ &&
Taehwan Kim43e715d2022-09-22 12:04:59 +09001085 (format == COLOR_FormatYUV420Planar ||
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001086 format == COLOR_FormatYUV420PackedPlanar ||
1087 format == COLOR_FormatYUV420SemiPlanar ||
1088 format == COLOR_FormatYUV420PackedSemiPlanar)) {
1089 // pre-S framework used to map these color formats into YV12.
1090 // Codecs from older vendor partition may be relying on
1091 // this assumption.
1092 format = HAL_PIXEL_FORMAT_YV12;
1093 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001094 switch (format) {
1095 case COLOR_FormatYUV420Flexible:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001096 format = COLOR_FormatYUV420Planar;
1097 if (flexPixelFormat.count(8) != 0) {
1098 format = flexPixelFormat[8];
1099 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001100 break;
1101 case COLOR_FormatYUV420Planar:
1102 case COLOR_FormatYUV420PackedPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001103 if (flexPlanarPixelFormat.count(8) != 0) {
1104 format = flexPlanarPixelFormat[8];
1105 } else if (flexPixelFormat.count(8) != 0) {
1106 format = flexPixelFormat[8];
1107 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001108 break;
1109 case COLOR_FormatYUV420SemiPlanar:
1110 case COLOR_FormatYUV420PackedSemiPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001111 if (flexSemiPlanarPixelFormat.count(8) != 0) {
1112 format = flexSemiPlanarPixelFormat[8];
1113 } else if (flexPixelFormat.count(8) != 0) {
1114 format = flexPixelFormat[8];
1115 }
1116 break;
1117 case COLOR_FormatYUVP010:
1118 format = COLOR_FormatYUVP010;
1119 if (flexSemiPlanarPixelFormat.count(10) != 0) {
1120 format = flexSemiPlanarPixelFormat[10];
1121 } else if (flexPixelFormat.count(10) != 0) {
1122 format = flexPixelFormat[10];
1123 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001124 break;
1125 default:
1126 // No-op
1127 break;
1128 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001129 }
1130 }
1131
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001132 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001133 msg->setInt32("android._color-format", format);
1134 }
1135 }
1136
Wonsik Kim77e97c72021-01-20 10:33:22 -08001137 /*
1138 * Handle dataspace
1139 */
1140 int32_t usingRecorder;
1141 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1142 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1143 int32_t width, height;
1144 if (msg->findInt32("width", &width)
1145 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001146 ColorAspects aspects;
1147 getColorAspectsFromFormat(msg, aspects);
1148 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001149 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001150 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1151 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001152 }
1153 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1154 ALOGD("setting dataspace to %x", dataSpace);
1155 }
1156
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001157 int32_t subscribeToAllVendorParams;
1158 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1159 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1160 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1161 }
1162 }
1163
Pawin Vongmasa36653902018-11-15 00:10:25 -08001164 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001165 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1166 // the behavior here.
1167 sp<AMessage> sdkParams = msg;
1168 int32_t videoBitrate;
1169 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1170 sdkParams = msg->dup();
1171 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1172 }
ted.sun765db4d2020-06-23 14:03:41 +08001173 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001174 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001175 if (err != OK) {
1176 ALOGW("failed to convert configuration to c2 params");
1177 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001178
1179 int32_t maxBframes = 0;
1180 if ((config->mDomain & Config::IS_ENCODER)
1181 && (config->mDomain & Config::IS_VIDEO)
1182 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1183 && maxBframes > 0) {
1184 std::unique_ptr<C2StreamGopTuning::output> gop =
1185 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1186 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1187 gop->m.values[1] = {
1188 C2Config::picture_type_t(P_FRAME | B_FRAME),
1189 uint32_t(maxBframes)
1190 };
1191 configUpdate.push_back(std::move(gop));
1192 }
1193
Ray Essicka0ae6972021-03-10 19:40:01 -08001194 if ((config->mDomain & Config::IS_ENCODER)
1195 && (config->mDomain & Config::IS_VIDEO)) {
1196 // we may not use all 3 of these entries
1197 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1198 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1199 0u /* stream */);
1200
1201 int ix = 0;
1202
1203 int32_t iMax = INT32_MAX;
1204 int32_t iMin = INT32_MIN;
1205 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1206 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1207 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1208 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1209 }
1210
1211 int32_t pMax = INT32_MAX;
1212 int32_t pMin = INT32_MIN;
1213 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1214 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1215 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1216 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1217 }
1218
1219 int32_t bMax = INT32_MAX;
1220 int32_t bMin = INT32_MIN;
1221 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1222 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1223 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1224 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1225 }
1226
1227 // adjust to reflect actual use.
1228 qp->setFlexCount(ix);
1229
1230 configUpdate.push_back(std::move(qp));
1231 }
1232
Wonsik Kima1335e12021-04-22 16:28:29 -07001233 int32_t background = 0;
1234 if ((config->mDomain & Config::IS_VIDEO)
1235 && msg->findInt32("android._background-mode", &background)
1236 && background) {
1237 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1238 if (config->mISConfig) {
1239 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1240 }
1241 }
1242
Pawin Vongmasa36653902018-11-15 00:10:25 -08001243 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1244 if (err != OK) {
1245 ALOGW("failed to configure c2 params");
1246 return err;
1247 }
1248
1249 std::vector<std::unique_ptr<C2Param>> params;
1250 C2StreamUsageTuning::input usage(0u, 0u);
1251 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001252 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001253
Wonsik Kim3baecda2021-02-07 22:19:56 -08001254 C2Param::Index colorAspectsRequestIndex =
1255 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001256 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001257 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001258 };
Chaejung Lim86c22dc2021-12-23 00:41:05 -08001259 int32_t colorTransferRequest = 0;
1260 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1261 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1262 colorTransferRequest = 0;
1263 }
1264 c2_status_t c2err = C2_OK;
1265 if (colorTransferRequest != 0) {
1266 c2err = comp->query(
1267 { &usage, &maxInputSize, &prepend },
1268 indices,
1269 C2_DONT_BLOCK,
1270 &params);
1271 } else {
1272 c2err = comp->query(
1273 { &usage, &maxInputSize, &prepend },
1274 {},
1275 C2_DONT_BLOCK,
1276 &params);
1277 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001278 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1279 ALOGE("Failed to query component interface: %d", c2err);
1280 return UNKNOWN_ERROR;
1281 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001282 if (usage) {
1283 if (usage.value & C2MemoryUsage::CPU_READ) {
1284 config->mInputFormat->setInt32("using-sw-read-often", true);
1285 }
1286 if (config->mISConfig) {
1287 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1288 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1289 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001290 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001291 }
1292
1293 // NOTE: we don't blindly use client specified input size if specified as clients
1294 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1295 // client specified size is only used to ask for bigger buffers than component suggested
1296 // size.
1297 int32_t clientInputSize = 0;
1298 bool clientSpecifiedInputSize =
1299 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1300 // TEMP: enforce minimum buffer size of 1MB for video decoders
1301 // and 16K / 4K for audio encoders/decoders
1302 if (maxInputSize.value == 0) {
1303 if (config->mDomain & Config::IS_AUDIO) {
1304 maxInputSize.value = encoder ? 16384 : 4096;
1305 } else if (!encoder) {
1306 maxInputSize.value = 1048576u;
1307 }
1308 }
1309
1310 // verify that CSD fits into this size (if defined)
1311 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1312 sp<ABuffer> csd;
1313 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1314 if (csd && csd->size() > maxInputSize.value) {
1315 maxInputSize.value = csd->size();
1316 }
1317 }
1318 }
1319
1320 // TODO: do this based on component requiring linear allocator for input
1321 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1322 if (clientSpecifiedInputSize) {
1323 // Warn that we're overriding client's max input size if necessary.
1324 if ((uint32_t)clientInputSize < maxInputSize.value) {
1325 ALOGD("client requested max input size %d, which is smaller than "
1326 "what component recommended (%u); overriding with component "
1327 "recommendation.", clientInputSize, maxInputSize.value);
1328 ALOGW("This behavior is subject to change. It is recommended that "
1329 "app developers double check whether the requested "
1330 "max input size is in reasonable range.");
1331 } else {
1332 maxInputSize.value = clientInputSize;
1333 }
1334 }
1335 // Pass max input size on input format to the buffer channel (if supplied by the
1336 // component or by a default)
1337 if (maxInputSize.value) {
1338 config->mInputFormat->setInt32(
1339 KEY_MAX_INPUT_SIZE,
1340 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1341 }
1342 }
1343
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001344 int32_t clientPrepend;
1345 if ((config->mDomain & Config::IS_VIDEO)
1346 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001347 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001348 && clientPrepend
1349 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001350 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001351 return BAD_VALUE;
1352 }
1353
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001354 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001355 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1356 // propagate HDR static info to output format for both encoders and decoders
1357 // if component supports this info, we will update from component, but only the raw port,
1358 // so don't propagate if component already filled it in.
1359 sp<ABuffer> hdrInfo;
1360 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1361 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1362 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1363 }
1364
1365 // Set desired color format from configuration parameter
1366 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001367 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1368 format = defaultColorFormat;
1369 }
1370 if (config->mDomain & Config::IS_ENCODER) {
1371 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001372 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1373 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001374 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001375 } else {
1376 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001377 }
1378 }
1379
1380 // propagate encoder delay and padding to output format
1381 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1382 int delay = 0;
1383 if (msg->findInt32("encoder-delay", &delay)) {
1384 config->mOutputFormat->setInt32("encoder-delay", delay);
1385 }
1386 int padding = 0;
1387 if (msg->findInt32("encoder-padding", &padding)) {
1388 config->mOutputFormat->setInt32("encoder-padding", padding);
1389 }
1390 }
1391
Pawin Vongmasa36653902018-11-15 00:10:25 -08001392 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001393 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 int32_t mask;
1395 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1396 if (config->mDomain & Config::IS_ENCODER) {
1397 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1398 } else {
1399 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1400 }
1401 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001402
1403 // set PCM encoding
1404 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1405 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1406 if (encoder) {
1407 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1408 } else {
1409 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1410 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001411 }
1412
Wonsik Kim3baecda2021-02-07 22:19:56 -08001413 std::unique_ptr<C2Param> colorTransferRequestParam;
1414 for (std::unique_ptr<C2Param> &param : params) {
1415 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1416 ALOGI("found color transfer request param");
1417 colorTransferRequestParam = std::move(param);
1418 }
1419 }
Wonsik Kim3baecda2021-02-07 22:19:56 -08001420
1421 if (colorTransferRequest != 0) {
1422 if (colorTransferRequestParam && *colorTransferRequestParam) {
1423 C2StreamColorAspectsInfo::output *info =
1424 static_cast<C2StreamColorAspectsInfo::output *>(
1425 colorTransferRequestParam.get());
1426 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1427 colorTransferRequest = 0;
1428 }
1429 } else {
1430 colorTransferRequest = 0;
1431 }
1432 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1433 }
1434
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001435 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1436 // Need to get stride/vstride
1437 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1438 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1439 // TODO: retrieve these values without allocating a buffer.
1440 // Currently allocating a buffer is necessary to retrieve the layout.
1441 int64_t blockUsage =
1442 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1443 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
Taehwan Kim2772e1c2022-03-31 17:15:08 +09001444 width, height, componentColorFormat, blockUsage, {comp->getName()});
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001445 sp<GraphicBlockBuffer> buffer;
1446 if (block) {
1447 buffer = GraphicBlockBuffer::Allocate(
1448 config->mInputFormat,
1449 block,
1450 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1451 } else {
1452 ALOGD("Failed to allocate a graphic block "
1453 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1454 width, height, pixelFormat, (long long)blockUsage);
1455 // This means that byte buffer mode is not supported in this configuration
1456 // anyway. Skip setting stride/vstride to input format.
1457 }
1458 if (buffer) {
1459 sp<ABuffer> imageData = buffer->getImageData();
1460 MediaImage2 *img = nullptr;
1461 if (imageData && imageData->data()
1462 && imageData->size() >= sizeof(MediaImage2)) {
1463 img = (MediaImage2*)imageData->data();
1464 }
1465 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1466 int32_t stride = img->mPlane[0].mRowInc;
1467 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1468 if (img->mNumPlanes > 1 && stride > 0) {
1469 int64_t offsetDelta =
1470 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1471 if (offsetDelta % stride == 0) {
1472 int32_t vstride = int32_t(offsetDelta / stride);
1473 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1474 } else {
1475 ALOGD("Cannot report accurate slice height: "
1476 "offsetDelta = %lld stride = %d",
1477 (long long)offsetDelta, stride);
1478 }
1479 }
1480 }
1481 }
1482 }
1483 }
1484
Wonsik Kimec585c32021-10-01 01:11:00 -07001485 if (config->mTunneled) {
1486 config->mOutputFormat->setInt32("android._tunneled", 1);
1487 }
1488
Yushin Cho91873b52021-12-21 04:08:35 -08001489 // Convert an encoding statistics level to corresponding encoding statistics
1490 // kinds
1491 int32_t encodingStatisticsLevel = VIDEO_ENCODING_STATISTICS_LEVEL_NONE;
1492 if ((config->mDomain & Config::IS_ENCODER)
1493 && (config->mDomain & Config::IS_VIDEO)
1494 && msg->findInt32(KEY_VIDEO_ENCODING_STATISTICS_LEVEL, &encodingStatisticsLevel)) {
1495 // Higher level include all the enc stats belong to lower level.
1496 switch (encodingStatisticsLevel) {
1497 // case VIDEO_ENCODING_STATISTICS_LEVEL_2: // reserved for the future level 2
1498 // with more enc stat kinds
1499 // Future extended encoding statistics for the level 2 should be added here
1500 case VIDEO_ENCODING_STATISTICS_LEVEL_1:
Wonsik Kimeebab652022-06-02 13:01:55 -07001501 config->subscribeToConfigUpdate(
1502 comp,
1503 {
1504 C2AndroidStreamAverageBlockQuantizationInfo::output::PARAM_TYPE,
1505 C2StreamPictureTypeInfo::output::PARAM_TYPE,
1506 });
Yushin Cho91873b52021-12-21 04:08:35 -08001507 break;
1508 case VIDEO_ENCODING_STATISTICS_LEVEL_NONE:
1509 break;
1510 }
1511 }
1512 ALOGD("encoding statistics level = %d", encodingStatisticsLevel);
1513
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001514 ALOGD("setup formats input: %s",
1515 config->mInputFormat->debugString().c_str());
1516 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001517 config->mOutputFormat->debugString().c_str());
1518 return OK;
1519 };
1520 if (tryAndReportOnError(doConfig) != OK) {
1521 return;
1522 }
1523
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001524 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1525 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001526
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001527 config->queryConfiguration(comp);
1528
Pawin Vongmasa36653902018-11-15 00:10:25 -08001529 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1530}
1531
1532void CCodec::initiateCreateInputSurface() {
1533 status_t err = [this] {
1534 Mutexed<State>::Locked state(mState);
1535 if (state->get() != ALLOCATED) {
1536 return UNKNOWN_ERROR;
1537 }
1538 // TODO: read it from intf() properly.
1539 if (state->comp->getName().find("encoder") == std::string::npos) {
1540 return INVALID_OPERATION;
1541 }
1542 return OK;
1543 }();
1544 if (err != OK) {
1545 mCallback->onInputSurfaceCreationFailed(err);
1546 return;
1547 }
1548
1549 (new AMessage(kWhatCreateInputSurface, this))->post();
1550}
1551
Lajos Molnar47118272019-01-31 16:28:04 -08001552sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1553 using namespace android::hardware::media::omx::V1_0;
1554 using namespace android::hardware::media::omx::V1_0::utils;
1555 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1556 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1557 android::sp<IOmx> omx = IOmx::getService();
Sungtak Lee47dcb482022-04-15 10:47:08 -07001558 if (omx == nullptr) {
1559 return nullptr;
1560 }
Lajos Molnar47118272019-01-31 16:28:04 -08001561 typedef android::hardware::graphics::bufferqueue::V1_0::
1562 IGraphicBufferProducer HGraphicBufferProducer;
1563 typedef android::hardware::media::omx::V1_0::
1564 IGraphicBufferSource HGraphicBufferSource;
1565 OmxStatus s;
1566 android::sp<HGraphicBufferProducer> gbp;
1567 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001568
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001569 using ::android::hardware::Return;
1570 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001571 [&s, &gbp, &gbs](
1572 OmxStatus status,
1573 const android::sp<HGraphicBufferProducer>& producer,
1574 const android::sp<HGraphicBufferSource>& source) {
1575 s = status;
1576 gbp = producer;
1577 gbs = source;
1578 });
1579 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001580 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001581 }
1582
1583 return nullptr;
1584}
1585
1586sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1587 sp<PersistentSurface> surface(CreateInputSurface());
1588
1589 if (surface == nullptr) {
1590 surface = CreateOmxInputSurface();
1591 }
1592
1593 return surface;
1594}
1595
Pawin Vongmasa36653902018-11-15 00:10:25 -08001596void CCodec::createInputSurface() {
1597 status_t err;
1598 sp<IGraphicBufferProducer> bufferProducer;
1599
Pawin Vongmasa36653902018-11-15 00:10:25 -08001600 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001601 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001602 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001603 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1604 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001605 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001606 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001607 }
1608
Lajos Molnar47118272019-01-31 16:28:04 -08001609 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001610 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1611 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1612 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001613
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001614 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001615 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1616 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001617 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001618 inputSurface));
1619 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001620 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001621 int32_t width = 0;
1622 (void)outputFormat->findInt32("width", &width);
1623 int32_t height = 0;
1624 (void)outputFormat->findInt32("height", &height);
1625 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001626 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001627 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001628 } else {
1629 ALOGE("Corrupted input surface");
1630 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1631 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001632 }
1633
1634 if (err != OK) {
1635 ALOGE("Failed to set up input surface: %d", err);
1636 mCallback->onInputSurfaceCreationFailed(err);
1637 return;
1638 }
1639
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001640 // Formats can change after setupInputSurface
1641 sp<AMessage> inputFormat;
1642 {
1643 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1644 const std::unique_ptr<Config> &config = *configLocked;
1645 inputFormat = config->mInputFormat;
1646 outputFormat = config->mOutputFormat;
1647 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001648 mCallback->onInputSurfaceCreated(
1649 inputFormat,
1650 outputFormat,
1651 new BufferProducerWrapper(bufferProducer));
1652}
1653
1654status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001655 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1656 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001657 config->mUsingSurface = true;
1658
1659 // we are now using surface - apply default color aspects to input format - as well as
1660 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001661 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001662
1663 // configure dataspace
1664 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
Wonsik Kim66b19552021-08-02 16:07:49 -07001665
1666 // The output format contains app-configured color aspects, and the input format
1667 // has the default color aspects. Use the default for the unspecified params.
1668 ColorAspects inputColorAspects, colorAspects;
1669 getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
1670 getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
1671 if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
1672 colorAspects.mRange = inputColorAspects.mRange;
1673 }
1674 if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
1675 colorAspects.mPrimaries = inputColorAspects.mPrimaries;
1676 }
1677 if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
1678 colorAspects.mTransfer = inputColorAspects.mTransfer;
1679 }
1680 if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
1681 colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
1682 }
1683 android_dataspace dataSpace = getDataSpaceForColorAspects(
1684 colorAspects, /* mayExtend = */ false);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001685 surface->setDataSpace(dataSpace);
Wonsik Kim66b19552021-08-02 16:07:49 -07001686 setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
1687 config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
1688
1689 ALOGD("input format %s to %s",
1690 inputFormatChanged ? "changed" : "unchanged",
1691 config->mInputFormat->debugString().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001692
1693 status_t err = mChannel->setInputSurface(surface);
1694 if (err != OK) {
1695 // undo input format update
1696 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001697 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001698 return err;
1699 }
1700 config->mInputSurface = surface;
1701
1702 if (config->mISConfig) {
1703 surface->configure(*config->mISConfig);
1704 } else {
1705 ALOGD("ISConfig: no configuration");
1706 }
1707
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001708 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001709}
1710
1711void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1712 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1713 msg->setObject("surface", surface);
1714 msg->post();
1715}
1716
1717void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001718 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001719 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001720 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001721 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1722 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001723 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001724 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001725 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001726 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1727 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1728 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1729 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001730 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1731 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1732 if (err != OK) {
1733 ALOGE("Failed to set up input surface: %d", err);
1734 mCallback->onInputSurfaceDeclined(err);
1735 return;
1736 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001737 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001738 int32_t width = 0;
1739 (void)outputFormat->findInt32("width", &width);
1740 int32_t height = 0;
1741 (void)outputFormat->findInt32("height", &height);
1742 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001743 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001744 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 {
1750 ALOGE("Failed to set input surface: Corrupted surface.");
1751 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1752 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001753 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001754 // Formats can change after setupInputSurface
1755 sp<AMessage> inputFormat;
1756 {
1757 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1758 const std::unique_ptr<Config> &config = *configLocked;
1759 inputFormat = config->mInputFormat;
1760 outputFormat = config->mOutputFormat;
1761 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001762 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1763}
1764
1765void CCodec::initiateStart() {
1766 auto setStarting = [this] {
1767 Mutexed<State>::Locked state(mState);
1768 if (state->get() != ALLOCATED) {
1769 return UNKNOWN_ERROR;
1770 }
1771 state->set(STARTING);
1772 return OK;
1773 };
1774 if (tryAndReportOnError(setStarting) != OK) {
1775 return;
1776 }
1777
1778 (new AMessage(kWhatStart, this))->post();
1779}
1780
1781void CCodec::start() {
1782 std::shared_ptr<Codec2Client::Component> comp;
1783 auto checkStarting = [this, &comp] {
1784 Mutexed<State>::Locked state(mState);
1785 if (state->get() != STARTING) {
1786 return UNKNOWN_ERROR;
1787 }
1788 comp = state->comp;
1789 return OK;
1790 };
1791 if (tryAndReportOnError(checkStarting) != OK) {
1792 return;
1793 }
1794
1795 c2_status_t err = comp->start();
1796 if (err != C2_OK) {
1797 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1798 ACTION_CODE_FATAL);
1799 return;
1800 }
1801 sp<AMessage> inputFormat;
1802 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001803 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001804 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001805 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001806 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1807 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001808 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001809 // start triggers format dup
1810 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001811 if (config->mInputSurface) {
1812 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001813 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001814 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001815 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001816 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001817 if (err2 != OK) {
1818 mCallback->onError(err2, ACTION_CODE_FATAL);
1819 return;
1820 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001821 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001822 if (err2 != OK) {
1823 mCallback->onError(err2, ACTION_CODE_FATAL);
1824 return;
1825 }
1826
1827 auto setRunning = [this] {
1828 Mutexed<State>::Locked state(mState);
1829 if (state->get() != STARTING) {
1830 return UNKNOWN_ERROR;
1831 }
1832 state->set(RUNNING);
1833 return OK;
1834 };
1835 if (tryAndReportOnError(setRunning) != OK) {
1836 return;
1837 }
Arun Johnson5997bb02022-04-01 19:35:44 +00001838
Wonsik Kim34b28b42022-05-20 15:49:32 -07001839 // preparation of input buffers may not succeed due to the lack of
1840 // memory; returning correct error code (NO_MEMORY) as an error allows
1841 // MediaCodec to try reclaim and restart codec gracefully.
1842 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
1843 err2 = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
1844 if (err2 != OK) {
1845 ALOGE("Initial preparation for Input Buffers failed");
1846 mCallback->onError(err2, ACTION_CODE_FATAL);
1847 return;
1848 }
1849
Pawin Vongmasa36653902018-11-15 00:10:25 -08001850 mCallback->onStartCompleted();
1851
Wonsik Kim34b28b42022-05-20 15:49:32 -07001852 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001853}
1854
1855void CCodec::initiateShutdown(bool keepComponentAllocated) {
1856 if (keepComponentAllocated) {
1857 initiateStop();
1858 } else {
1859 initiateRelease();
1860 }
1861}
1862
1863void CCodec::initiateStop() {
1864 {
1865 Mutexed<State>::Locked state(mState);
1866 if (state->get() == ALLOCATED
1867 || state->get() == RELEASED
1868 || state->get() == STOPPING
1869 || state->get() == RELEASING) {
1870 // We're already stopped, released, or doing it right now.
1871 state.unlock();
1872 mCallback->onStopCompleted();
1873 state.lock();
1874 return;
1875 }
1876 state->set(STOPPING);
1877 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001878 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00001879 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
1880 sp<AMessage> stopMessage(new AMessage(kWhatStop, this));
1881 stopMessage->setInt32("pushBlankBuffer", pushBlankBuffer);
1882 stopMessage->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001883}
1884
Sungtak Lee99144332023-01-26 11:03:14 +00001885void CCodec::stop(bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001886 std::shared_ptr<Codec2Client::Component> comp;
1887 {
1888 Mutexed<State>::Locked state(mState);
1889 if (state->get() == RELEASING) {
1890 state.unlock();
1891 // We're already stopped or release is in progress.
1892 mCallback->onStopCompleted();
1893 state.lock();
1894 return;
1895 } else if (state->get() != STOPPING) {
1896 state.unlock();
1897 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1898 state.lock();
1899 return;
1900 }
1901 comp = state->comp;
1902 }
1903 status_t err = comp->stop();
Sungtak Lee99144332023-01-26 11:03:14 +00001904 mChannel->stopUseOutputSurface(pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001905 if (err != C2_OK) {
1906 // TODO: convert err into status_t
1907 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1908 }
1909
1910 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001911 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1912 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001913 if (config->mInputSurface) {
1914 config->mInputSurface->disconnect();
1915 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001916 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001917 }
1918 }
1919 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001920 Mutexed<State>::Locked state(mState);
1921 if (state->get() == STOPPING) {
1922 state->set(ALLOCATED);
1923 }
1924 }
1925 mCallback->onStopCompleted();
1926}
1927
1928void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001929 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001930 {
1931 Mutexed<State>::Locked state(mState);
1932 if (state->get() == RELEASED || state->get() == RELEASING) {
1933 // We're already released or doing it right now.
1934 if (sendCallback) {
1935 state.unlock();
1936 mCallback->onReleaseCompleted();
1937 state.lock();
1938 }
1939 return;
1940 }
1941 if (state->get() == ALLOCATING) {
1942 state->set(RELEASING);
1943 // With the altered state allocate() would fail and clean up.
1944 if (sendCallback) {
1945 state.unlock();
1946 mCallback->onReleaseCompleted();
1947 state.lock();
1948 }
1949 return;
1950 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001951 if (state->get() == STARTING
1952 || state->get() == RUNNING
1953 || state->get() == STOPPING) {
1954 // Input surface may have been started, so clean up is needed.
1955 clearInputSurfaceIfNeeded = true;
1956 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001957 state->set(RELEASING);
1958 }
1959
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001960 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001961 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1962 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001963 if (config->mInputSurface) {
1964 config->mInputSurface->disconnect();
1965 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001966 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001967 }
1968 }
1969
Wonsik Kim936a89c2020-05-08 16:07:50 -07001970 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00001971 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001972 // thiz holds strong ref to this while the thread is running.
1973 sp<CCodec> thiz(this);
Sungtak Lee99144332023-01-26 11:03:14 +00001974 std::thread([thiz, sendCallback, pushBlankBuffer]
1975 { thiz->release(sendCallback, pushBlankBuffer); }).detach();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001976}
1977
Sungtak Lee99144332023-01-26 11:03:14 +00001978void CCodec::release(bool sendCallback, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001979 std::shared_ptr<Codec2Client::Component> comp;
1980 {
1981 Mutexed<State>::Locked state(mState);
1982 if (state->get() == RELEASED) {
1983 if (sendCallback) {
1984 state.unlock();
1985 mCallback->onReleaseCompleted();
1986 state.lock();
1987 }
1988 return;
1989 }
1990 comp = state->comp;
1991 }
1992 comp->release();
Sungtak Lee99144332023-01-26 11:03:14 +00001993 mChannel->stopUseOutputSurface(pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001994
1995 {
1996 Mutexed<State>::Locked state(mState);
1997 state->set(RELEASED);
1998 state->comp.reset();
1999 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002000 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002001 if (sendCallback) {
2002 mCallback->onReleaseCompleted();
2003 }
2004}
2005
2006status_t CCodec::setSurface(const sp<Surface> &surface) {
Sungtak Lee99144332023-01-26 11:03:14 +00002007 bool pushBlankBuffer = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002008 {
2009 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2010 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002011 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
2012 status_t err = OK;
2013
Wonsik Kim75e22f42021-04-14 23:34:51 -07002014 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002015 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07002016 nativeWindow.get(),
2017 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
2018 if (err != OK) {
2019 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
2020 nativeWindow.get(), config->mSidebandHandle->handle(), err);
2021 return err;
2022 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002023 } else {
2024 // Explicitly reset the sideband handle of the window for
2025 // non-tunneled video in case the window was previously used
2026 // for a tunneled video playback.
2027 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
2028 if (err != OK) {
2029 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
2030 return err;
2031 }
ted.sun765db4d2020-06-23 14:03:41 +08002032 }
Sungtak Lee99144332023-01-26 11:03:14 +00002033 pushBlankBuffer = config->mPushBlankBuffersOnStop;
ted.sun765db4d2020-06-23 14:03:41 +08002034 }
Sungtak Lee99144332023-01-26 11:03:14 +00002035 return mChannel->setSurface(surface, pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002036}
2037
2038void CCodec::signalFlush() {
2039 status_t err = [this] {
2040 Mutexed<State>::Locked state(mState);
2041 if (state->get() == FLUSHED) {
2042 return ALREADY_EXISTS;
2043 }
2044 if (state->get() != RUNNING) {
2045 return UNKNOWN_ERROR;
2046 }
2047 state->set(FLUSHING);
2048 return OK;
2049 }();
2050 switch (err) {
2051 case ALREADY_EXISTS:
2052 mCallback->onFlushCompleted();
2053 return;
2054 case OK:
2055 break;
2056 default:
2057 mCallback->onError(err, ACTION_CODE_FATAL);
2058 return;
2059 }
2060
2061 mChannel->stop();
2062 (new AMessage(kWhatFlush, this))->post();
2063}
2064
2065void CCodec::flush() {
2066 std::shared_ptr<Codec2Client::Component> comp;
2067 auto checkFlushing = [this, &comp] {
2068 Mutexed<State>::Locked state(mState);
2069 if (state->get() != FLUSHING) {
2070 return UNKNOWN_ERROR;
2071 }
2072 comp = state->comp;
2073 return OK;
2074 };
2075 if (tryAndReportOnError(checkFlushing) != OK) {
2076 return;
2077 }
2078
2079 std::list<std::unique_ptr<C2Work>> flushedWork;
2080 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2081 {
2082 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2083 flushedWork.splice(flushedWork.end(), *queue);
2084 }
2085 if (err != C2_OK) {
2086 // TODO: convert err into status_t
2087 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2088 }
2089
2090 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002091
2092 {
2093 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002094 if (state->get() == FLUSHING) {
2095 state->set(FLUSHED);
2096 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002097 }
2098 mCallback->onFlushCompleted();
2099}
2100
2101void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002102 std::shared_ptr<Codec2Client::Component> comp;
2103 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002104 Mutexed<State>::Locked state(mState);
2105 if (state->get() != FLUSHED) {
2106 return UNKNOWN_ERROR;
2107 }
2108 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002109 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002110 return OK;
2111 };
2112 if (tryAndReportOnError(setResuming) != OK) {
2113 return;
2114 }
2115
Wonsik Kime75a5da2020-02-14 17:29:03 -08002116 {
2117 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2118 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002119 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002120 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002121 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002122 }
2123
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002124 (void)mChannel->start(nullptr, nullptr, [&]{
2125 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2126 const std::unique_ptr<Config> &config = *configLocked;
2127 return config->mBuffersBoundToCodec;
2128 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002129
2130 {
2131 Mutexed<State>::Locked state(mState);
2132 if (state->get() != RESUMING) {
2133 state.unlock();
2134 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2135 state.lock();
2136 return;
2137 }
2138 state->set(RUNNING);
2139 }
2140
Wonsik Kim34b28b42022-05-20 15:49:32 -07002141 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
2142 status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
Wonsik Kim944b0a52022-08-18 17:06:33 -07002143 // FIXME(b/237656746)
2144 if (err != OK && err != NO_MEMORY) {
Wonsik Kima027bf72022-05-09 19:45:57 -07002145 ALOGE("Resume request for Input Buffers failed");
2146 mCallback->onError(err, ACTION_CODE_FATAL);
Wonsik Kim34b28b42022-05-20 15:49:32 -07002147 return;
Wonsik Kima027bf72022-05-09 19:45:57 -07002148 }
Wonsik Kim34b28b42022-05-20 15:49:32 -07002149 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002150}
2151
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002152void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002153 std::shared_ptr<Codec2Client::Component> comp;
2154 auto checkState = [this, &comp] {
2155 Mutexed<State>::Locked state(mState);
2156 if (state->get() == RELEASED) {
2157 return INVALID_OPERATION;
2158 }
2159 comp = state->comp;
2160 return OK;
2161 };
2162 if (tryAndReportOnError(checkState) != OK) {
2163 return;
2164 }
2165
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002166 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2167 // the behavior here.
2168 sp<AMessage> params = msg;
2169 int32_t bitrate;
2170 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2171 params = msg->dup();
2172 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2173 }
2174
Houxiang Dai5a97b472021-03-22 17:56:04 +08002175 int32_t syncId = 0;
2176 if (params->findInt32("audio-hw-sync", &syncId)
2177 || params->findInt32("hw-av-sync-id", &syncId)) {
2178 configureTunneledVideoPlayback(comp, nullptr, params);
2179 }
2180
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002181 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2182 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002183
2184 /**
2185 * Handle input surface parameters
2186 */
2187 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002188 && (config->mDomain & Config::IS_ENCODER)
2189 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002190 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002191
2192 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2193 config->mISConfig->mStopped = false;
2194 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2195 config->mISConfig->mStopped = true;
2196 }
2197
2198 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002199 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002200 config->mISConfig->mSuspended = value;
2201 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002202 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002203 }
2204
2205 (void)config->mInputSurface->configure(*config->mISConfig);
2206 if (config->mISConfig->mStopped) {
2207 config->mInputFormat->setInt64(
2208 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2209 }
2210 }
2211
2212 std::vector<std::unique_ptr<C2Param>> configUpdate;
2213 (void)config->getConfigUpdateFromSdkParams(
2214 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2215 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2216 // Parameter synchronization is not defined when using input surface. For now, route
2217 // these directly to the component.
2218 if (config->mInputSurface == nullptr
2219 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2220 || comp->getName().find("c2.android.") == 0)) {
2221 mChannel->setParameters(configUpdate);
2222 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002223 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002224 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002225 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002226 }
2227}
2228
2229void CCodec::signalEndOfInputStream() {
2230 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2231}
2232
2233void CCodec::signalRequestIDRFrame() {
2234 std::shared_ptr<Codec2Client::Component> comp;
2235 {
2236 Mutexed<State>::Locked state(mState);
2237 if (state->get() == RELEASED) {
2238 ALOGD("no IDR request sent since component is released");
2239 return;
2240 }
2241 comp = state->comp;
2242 }
2243 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002244 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2245 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002246 std::vector<std::unique_ptr<C2Param>> params;
2247 params.push_back(
2248 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2249 config->setParameters(comp, params, C2_MAY_BLOCK);
2250}
2251
Wonsik Kim874ad382021-03-12 09:59:36 -08002252status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2253 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2254 const std::unique_ptr<Config> &config = *configLocked;
2255 return config->querySupportedParameters(names);
2256}
2257
2258status_t CCodec::describeParameter(
2259 const std::string &name, CodecParameterDescriptor *desc) {
2260 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2261 const std::unique_ptr<Config> &config = *configLocked;
2262 return config->describe(name, desc);
2263}
2264
2265status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2266 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2267 if (!comp) {
2268 return INVALID_OPERATION;
2269 }
2270 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2271 const std::unique_ptr<Config> &config = *configLocked;
2272 return config->subscribeToVendorConfigUpdate(comp, names);
2273}
2274
2275status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2276 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2277 if (!comp) {
2278 return INVALID_OPERATION;
2279 }
2280 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2281 const std::unique_ptr<Config> &config = *configLocked;
2282 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2283}
2284
Wonsik Kimab34ed62019-01-31 15:28:46 -08002285void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002286 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002287 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2288 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002289 }
2290 (new AMessage(kWhatWorkDone, this))->post();
2291}
2292
Wonsik Kimab34ed62019-01-31 15:28:46 -08002293void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2294 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002295 if (arrayIndex == 0) {
2296 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002297 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2298 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002299 if (config->mInputSurface) {
2300 config->mInputSurface->onInputBufferDone(frameIndex);
2301 }
2302 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002303}
2304
2305void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2306 TimePoint now = std::chrono::steady_clock::now();
2307 CCodecWatchdog::getInstance()->watch(this);
2308 switch (msg->what()) {
2309 case kWhatAllocate: {
2310 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002311 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002312 sp<RefBase> obj;
2313 CHECK(msg->findObject("codecInfo", &obj));
2314 allocate((MediaCodecInfo *)obj.get());
2315 break;
2316 }
2317 case kWhatConfigure: {
2318 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002319 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002320 sp<AMessage> format;
2321 CHECK(msg->findMessage("format", &format));
2322 configure(format);
2323 break;
2324 }
2325 case kWhatStart: {
2326 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002327 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002328 start();
2329 break;
2330 }
2331 case kWhatStop: {
2332 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002333 setDeadline(now, 1500ms, "stop");
Sungtak Lee99144332023-01-26 11:03:14 +00002334 int32_t pushBlankBuffer;
2335 if (!msg->findInt32("pushBlankBuffer", &pushBlankBuffer)) {
2336 pushBlankBuffer = 0;
2337 }
2338 stop(static_cast<bool>(pushBlankBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002339 break;
2340 }
2341 case kWhatFlush: {
2342 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002343 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002344 flush();
2345 break;
2346 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002347 case kWhatRelease: {
2348 mChannel->release();
2349 mClient.reset();
2350 mClientListener.reset();
2351 break;
2352 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002353 case kWhatCreateInputSurface: {
2354 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002355 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002356 createInputSurface();
2357 break;
2358 }
2359 case kWhatSetInputSurface: {
2360 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002361 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002362 sp<RefBase> obj;
2363 CHECK(msg->findObject("surface", &obj));
2364 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2365 setInputSurface(surface);
2366 break;
2367 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002368 case kWhatWorkDone: {
2369 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002370 bool shouldPost = false;
2371 {
2372 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2373 if (queue->empty()) {
2374 break;
2375 }
2376 work.swap(queue->front());
2377 queue->pop_front();
2378 shouldPost = !queue->empty();
2379 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002380 if (shouldPost) {
2381 (new AMessage(kWhatWorkDone, this))->post();
2382 }
2383
Pawin Vongmasa36653902018-11-15 00:10:25 -08002384 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002385 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002386 sp<AMessage> outputFormat = nullptr;
2387 {
2388 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2389 const std::unique_ptr<Config> &config = *configLocked;
2390 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2391 config->watch<C2StreamInitDataInfo::output>();
2392 if (!work->worklets.empty()
2393 && (work->worklets.front()->output.flags
2394 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002395
Wonsik Kim75e22f42021-04-14 23:34:51 -07002396 // copy buffer info to config
2397 std::vector<std::unique_ptr<C2Param>> updates;
2398 for (const std::unique_ptr<C2Param> &param
2399 : work->worklets.front()->output.configUpdate) {
2400 updates.push_back(C2Param::Copy(*param));
2401 }
2402 unsigned stream = 0;
2403 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2404 work->worklets.front()->output.buffers;
2405 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2406 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2407 // move all info into output-stream #0 domain
2408 updates.emplace_back(
2409 C2Param::CopyAsStream(*info, true /* output */, stream));
2410 }
2411
2412 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2413 // for now only do the first block
2414 if (!blocks.empty()) {
2415 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2416 // block.crop().left, block.crop().top,
2417 // block.crop().width, block.crop().height,
2418 // block.width(), block.height());
2419 const C2ConstGraphicBlock &block = blocks[0];
2420 updates.emplace_back(new C2StreamCropRectInfo::output(
2421 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002422 }
2423 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002424 }
George Burgess IVc813a592020-02-22 22:54:44 -08002425
Wonsik Kim75e22f42021-04-14 23:34:51 -07002426 sp<AMessage> oldFormat = config->mOutputFormat;
2427 config->updateConfiguration(updates, config->mOutputDomain);
2428 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002429
Wonsik Kim75e22f42021-04-14 23:34:51 -07002430 // copy standard infos to graphic buffers if not already present (otherwise, we
2431 // may overwrite the actual intermediate value with a final value)
2432 stream = 0;
2433 const static C2Param::Index stdGfxInfos[] = {
2434 C2StreamRotationInfo::output::PARAM_TYPE,
2435 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2436 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2437 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Taehwan Kim2d222b82022-05-12 14:19:26 +09002438 C2StreamHdr10PlusInfo::output::PARAM_TYPE, // will be deprecated
2439 C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE,
Wonsik Kim75e22f42021-04-14 23:34:51 -07002440 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2441 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2442 };
2443 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2444 if (buf->data().graphicBlocks().size()) {
2445 for (C2Param::Index ix : stdGfxInfos) {
2446 if (!buf->hasInfo(ix)) {
2447 const C2Param *param =
2448 config->getConfigParameterValue(ix.withStream(stream));
2449 if (param) {
2450 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2451 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2452 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002453 }
2454 }
2455 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002456 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002457 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002458 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002459 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302460 if (work->worklets.empty()
2461 || !work->worklets.back()
2462 || (work->worklets.back()->output.flags
2463 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2464 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2465 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002466 }
2467 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002468 initData = initDataWatcher.update();
2469 AmendOutputFormatWithCodecSpecificData(
2470 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2471 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002472 }
2473 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002474 }
2475 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002476 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002477 break;
2478 }
2479 case kWhatWatch: {
2480 // watch message already posted; no-op.
2481 break;
2482 }
2483 default: {
2484 ALOGE("unrecognized message");
2485 break;
2486 }
2487 }
2488 setDeadline(TimePoint::max(), 0ms, "none");
2489}
2490
2491void CCodec::setDeadline(
2492 const TimePoint &now,
2493 const std::chrono::milliseconds &timeout,
2494 const char *name) {
2495 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2496 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2497 deadline->set(now + (timeout * mult), name);
2498}
2499
ted.sun765db4d2020-06-23 14:03:41 +08002500status_t CCodec::configureTunneledVideoPlayback(
2501 std::shared_ptr<Codec2Client::Component> comp,
2502 sp<NativeHandle> *sidebandHandle,
2503 const sp<AMessage> &msg) {
2504 std::vector<std::unique_ptr<C2SettingResult>> failures;
2505
2506 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2507 C2PortTunneledModeTuning::output::AllocUnique(
2508 1,
2509 C2PortTunneledModeTuning::Struct::SIDEBAND,
2510 C2PortTunneledModeTuning::Struct::REALTIME,
2511 0);
2512 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2513 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2514 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2515 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2516 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2517 } else {
2518 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2519 tunneledPlayback->setFlexCount(0);
2520 }
2521 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2522 if (c2err != C2_OK) {
2523 return UNKNOWN_ERROR;
2524 }
2525
Houxiang Dai5a97b472021-03-22 17:56:04 +08002526 if (sidebandHandle == nullptr) {
2527 return OK;
2528 }
2529
ted.sun765db4d2020-06-23 14:03:41 +08002530 std::vector<std::unique_ptr<C2Param>> params;
2531 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2532 if (c2err == C2_OK && params.size() == 1u) {
2533 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2534 C2PortTunnelHandleTuning::output::From(params[0].get());
2535 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2536 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2537 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2538 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2539 memcpy(handle->data, videoTunnelSideband->m.values,
2540 sizeof(int32_t) * videoTunnelSideband->flexCount());
2541 return OK;
2542 } else {
2543 return NO_MEMORY;
2544 }
2545 }
2546 return UNKNOWN_ERROR;
2547}
2548
Pawin Vongmasa36653902018-11-15 00:10:25 -08002549void CCodec::initiateReleaseIfStuck() {
2550 std::string name;
2551 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002552 {
2553 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002554 if (deadline->get() < std::chrono::steady_clock::now()) {
2555 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002556 }
2557 if (deadline->get() != TimePoint::max()) {
2558 pendingDeadline = true;
2559 }
2560 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002561 bool tunneled = false;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002562 bool isMediaTypeKnown = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002563 {
Wonsik Kimabca11e2021-04-30 13:11:41 -07002564 static const std::set<std::string> kKnownMediaTypes{
2565 MIMETYPE_VIDEO_VP8,
2566 MIMETYPE_VIDEO_VP9,
2567 MIMETYPE_VIDEO_AV1,
2568 MIMETYPE_VIDEO_AVC,
2569 MIMETYPE_VIDEO_HEVC,
2570 MIMETYPE_VIDEO_MPEG4,
2571 MIMETYPE_VIDEO_H263,
2572 MIMETYPE_VIDEO_MPEG2,
2573 MIMETYPE_VIDEO_RAW,
2574 MIMETYPE_VIDEO_DOLBY_VISION,
2575
2576 MIMETYPE_AUDIO_AMR_NB,
2577 MIMETYPE_AUDIO_AMR_WB,
2578 MIMETYPE_AUDIO_MPEG,
2579 MIMETYPE_AUDIO_AAC,
2580 MIMETYPE_AUDIO_QCELP,
2581 MIMETYPE_AUDIO_VORBIS,
2582 MIMETYPE_AUDIO_OPUS,
2583 MIMETYPE_AUDIO_G711_ALAW,
2584 MIMETYPE_AUDIO_G711_MLAW,
2585 MIMETYPE_AUDIO_RAW,
2586 MIMETYPE_AUDIO_FLAC,
2587 MIMETYPE_AUDIO_MSGSM,
2588 MIMETYPE_AUDIO_AC3,
2589 MIMETYPE_AUDIO_EAC3,
2590
2591 MIMETYPE_IMAGE_ANDROID_HEIC,
2592 };
Wonsik Kim75e22f42021-04-14 23:34:51 -07002593 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2594 const std::unique_ptr<Config> &config = *configLocked;
2595 tunneled = config->mTunneled;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002596 isMediaTypeKnown = (kKnownMediaTypes.count(config->mCodingMediaType) != 0);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002597 }
Wonsik Kimabca11e2021-04-30 13:11:41 -07002598 if (!tunneled && isMediaTypeKnown && name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002599 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2600 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2601 if (elapsed >= kWorkDurationThreshold) {
2602 name = "queue";
2603 }
2604 if (elapsed > 0s) {
2605 pendingDeadline = true;
2606 }
2607 }
2608 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002609 // We're not stuck.
2610 if (pendingDeadline) {
2611 // If we are not stuck yet but still has deadline coming up,
2612 // post watch message to check back later.
2613 (new AMessage(kWhatWatch, this))->post();
2614 }
2615 return;
2616 }
2617
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002618 C2String compName;
2619 {
2620 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002621 if (!state->comp) {
2622 ALOGD("previous call to %s exceeded timeout "
2623 "and the component is already released", name.c_str());
2624 return;
2625 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002626 compName = state->comp->getName();
2627 }
2628 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2629
Pawin Vongmasa36653902018-11-15 00:10:25 -08002630 initiateRelease(false);
2631 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2632}
2633
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002634// static
2635PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002636 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002637 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002638 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002639 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2640 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002641 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002642 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2643 sp<IGraphicBufferProducer> gbp;
2644 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2645 status_t err = gbs->initCheck();
2646 if (err != OK) {
2647 ALOGE("Failed to create persistent input surface: error %d", err);
2648 return nullptr;
2649 }
2650 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002651 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002652 } else {
2653 return nullptr;
2654 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002655 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002656 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002657 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002658 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002659 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002660}
2661
Wonsik Kimffb889a2020-05-28 11:32:25 -07002662class IntfCache {
2663public:
2664 IntfCache() = default;
2665
2666 status_t init(const std::string &name) {
2667 std::shared_ptr<Codec2Client::Interface> intf{
2668 Codec2Client::CreateInterfaceByName(name.c_str())};
2669 if (!intf) {
2670 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2671 mInitStatus = NO_INIT;
2672 return NO_INIT;
2673 }
2674 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2675 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2676 C2ParamField{&sUsage, &sUsage.value}));
2677 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2678 if (err != C2_OK) {
2679 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2680 name.c_str(), err);
2681 mFields[0].status = err;
2682 }
2683 std::vector<std::unique_ptr<C2Param>> params;
2684 err = intf->query(
2685 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09002686 {
2687 C2StreamBufferTypeSetting::input::PARAM_TYPE,
2688 C2PortAllocatorsTuning::input::PARAM_TYPE
2689 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07002690 C2_MAY_BLOCK,
2691 &params);
2692 if (err != C2_OK && err != C2_BAD_INDEX) {
2693 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2694 name.c_str(), err);
2695 }
2696 while (!params.empty()) {
2697 C2Param *param = params.back().release();
2698 params.pop_back();
2699 if (!param) {
2700 continue;
2701 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002702 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
2703 mInputStreamFormat.reset(
2704 C2StreamBufferTypeSetting::input::From(param));
2705 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002706 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002707 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002708 }
2709 }
2710 mInitStatus = OK;
2711 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002712 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002713
2714 status_t initCheck() const { return mInitStatus; }
2715
2716 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2717 CHECK_EQ(1u, mFields.size());
2718 return mFields[0];
2719 }
2720
2721 const C2ApiFeaturesSetting &getApiFeatures() const {
2722 return mApiFeatures;
2723 }
2724
Taehwan Kim900b49c2021-12-13 11:16:22 +09002725 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
2726 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
2727 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
2728 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
2729 param->invalidate();
2730 return param;
2731 }();
2732 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
2733 }
2734
Wonsik Kimffb889a2020-05-28 11:32:25 -07002735 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2736 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2737 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2738 C2PortAllocatorsTuning::input::AllocUnique(0);
2739 param->invalidate();
2740 return param;
2741 }();
2742 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2743 }
2744
2745private:
2746 status_t mInitStatus{NO_INIT};
2747
2748 std::vector<C2FieldSupportedValuesQuery> mFields;
2749 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09002750 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002751 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2752};
2753
2754static const IntfCache &GetIntfCache(const std::string &name) {
2755 static IntfCache sNullIntfCache;
2756 static std::mutex sMutex;
2757 static std::map<std::string, IntfCache> sCache;
2758 std::unique_lock<std::mutex> lock{sMutex};
2759 auto it = sCache.find(name);
2760 if (it == sCache.end()) {
2761 lock.unlock();
2762 IntfCache intfCache;
2763 status_t err = intfCache.init(name);
2764 if (err != OK) {
2765 return sNullIntfCache;
2766 }
2767 lock.lock();
2768 it = sCache.insert({name, std::move(intfCache)}).first;
2769 }
2770 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002771}
2772
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002773static status_t GetCommonAllocatorIds(
2774 const std::vector<std::string> &names,
2775 C2Allocator::type_t type,
2776 std::set<C2Allocator::id_t> *ids) {
2777 int poolMask = GetCodec2PoolMask();
2778 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2779 C2Allocator::id_t defaultAllocatorId =
2780 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2781
2782 ids->clear();
2783 if (names.empty()) {
2784 return OK;
2785 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002786 bool firstIteration = true;
2787 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002788 const IntfCache &intfCache = GetIntfCache(name);
2789 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002790 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002791 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002792 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
2793 if (streamFormat) {
2794 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
2795 if (streamFormat.value == C2BufferData::GRAPHIC
2796 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
2797 allocatorType = C2Allocator::GRAPHIC;
2798 }
2799
2800 if (type != allocatorType) {
2801 // requested type is not supported at input allocators
2802 ids->clear();
2803 ids->insert(defaultAllocatorId);
2804 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
2805 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
2806 break;
2807 }
2808 }
2809
Wonsik Kimffb889a2020-05-28 11:32:25 -07002810 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002811 if (firstIteration) {
2812 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002813 if (allocators && allocators.flexCount() > 0) {
2814 ids->insert(allocators.m.values,
2815 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002816 }
2817 if (ids->empty()) {
2818 // The component does not advertise allocators. Use default.
2819 ids->insert(defaultAllocatorId);
2820 }
2821 continue;
2822 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002823 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002824 if (allocators && allocators.flexCount() > 0) {
2825 filtered = true;
2826 for (auto it = ids->begin(); it != ids->end(); ) {
2827 bool found = false;
2828 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2829 if (allocators.m.values[j] == *it) {
2830 found = true;
2831 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002832 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002833 }
2834 if (found) {
2835 ++it;
2836 } else {
2837 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002838 }
2839 }
2840 }
2841 if (!filtered) {
2842 // The component does not advertise supported allocators. Use default.
2843 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2844 if (ids->size() != (containsDefault ? 1 : 0)) {
2845 ids->clear();
2846 if (containsDefault) {
2847 ids->insert(defaultAllocatorId);
2848 }
2849 }
2850 }
2851 }
2852 // Finally, filter with pool masks
2853 for (auto it = ids->begin(); it != ids->end(); ) {
2854 if ((poolMask >> *it) & 1) {
2855 ++it;
2856 } else {
2857 it = ids->erase(it);
2858 }
2859 }
2860 return OK;
2861}
2862
2863static status_t CalculateMinMaxUsage(
2864 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2865 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2866 *minUsage = 0;
2867 *maxUsage = ~0ull;
2868 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002869 const IntfCache &intfCache = GetIntfCache(name);
2870 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002871 continue;
2872 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002873 const C2FieldSupportedValuesQuery &usageSupportedValues =
2874 intfCache.getUsageSupportedValues();
2875 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002876 continue;
2877 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002878 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002879 if (supported.type != C2FieldSupportedValues::FLAGS) {
2880 continue;
2881 }
2882 if (supported.values.empty()) {
2883 *maxUsage = 0;
2884 continue;
2885 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08002886 if (supported.values.size() > 1) {
2887 *minUsage |= supported.values[1].u64;
2888 } else {
2889 *minUsage |= supported.values[0].u64;
2890 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002891 int64_t currentMaxUsage = 0;
2892 for (const C2Value::Primitive &flags : supported.values) {
2893 currentMaxUsage |= flags.u64;
2894 }
2895 *maxUsage &= currentMaxUsage;
2896 }
2897 return OK;
2898}
2899
2900// static
2901status_t CCodec::CanFetchLinearBlock(
2902 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002903 for (const std::string &name : names) {
2904 const IntfCache &intfCache = GetIntfCache(name);
2905 if (intfCache.initCheck() != OK) {
2906 continue;
2907 }
2908 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2909 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2910 *isCompatible = false;
2911 return OK;
2912 }
2913 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002914 std::set<C2Allocator::id_t> allocators;
2915 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2916 if (allocators.empty()) {
2917 *isCompatible = false;
2918 return OK;
2919 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002920
2921 uint64_t minUsage = 0;
2922 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002923 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002924 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002925 *isCompatible = ((maxUsage & minUsage) == minUsage);
2926 return OK;
2927}
2928
2929static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2930 static std::mutex sMutex{};
2931 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2932 std::unique_lock<std::mutex> lock{sMutex};
2933 std::shared_ptr<C2BlockPool> pool;
2934 auto it = sPools.find(allocId);
2935 if (it == sPools.end()) {
2936 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2937 if (err == OK) {
2938 sPools.emplace(allocId, pool);
2939 } else {
2940 pool.reset();
2941 }
2942 } else {
2943 pool = it->second;
2944 }
2945 return pool;
2946}
2947
2948// static
2949std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2950 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002951 std::set<C2Allocator::id_t> allocators;
2952 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2953 if (allocators.empty()) {
2954 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2955 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002956
2957 uint64_t minUsage = 0;
2958 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002959 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002960 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002961 if ((maxUsage & minUsage) != minUsage) {
2962 allocators.clear();
2963 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2964 }
2965 std::shared_ptr<C2LinearBlock> block;
2966 for (C2Allocator::id_t allocId : allocators) {
2967 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2968 if (!pool) {
2969 continue;
2970 }
2971 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2972 if (err != C2_OK || !block) {
2973 block.reset();
2974 continue;
2975 }
2976 break;
2977 }
2978 return block;
2979}
2980
2981// static
2982status_t CCodec::CanFetchGraphicBlock(
2983 const std::vector<std::string> &names, bool *isCompatible) {
2984 uint64_t minUsage = 0;
2985 uint64_t maxUsage = ~0ull;
2986 std::set<C2Allocator::id_t> allocators;
2987 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2988 if (allocators.empty()) {
2989 *isCompatible = false;
2990 return OK;
2991 }
2992 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2993 *isCompatible = ((maxUsage & minUsage) == minUsage);
2994 return OK;
2995}
2996
2997// static
2998std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2999 int32_t width,
3000 int32_t height,
3001 int32_t format,
3002 uint64_t usage,
3003 const std::vector<std::string> &names) {
3004 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
3005 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
3006 ALOGD("Unrecognized pixel format: %d", format);
3007 return nullptr;
3008 }
3009 uint64_t minUsage = 0;
3010 uint64_t maxUsage = ~0ull;
3011 std::set<C2Allocator::id_t> allocators;
3012 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3013 if (allocators.empty()) {
3014 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3015 }
3016 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3017 minUsage |= usage;
3018 if ((maxUsage & minUsage) != minUsage) {
3019 allocators.clear();
3020 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3021 }
3022 std::shared_ptr<C2GraphicBlock> block;
3023 for (C2Allocator::id_t allocId : allocators) {
3024 std::shared_ptr<C2BlockPool> pool;
3025 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3026 if (err != C2_OK || !pool) {
3027 continue;
3028 }
3029 err = pool->fetchGraphicBlock(
3030 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
3031 if (err != C2_OK || !block) {
3032 block.reset();
3033 continue;
3034 }
3035 break;
3036 }
3037 return block;
3038}
3039
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003040} // namespace android