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