blob: 2db6f2f4b42d4486ac314c277fb4103cc1246a9c [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodec"
19#include <utils/Log.h>
20
21#include <sstream>
22#include <thread>
23
24#include <C2Config.h>
25#include <C2Debug.h>
26#include <C2ParamInternal.h>
27#include <C2PlatformSupport.h>
28
Pawin Vongmasa36653902018-11-15 00:10:25 -080029#include <android/IOMXBufferSource.h>
Pawin Vongmasabf69de92019-10-29 06:21:27 -070030#include <android/hardware/media/c2/1.0/IInputSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080031#include <android/hardware/media/omx/1.0/IGraphicBufferSource.h>
32#include <android/hardware/media/omx/1.0/IOmx.h>
Wonsik Kim50811882022-04-28 15:57:27 -070033#include <android-base/properties.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080034#include <android-base/stringprintf.h>
35#include <cutils/properties.h>
36#include <gui/IGraphicBufferProducer.h>
37#include <gui/Surface.h>
38#include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070039#include <media/omx/1.0/WOmxNode.h>
40#include <media/openmax/OMX_Core.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080041#include <media/openmax/OMX_IndexExt.h>
Wonsik Kim1f5063d2021-05-03 15:41:17 -070042#include <media/stagefright/foundation/avc_utils.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070043#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
44#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070045#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080046#include <media/stagefright/BufferProducerWrapper.h>
47#include <media/stagefright/MediaCodecConstants.h>
48#include <media/stagefright/PersistentSurface.h>
ted.sun765db4d2020-06-23 14:03:41 +080049#include <utils/NativeHandle.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080050
51#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080052#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070053#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080054#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080055#include "InputSurfaceWrapper.h"
56
57extern "C" android::PersistentSurface *CreateInputSurface();
58
59namespace android {
60
61using namespace std::chrono_literals;
62using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
63using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080064using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080065
Wonsik Kim9917d4a2019-10-24 12:56:38 -070066typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070067typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070068
Pawin Vongmasa36653902018-11-15 00:10:25 -080069namespace {
70
71class CCodecWatchdog : public AHandler {
72private:
73 enum {
74 kWhatWatch,
75 };
76 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
77
78public:
79 static sp<CCodecWatchdog> getInstance() {
80 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
81 static std::once_flag flag;
82 // Call Init() only once.
83 std::call_once(flag, Init, instance);
84 return instance;
85 }
86
87 ~CCodecWatchdog() = default;
88
89 void watch(sp<CCodec> codec) {
90 bool shouldPost = false;
91 {
92 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
93 // If a watch message is in flight, piggy-back this instance as well.
94 // Otherwise, post a new watch message.
95 shouldPost = codecs->empty();
96 codecs->emplace(codec);
97 }
98 if (shouldPost) {
99 ALOGV("posting watch message");
100 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
101 }
102 }
103
104protected:
105 void onMessageReceived(const sp<AMessage> &msg) {
106 switch (msg->what()) {
107 case kWhatWatch: {
108 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
109 ALOGV("watch for %zu codecs", codecs->size());
110 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
111 sp<CCodec> codec = it->promote();
112 if (codec == nullptr) {
113 continue;
114 }
115 codec->initiateReleaseIfStuck();
116 }
117 codecs->clear();
118 break;
119 }
120
121 default: {
122 TRESPASS("CCodecWatchdog: unrecognized message");
123 }
124 }
125 }
126
127private:
128 CCodecWatchdog() : mLooper(new ALooper) {}
129
130 static void Init(const sp<CCodecWatchdog> &thiz) {
131 ALOGV("Init");
132 thiz->mLooper->setName("CCodecWatchdog");
133 thiz->mLooper->registerHandler(thiz);
134 thiz->mLooper->start();
135 }
136
137 sp<ALooper> mLooper;
138
139 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
140};
141
142class C2InputSurfaceWrapper : public InputSurfaceWrapper {
143public:
144 explicit C2InputSurfaceWrapper(
145 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
146 mSurface(surface) {
147 }
148
149 ~C2InputSurfaceWrapper() override = default;
150
151 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
152 if (mConnection != nullptr) {
153 return ALREADY_EXISTS;
154 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800155 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800156 }
157
158 void disconnect() override {
159 if (mConnection != nullptr) {
160 mConnection->disconnect();
161 mConnection = nullptr;
162 }
163 }
164
165 status_t start() override {
166 // InputSurface does not distinguish started state
167 return OK;
168 }
169
170 status_t signalEndOfInputStream() override {
171 C2InputSurfaceEosTuning eos(true);
172 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800173 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800174 if (err != C2_OK) {
175 return UNKNOWN_ERROR;
176 }
177 return OK;
178 }
179
180 status_t configure(Config &config __unused) {
181 // TODO
182 return OK;
183 }
184
185private:
186 std::shared_ptr<Codec2Client::InputSurface> mSurface;
187 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
188};
189
190class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
191public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700192 typedef hardware::media::omx::V1_0::Status OmxStatus;
193
Pawin Vongmasa36653902018-11-15 00:10:25 -0800194 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700195 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800196 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700197 uint32_t height,
198 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800199 : mSource(source), mWidth(width), mHeight(height) {
200 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700201 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800202 }
203 ~GraphicBufferSourceWrapper() override = default;
204
205 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
206 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700207 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800208 mNode->setFrameSize(mWidth, mHeight);
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700209 // Usage is queried during configure(), so setting it beforehand.
Sungtak Lee0cd4fbc2023-02-02 00:59:01 +0000210 // 64 bit set parameter is existing only in C2OMXNode.
211 OMX_U64 usage64 = mConfig.mUsage;
212 status_t res = mNode->setParameter(
213 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits64,
214 &usage64, sizeof(usage64));
215
216 if (res != OK) {
217 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
218 (void)mNode->setParameter(
219 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
220 &usage, sizeof(usage));
221 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700222
Yanqiang Fanc56f3e62021-09-28 16:54:07 +0800223 return GetStatus(mSource->configure(
224 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800225 }
226
227 void disconnect() override {
228 if (mNode == nullptr) {
229 return;
230 }
231 sp<IOMXBufferSource> source = mNode->getSource();
232 if (source == nullptr) {
233 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
234 return;
235 }
236 source->onOmxIdle();
237 source->onOmxLoaded();
238 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700239 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800240 }
241
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700242 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
243 if (status.isOk()) {
244 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
245 } else if (status.isDeadObject()) {
246 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800247 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700248 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800249 }
250
251 status_t start() override {
252 sp<IOMXBufferSource> source = mNode->getSource();
253 if (source == nullptr) {
254 return NO_INIT;
255 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900256
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800257 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800258 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900259
Wonsik Kim34d66012021-03-01 16:40:33 -0800260 OMX_PARAM_PORTDEFINITIONTYPE param;
261 param.nPortIndex = kPortIndexInput;
262 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
263 &param, sizeof(param));
264 if (err == OK) {
265 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900266 }
267
268 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800269 source->onInputBufferAdded(i);
270 }
271
272 source->onOmxExecuting();
273 return OK;
274 }
275
276 status_t signalEndOfInputStream() override {
277 return GetStatus(mSource->signalEndOfInputStream());
278 }
279
280 status_t configure(Config &config) {
281 std::stringstream status;
282 status_t err = OK;
283
284 // handle each configuration granually, in case we need to handle part of the configuration
285 // elsewhere
286
287 // TRICKY: we do not unset frame delay repeating
288 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
289 int64_t us = 1e6 / config.mMinFps + 0.5;
290 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
291 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
292 if (res != OK) {
293 status << " (=> " << asString(res) << ")";
294 err = res;
295 }
296 mConfig.mMinFps = config.mMinFps;
297 }
298
299 // pts gap
300 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
301 if (mNode != nullptr) {
302 OMX_PARAM_U32TYPE ptrGapParam = {};
303 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700304 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800305 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
306 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700307 // float -> uint32_t is undefined if the value is negative.
308 // First convert to int32_t to ensure the expected behavior.
309 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800310 (void)mNode->setParameter(
311 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
312 &ptrGapParam, sizeof(ptrGapParam));
313 }
314 }
315
316 // max fps
317 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700318 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800319 && config.mMaxFps != mConfig.mMaxFps) {
320 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
321 status << " maxFps=" << config.mMaxFps;
322 if (res != OK) {
323 status << " (=> " << asString(res) << ")";
324 err = res;
325 }
326 mConfig.mMaxFps = config.mMaxFps;
327 }
328
329 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
330 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
331 status << " timeOffset " << config.mTimeOffsetUs << "us";
332 if (res != OK) {
333 status << " (=> " << asString(res) << ")";
334 err = res;
335 }
336 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
337 }
338
339 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
340 status_t res =
341 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
342 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
343 if (res != OK) {
344 status << " (=> " << asString(res) << ")";
345 err = res;
346 }
347 mConfig.mCaptureFps = config.mCaptureFps;
348 mConfig.mCodedFps = config.mCodedFps;
349 }
350
351 if (config.mStartAtUs != mConfig.mStartAtUs
352 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
353 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
354 status << " start at " << config.mStartAtUs << "us";
355 if (res != OK) {
356 status << " (=> " << asString(res) << ")";
357 err = res;
358 }
359 mConfig.mStartAtUs = config.mStartAtUs;
360 mConfig.mStopped = config.mStopped;
361 }
362
363 // suspend-resume
364 if (config.mSuspended != mConfig.mSuspended) {
365 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
366 status << " " << (config.mSuspended ? "suspend" : "resume")
367 << " at " << config.mSuspendAtUs << "us";
368 if (res != OK) {
369 status << " (=> " << asString(res) << ")";
370 err = res;
371 }
372 mConfig.mSuspended = config.mSuspended;
373 mConfig.mSuspendAtUs = config.mSuspendAtUs;
374 }
375
376 if (config.mStopped != mConfig.mStopped && config.mStopped) {
377 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
378 status << " stop at " << config.mStopAtUs << "us";
379 if (res != OK) {
380 status << " (=> " << asString(res) << ")";
381 err = res;
382 } else {
383 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700384 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
385 [&res, &delayUs = config.mInputDelayUs](
386 auto status, auto stopTimeOffsetUs) {
387 res = static_cast<status_t>(status);
388 delayUs = stopTimeOffsetUs;
389 });
390 if (!trans.isOk()) {
391 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
392 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800393 if (res != OK) {
394 status << " (=> " << asString(res) << ")";
395 } else {
396 status << "=" << config.mInputDelayUs << "us";
397 }
398 mConfig.mInputDelayUs = config.mInputDelayUs;
399 }
400 mConfig.mStopAtUs = config.mStopAtUs;
401 mConfig.mStopped = config.mStopped;
402 }
403
404 // color aspects (android._color-aspects)
405
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700406 // consumer usage is queried earlier.
407
Wonsik Kima1335e12021-04-22 16:28:29 -0700408 // priority
409 if (mConfig.mPriority != config.mPriority) {
410 if (config.mPriority != INT_MAX) {
411 mNode->setPriority(config.mPriority);
412 }
413 mConfig.mPriority = config.mPriority;
414 }
415
Wonsik Kimbd557932019-07-02 15:51:20 -0700416 if (status.str().empty()) {
417 ALOGD("ISConfig not changed");
418 } else {
419 ALOGD("ISConfig%s", status.str().c_str());
420 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800421 return err;
422 }
423
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700424 void onInputBufferDone(c2_cntr64_t index) override {
425 mNode->onInputBufferDone(index);
426 }
427
Wonsik Kim673dd192021-01-29 14:58:12 -0800428 android_dataspace getDataspace() override {
429 return mNode->getDataspace();
430 }
431
Pawin Vongmasa36653902018-11-15 00:10:25 -0800432private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700433 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800434 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700435 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800436 uint32_t mWidth;
437 uint32_t mHeight;
438 Config mConfig;
439};
440
441class Codec2ClientInterfaceWrapper : public C2ComponentStore {
442 std::shared_ptr<Codec2Client> mClient;
443
444public:
445 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
446 : mClient(client) { }
447
448 virtual ~Codec2ClientInterfaceWrapper() = default;
449
450 virtual c2_status_t config_sm(
451 const std::vector<C2Param *> &params,
452 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
453 return mClient->config(params, C2_MAY_BLOCK, failures);
454 };
455
456 virtual c2_status_t copyBuffer(
457 std::shared_ptr<C2GraphicBuffer>,
458 std::shared_ptr<C2GraphicBuffer>) {
459 return C2_OMITTED;
460 }
461
462 virtual c2_status_t createComponent(
463 C2String, std::shared_ptr<C2Component> *const component) {
464 component->reset();
465 return C2_OMITTED;
466 }
467
468 virtual c2_status_t createInterface(
469 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
470 interface->reset();
471 return C2_OMITTED;
472 }
473
474 virtual c2_status_t query_sm(
475 const std::vector<C2Param *> &stackParams,
476 const std::vector<C2Param::Index> &heapParamIndices,
477 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
478 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
479 }
480
481 virtual c2_status_t querySupportedParams_nb(
482 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
483 return mClient->querySupportedParams(params);
484 }
485
486 virtual c2_status_t querySupportedValues_sm(
487 std::vector<C2FieldSupportedValuesQuery> &fields) const {
488 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
489 }
490
491 virtual C2String getName() const {
492 return mClient->getName();
493 }
494
495 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
496 return mClient->getParamReflector();
497 }
498
499 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
500 return std::vector<std::shared_ptr<const C2Component::Traits>>();
501 }
502};
503
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800504void RevertOutputFormatIfNeeded(
505 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
506 // We used to not report changes to these keys to the client.
507 const static std::set<std::string> sIgnoredKeys({
508 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800509 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800510 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800511 KEY_MAX_WIDTH,
512 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800513 "csd-0",
514 "csd-1",
515 "csd-2",
516 });
517 if (currentFormat == oldFormat) {
518 return;
519 }
520 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
521 AMessage::Type type;
522 for (size_t i = diff->countEntries(); i > 0; --i) {
523 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
524 diff->removeEntryAt(i - 1);
525 }
526 }
527 if (diff->countEntries() == 0) {
528 currentFormat = oldFormat;
529 }
530}
531
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700532void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700533 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700534 const sp<AMessage> &outputFormat) {
535 if (mediaType == MIMETYPE_VIDEO_AVC) {
536 // Codec specific data should be SPS and PPS in a single buffer,
537 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
538 // We separate the two and put them into the output format
539 // under the keys "csd-0" and "csd-1".
540
541 unsigned csdIndex = 0;
542
543 const uint8_t *nalStart;
544 size_t nalSize;
545 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
546 sp<ABuffer> csd = new ABuffer(nalSize + 4);
547 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
548 memcpy(csd->data() + 4, nalStart, nalSize);
549
550 outputFormat->setBuffer(
551 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
552
553 ++csdIndex;
554 }
555
556 if (csdIndex != 2) {
557 ALOGW("Expected two NAL units from AVC codec config, but %u found",
558 csdIndex);
559 }
560 } else {
561 // For everything else we just stash the codec specific data into
562 // the output format as a single piece of csd under "csd-0".
563 sp<ABuffer> csd = new ABuffer(size);
564 memcpy(csd->data(), data, size);
565 csd->setRange(0, size);
566 outputFormat->setBuffer("csd-0", csd);
567 }
568}
569
Pawin Vongmasa36653902018-11-15 00:10:25 -0800570} // namespace
571
572// CCodec::ClientListener
573
574struct CCodec::ClientListener : public Codec2Client::Listener {
575
576 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
577
578 virtual void onWorkDone(
579 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800580 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800581 (void)component;
582 sp<CCodec> codec(mCodec.promote());
583 if (!codec) {
584 return;
585 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800586 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800587 }
588
589 virtual void onTripped(
590 const std::weak_ptr<Codec2Client::Component>& component,
591 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
592 ) override {
593 // TODO
594 (void)component;
595 (void)settingResult;
596 }
597
598 virtual void onError(
599 const std::weak_ptr<Codec2Client::Component>& component,
600 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800601 {
602 // Component is only used for reporting as we use a separate listener for each instance
603 std::shared_ptr<Codec2Client::Component> comp = component.lock();
604 if (!comp) {
605 ALOGD("Component died with error: 0x%x", errorCode);
606 } else {
607 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
608 }
609 }
610
611 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800612 // Note: for now we do not propagate the error code to MediaCodec
613 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800614 sp<CCodec> codec(mCodec.promote());
615 if (!codec || !codec->mCallback) {
616 return;
617 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800618 codec->mCallback->onError(
619 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
620 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800621 }
622
623 virtual void onDeath(
624 const std::weak_ptr<Codec2Client::Component>& component) override {
625 { // Log the death of the component.
626 std::shared_ptr<Codec2Client::Component> comp = component.lock();
627 if (!comp) {
628 ALOGE("Codec2 component died.");
629 } else {
630 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
631 }
632 }
633
634 // Report to MediaCodec.
635 sp<CCodec> codec(mCodec.promote());
636 if (!codec || !codec->mCallback) {
637 return;
638 }
639 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
640 }
641
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800642 virtual void onFrameRendered(uint64_t bufferQueueId,
643 int32_t slotId,
644 int64_t timestampNs) override {
645 // TODO: implement
646 (void)bufferQueueId;
647 (void)slotId;
648 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800649 }
650
651 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800652 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800653 sp<CCodec> codec(mCodec.promote());
654 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800655 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800656 }
657 }
658
659private:
660 wp<CCodec> mCodec;
661};
662
663// CCodecCallbackImpl
664
665class CCodecCallbackImpl : public CCodecCallback {
666public:
667 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
668 ~CCodecCallbackImpl() override = default;
669
670 void onError(status_t err, enum ActionCode actionCode) override {
671 mCodec->mCallback->onError(err, actionCode);
672 }
673
674 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
675 mCodec->mCallback->onOutputFramesRendered(
676 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
677 }
678
Pawin Vongmasa36653902018-11-15 00:10:25 -0800679 void onOutputBuffersChanged() override {
680 mCodec->mCallback->onOutputBuffersChanged();
681 }
682
Guillaume Chelfi5ffbcb32021-04-12 14:23:43 +0200683 void onFirstTunnelFrameReady() override {
684 mCodec->mCallback->onFirstTunnelFrameReady();
685 }
686
Pawin Vongmasa36653902018-11-15 00:10:25 -0800687private:
688 CCodec *mCodec;
689};
690
691// CCodec
692
693CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700694 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
695 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800696}
697
698CCodec::~CCodec() {
699}
700
701std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
702 return mChannel;
703}
704
705status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
706 status_t err = job();
707 if (err != C2_OK) {
708 mCallback->onError(err, ACTION_CODE_FATAL);
709 }
710 return err;
711}
712
713void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
714 auto setAllocating = [this] {
715 Mutexed<State>::Locked state(mState);
716 if (state->get() != RELEASED) {
717 return INVALID_OPERATION;
718 }
719 state->set(ALLOCATING);
720 return OK;
721 };
722 if (tryAndReportOnError(setAllocating) != OK) {
723 return;
724 }
725
726 sp<RefBase> codecInfo;
727 CHECK(msg->findObject("codecInfo", &codecInfo));
728 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
729
730 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
731 allocMsg->setObject("codecInfo", codecInfo);
732 allocMsg->post();
733}
734
735void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
736 if (codecInfo == nullptr) {
737 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
738 return;
739 }
740 ALOGD("allocate(%s)", codecInfo->getCodecName());
741 mClientListener.reset(new ClientListener(this));
742
743 AString componentName = codecInfo->getCodecName();
744 std::shared_ptr<Codec2Client> client;
745
746 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700747 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800749 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800750 SetPreferredCodec2ComponentStore(
751 std::make_shared<Codec2ClientInterfaceWrapper>(client));
752 }
753
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900754 std::shared_ptr<Codec2Client::Component> comp;
755 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800756 componentName.c_str(),
757 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900758 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900760 if (status != C2_OK) {
761 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800762 Mutexed<State>::Locked state(mState);
763 state->set(RELEASED);
764 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900765 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800766 state.lock();
767 return;
768 }
769 ALOGI("Created component [%s]", componentName.c_str());
770 mChannel->setComponent(comp);
771 auto setAllocated = [this, comp, client] {
772 Mutexed<State>::Locked state(mState);
773 if (state->get() != ALLOCATING) {
774 state->set(RELEASED);
775 return UNKNOWN_ERROR;
776 }
777 state->set(ALLOCATED);
778 state->comp = comp;
779 mClient = client;
780 return OK;
781 };
782 if (tryAndReportOnError(setAllocated) != OK) {
783 return;
784 }
785
786 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700787 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
788 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800789 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800790 if (err != OK) {
791 ALOGW("Failed to initialize configuration support");
792 // TODO: report error once we complete implementation.
793 }
794 config->queryConfiguration(comp);
795
796 mCallback->onComponentAllocated(componentName.c_str());
797}
798
799void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
800 auto checkAllocated = [this] {
801 Mutexed<State>::Locked state(mState);
802 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
803 };
804 if (tryAndReportOnError(checkAllocated) != OK) {
805 return;
806 }
807
808 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
809 msg->setMessage("format", format);
810 msg->post();
811}
812
813void CCodec::configure(const sp<AMessage> &msg) {
814 std::shared_ptr<Codec2Client::Component> comp;
815 auto checkAllocated = [this, &comp] {
816 Mutexed<State>::Locked state(mState);
817 if (state->get() != ALLOCATED) {
818 state->set(RELEASED);
819 return UNKNOWN_ERROR;
820 }
821 comp = state->comp;
822 return OK;
823 };
824 if (tryAndReportOnError(checkAllocated) != OK) {
825 return;
826 }
827
828 auto doConfig = [msg, comp, this]() -> status_t {
829 AString mime;
830 if (!msg->findString("mime", &mime)) {
831 return BAD_VALUE;
832 }
833
834 int32_t encoder;
835 if (!msg->findInt32("encoder", &encoder)) {
836 encoder = false;
837 }
838
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800839 int32_t flags;
840 if (!msg->findInt32("flags", &flags)) {
841 return BAD_VALUE;
842 }
843
Pawin Vongmasa36653902018-11-15 00:10:25 -0800844 // TODO: read from intf()
845 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
846 return UNKNOWN_ERROR;
847 }
848
849 int32_t storeMeta;
850 if (encoder
851 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
852 && storeMeta != kMetadataBufferTypeInvalid) {
853 if (storeMeta != kMetadataBufferTypeANWBuffer) {
854 ALOGD("Only ANW buffers are supported for legacy metadata mode");
855 return BAD_VALUE;
856 }
857 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
858 }
859
ted.sun765db4d2020-06-23 14:03:41 +0800860 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800861 sp<RefBase> obj;
862 sp<Surface> surface;
863 if (msg->findObject("native-window", &obj)) {
864 surface = static_cast<Surface *>(obj.get());
ted.sun765db4d2020-06-23 14:03:41 +0800865 // setup tunneled playback
866 if (surface != nullptr) {
867 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
868 const std::unique_ptr<Config> &config = *configLocked;
869 if ((config->mDomain & Config::IS_DECODER)
870 && (config->mDomain & Config::IS_VIDEO)) {
871 int32_t tunneled;
872 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
873 ALOGI("Configuring TUNNELED video playback.");
874
875 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
876 if (err != OK) {
877 ALOGE("configureTunneledVideoPlayback failed!");
878 return err;
879 }
880 config->mTunneled = true;
881 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +0100882
883 int32_t pushBlankBuffersOnStop = 0;
884 if (msg->findInt32(KEY_PUSH_BLANK_BUFFERS_ON_STOP, &pushBlankBuffersOnStop)) {
885 config->mPushBlankBuffersOnStop = pushBlankBuffersOnStop == 1;
886 }
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 }
1811 sp<AMessage> inputFormat;
1812 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001813 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001814 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001815 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001816 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1817 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001818 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001819 // start triggers format dup
1820 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001821 if (config->mInputSurface) {
1822 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001823 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001824 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001825 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001826 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001827 if (err2 != OK) {
1828 mCallback->onError(err2, ACTION_CODE_FATAL);
1829 return;
1830 }
Arun Johnson106fe7a2023-04-26 17:49:43 +00001831
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001832 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001833 if (err2 != OK) {
1834 mCallback->onError(err2, ACTION_CODE_FATAL);
1835 return;
1836 }
1837
1838 auto setRunning = [this] {
1839 Mutexed<State>::Locked state(mState);
1840 if (state->get() != STARTING) {
1841 return UNKNOWN_ERROR;
1842 }
1843 state->set(RUNNING);
1844 return OK;
1845 };
1846 if (tryAndReportOnError(setRunning) != OK) {
1847 return;
1848 }
Arun Johnson5997bb02022-04-01 19:35:44 +00001849
Wonsik Kim34b28b42022-05-20 15:49:32 -07001850 // preparation of input buffers may not succeed due to the lack of
1851 // memory; returning correct error code (NO_MEMORY) as an error allows
1852 // MediaCodec to try reclaim and restart codec gracefully.
1853 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
1854 err2 = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
1855 if (err2 != OK) {
1856 ALOGE("Initial preparation for Input Buffers failed");
1857 mCallback->onError(err2, ACTION_CODE_FATAL);
1858 return;
1859 }
1860
Pawin Vongmasa36653902018-11-15 00:10:25 -08001861 mCallback->onStartCompleted();
1862
Wonsik Kim34b28b42022-05-20 15:49:32 -07001863 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001864}
1865
1866void CCodec::initiateShutdown(bool keepComponentAllocated) {
1867 if (keepComponentAllocated) {
1868 initiateStop();
1869 } else {
1870 initiateRelease();
1871 }
1872}
1873
1874void CCodec::initiateStop() {
1875 {
1876 Mutexed<State>::Locked state(mState);
1877 if (state->get() == ALLOCATED
1878 || state->get() == RELEASED
1879 || state->get() == STOPPING
1880 || state->get() == RELEASING) {
1881 // We're already stopped, released, or doing it right now.
1882 state.unlock();
1883 mCallback->onStopCompleted();
1884 state.lock();
1885 return;
1886 }
1887 state->set(STOPPING);
1888 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001889 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00001890 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
1891 sp<AMessage> stopMessage(new AMessage(kWhatStop, this));
1892 stopMessage->setInt32("pushBlankBuffer", pushBlankBuffer);
1893 stopMessage->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001894}
1895
Sungtak Lee99144332023-01-26 11:03:14 +00001896void CCodec::stop(bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001897 std::shared_ptr<Codec2Client::Component> comp;
1898 {
1899 Mutexed<State>::Locked state(mState);
1900 if (state->get() == RELEASING) {
1901 state.unlock();
1902 // We're already stopped or release is in progress.
1903 mCallback->onStopCompleted();
1904 state.lock();
1905 return;
1906 } else if (state->get() != STOPPING) {
1907 state.unlock();
1908 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1909 state.lock();
1910 return;
1911 }
1912 comp = state->comp;
1913 }
1914 status_t err = comp->stop();
Sungtak Lee99144332023-01-26 11:03:14 +00001915 mChannel->stopUseOutputSurface(pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001916 if (err != C2_OK) {
1917 // TODO: convert err into status_t
1918 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1919 }
1920
1921 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001922 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1923 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001924 if (config->mInputSurface) {
1925 config->mInputSurface->disconnect();
1926 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001927 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001928 }
1929 }
1930 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001931 Mutexed<State>::Locked state(mState);
1932 if (state->get() == STOPPING) {
1933 state->set(ALLOCATED);
1934 }
1935 }
1936 mCallback->onStopCompleted();
1937}
1938
1939void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001940 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001941 {
1942 Mutexed<State>::Locked state(mState);
1943 if (state->get() == RELEASED || state->get() == RELEASING) {
1944 // We're already released or doing it right now.
1945 if (sendCallback) {
1946 state.unlock();
1947 mCallback->onReleaseCompleted();
1948 state.lock();
1949 }
1950 return;
1951 }
1952 if (state->get() == ALLOCATING) {
1953 state->set(RELEASING);
1954 // With the altered state allocate() would fail and clean up.
1955 if (sendCallback) {
1956 state.unlock();
1957 mCallback->onReleaseCompleted();
1958 state.lock();
1959 }
1960 return;
1961 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001962 if (state->get() == STARTING
1963 || state->get() == RUNNING
1964 || state->get() == STOPPING) {
1965 // Input surface may have been started, so clean up is needed.
1966 clearInputSurfaceIfNeeded = true;
1967 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001968 state->set(RELEASING);
1969 }
1970
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001971 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001972 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1973 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001974 if (config->mInputSurface) {
1975 config->mInputSurface->disconnect();
1976 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001977 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001978 }
1979 }
1980
Wonsik Kim936a89c2020-05-08 16:07:50 -07001981 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00001982 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001983 // thiz holds strong ref to this while the thread is running.
1984 sp<CCodec> thiz(this);
Sungtak Lee99144332023-01-26 11:03:14 +00001985 std::thread([thiz, sendCallback, pushBlankBuffer]
1986 { thiz->release(sendCallback, pushBlankBuffer); }).detach();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001987}
1988
Sungtak Lee99144332023-01-26 11:03:14 +00001989void CCodec::release(bool sendCallback, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001990 std::shared_ptr<Codec2Client::Component> comp;
1991 {
1992 Mutexed<State>::Locked state(mState);
1993 if (state->get() == RELEASED) {
1994 if (sendCallback) {
1995 state.unlock();
1996 mCallback->onReleaseCompleted();
1997 state.lock();
1998 }
1999 return;
2000 }
2001 comp = state->comp;
2002 }
2003 comp->release();
Sungtak Lee99144332023-01-26 11:03:14 +00002004 mChannel->stopUseOutputSurface(pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002005
2006 {
2007 Mutexed<State>::Locked state(mState);
2008 state->set(RELEASED);
2009 state->comp.reset();
2010 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002011 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002012 if (sendCallback) {
2013 mCallback->onReleaseCompleted();
2014 }
2015}
2016
2017status_t CCodec::setSurface(const sp<Surface> &surface) {
Sungtak Lee99144332023-01-26 11:03:14 +00002018 bool pushBlankBuffer = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002019 {
2020 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2021 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002022 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
2023 status_t err = OK;
2024
Wonsik Kim75e22f42021-04-14 23:34:51 -07002025 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002026 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07002027 nativeWindow.get(),
2028 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
2029 if (err != OK) {
2030 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
2031 nativeWindow.get(), config->mSidebandHandle->handle(), err);
2032 return err;
2033 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002034 } else {
2035 // Explicitly reset the sideband handle of the window for
2036 // non-tunneled video in case the window was previously used
2037 // for a tunneled video playback.
2038 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
2039 if (err != OK) {
2040 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
2041 return err;
2042 }
ted.sun765db4d2020-06-23 14:03:41 +08002043 }
Sungtak Lee99144332023-01-26 11:03:14 +00002044 pushBlankBuffer = config->mPushBlankBuffersOnStop;
ted.sun765db4d2020-06-23 14:03:41 +08002045 }
Sungtak Lee99144332023-01-26 11:03:14 +00002046 return mChannel->setSurface(surface, pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002047}
2048
2049void CCodec::signalFlush() {
2050 status_t err = [this] {
2051 Mutexed<State>::Locked state(mState);
2052 if (state->get() == FLUSHED) {
2053 return ALREADY_EXISTS;
2054 }
2055 if (state->get() != RUNNING) {
2056 return UNKNOWN_ERROR;
2057 }
2058 state->set(FLUSHING);
2059 return OK;
2060 }();
2061 switch (err) {
2062 case ALREADY_EXISTS:
2063 mCallback->onFlushCompleted();
2064 return;
2065 case OK:
2066 break;
2067 default:
2068 mCallback->onError(err, ACTION_CODE_FATAL);
2069 return;
2070 }
2071
2072 mChannel->stop();
2073 (new AMessage(kWhatFlush, this))->post();
2074}
2075
2076void CCodec::flush() {
2077 std::shared_ptr<Codec2Client::Component> comp;
2078 auto checkFlushing = [this, &comp] {
2079 Mutexed<State>::Locked state(mState);
2080 if (state->get() != FLUSHING) {
2081 return UNKNOWN_ERROR;
2082 }
2083 comp = state->comp;
2084 return OK;
2085 };
2086 if (tryAndReportOnError(checkFlushing) != OK) {
2087 return;
2088 }
2089
2090 std::list<std::unique_ptr<C2Work>> flushedWork;
2091 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2092 {
2093 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2094 flushedWork.splice(flushedWork.end(), *queue);
2095 }
2096 if (err != C2_OK) {
2097 // TODO: convert err into status_t
2098 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2099 }
2100
2101 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002102
2103 {
2104 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002105 if (state->get() == FLUSHING) {
2106 state->set(FLUSHED);
2107 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002108 }
2109 mCallback->onFlushCompleted();
2110}
2111
2112void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002113 std::shared_ptr<Codec2Client::Component> comp;
2114 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002115 Mutexed<State>::Locked state(mState);
2116 if (state->get() != FLUSHED) {
2117 return UNKNOWN_ERROR;
2118 }
2119 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002120 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002121 return OK;
2122 };
2123 if (tryAndReportOnError(setResuming) != OK) {
2124 return;
2125 }
2126
Wonsik Kime75a5da2020-02-14 17:29:03 -08002127 {
2128 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2129 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002130 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002131 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002132 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002133 }
2134
Arun Johnson106fe7a2023-04-26 17:49:43 +00002135 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
2136 status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
2137 if (err != OK) {
2138 if (err == NO_MEMORY) {
2139 // NO_MEMORY happens here when all the buffers are still
2140 // with the codec. That is not an error as it is momentarily
2141 // and the buffers are send to the client as soon as the codec
2142 // releases them
2143 ALOGI("Resuming with all input buffers still with codec");
2144 } else {
2145 ALOGE("Resume request for Input Buffers failed");
2146 mCallback->onError(err, ACTION_CODE_FATAL);
2147 return;
2148 }
2149 }
2150
2151 // channel start should be called after prepareInitialBuffers
2152 // Calling before can cause a failure during prepare when
2153 // buffers are sent to the client before preparation from onWorkDone
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002154 (void)mChannel->start(nullptr, nullptr, [&]{
2155 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2156 const std::unique_ptr<Config> &config = *configLocked;
2157 return config->mBuffersBoundToCodec;
2158 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002159
2160 {
2161 Mutexed<State>::Locked state(mState);
2162 if (state->get() != RESUMING) {
2163 state.unlock();
2164 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2165 state.lock();
2166 return;
2167 }
2168 state->set(RUNNING);
2169 }
2170
Wonsik Kim34b28b42022-05-20 15:49:32 -07002171 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002172}
2173
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002174void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002175 std::shared_ptr<Codec2Client::Component> comp;
2176 auto checkState = [this, &comp] {
2177 Mutexed<State>::Locked state(mState);
2178 if (state->get() == RELEASED) {
2179 return INVALID_OPERATION;
2180 }
2181 comp = state->comp;
2182 return OK;
2183 };
2184 if (tryAndReportOnError(checkState) != OK) {
2185 return;
2186 }
2187
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002188 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2189 // the behavior here.
2190 sp<AMessage> params = msg;
2191 int32_t bitrate;
2192 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2193 params = msg->dup();
2194 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2195 }
2196
Houxiang Dai5a97b472021-03-22 17:56:04 +08002197 int32_t syncId = 0;
2198 if (params->findInt32("audio-hw-sync", &syncId)
2199 || params->findInt32("hw-av-sync-id", &syncId)) {
2200 configureTunneledVideoPlayback(comp, nullptr, params);
2201 }
2202
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002203 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2204 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002205
2206 /**
2207 * Handle input surface parameters
2208 */
2209 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002210 && (config->mDomain & Config::IS_ENCODER)
2211 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002212 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002213
2214 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2215 config->mISConfig->mStopped = false;
2216 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2217 config->mISConfig->mStopped = true;
2218 }
2219
2220 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002221 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002222 config->mISConfig->mSuspended = value;
2223 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002224 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002225 }
2226
2227 (void)config->mInputSurface->configure(*config->mISConfig);
2228 if (config->mISConfig->mStopped) {
2229 config->mInputFormat->setInt64(
2230 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2231 }
2232 }
2233
2234 std::vector<std::unique_ptr<C2Param>> configUpdate;
2235 (void)config->getConfigUpdateFromSdkParams(
2236 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2237 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2238 // Parameter synchronization is not defined when using input surface. For now, route
2239 // these directly to the component.
2240 if (config->mInputSurface == nullptr
2241 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2242 || comp->getName().find("c2.android.") == 0)) {
2243 mChannel->setParameters(configUpdate);
2244 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002245 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002246 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002247 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002248 }
2249}
2250
2251void CCodec::signalEndOfInputStream() {
2252 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2253}
2254
2255void CCodec::signalRequestIDRFrame() {
2256 std::shared_ptr<Codec2Client::Component> comp;
2257 {
2258 Mutexed<State>::Locked state(mState);
2259 if (state->get() == RELEASED) {
2260 ALOGD("no IDR request sent since component is released");
2261 return;
2262 }
2263 comp = state->comp;
2264 }
2265 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002266 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2267 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002268 std::vector<std::unique_ptr<C2Param>> params;
2269 params.push_back(
2270 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2271 config->setParameters(comp, params, C2_MAY_BLOCK);
2272}
2273
Wonsik Kim874ad382021-03-12 09:59:36 -08002274status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2275 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2276 const std::unique_ptr<Config> &config = *configLocked;
2277 return config->querySupportedParameters(names);
2278}
2279
2280status_t CCodec::describeParameter(
2281 const std::string &name, CodecParameterDescriptor *desc) {
2282 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2283 const std::unique_ptr<Config> &config = *configLocked;
2284 return config->describe(name, desc);
2285}
2286
2287status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2288 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2289 if (!comp) {
2290 return INVALID_OPERATION;
2291 }
2292 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2293 const std::unique_ptr<Config> &config = *configLocked;
2294 return config->subscribeToVendorConfigUpdate(comp, names);
2295}
2296
2297status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2298 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2299 if (!comp) {
2300 return INVALID_OPERATION;
2301 }
2302 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2303 const std::unique_ptr<Config> &config = *configLocked;
2304 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2305}
2306
Wonsik Kimab34ed62019-01-31 15:28:46 -08002307void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002308 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002309 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2310 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002311 }
2312 (new AMessage(kWhatWorkDone, this))->post();
2313}
2314
Wonsik Kimab34ed62019-01-31 15:28:46 -08002315void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2316 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002317 if (arrayIndex == 0) {
2318 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002319 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2320 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002321 if (config->mInputSurface) {
2322 config->mInputSurface->onInputBufferDone(frameIndex);
2323 }
2324 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002325}
2326
2327void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2328 TimePoint now = std::chrono::steady_clock::now();
2329 CCodecWatchdog::getInstance()->watch(this);
2330 switch (msg->what()) {
2331 case kWhatAllocate: {
2332 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002333 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002334 sp<RefBase> obj;
2335 CHECK(msg->findObject("codecInfo", &obj));
2336 allocate((MediaCodecInfo *)obj.get());
2337 break;
2338 }
2339 case kWhatConfigure: {
2340 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002341 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002342 sp<AMessage> format;
2343 CHECK(msg->findMessage("format", &format));
2344 configure(format);
2345 break;
2346 }
2347 case kWhatStart: {
2348 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002349 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002350 start();
2351 break;
2352 }
2353 case kWhatStop: {
2354 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002355 setDeadline(now, 1500ms, "stop");
Sungtak Lee99144332023-01-26 11:03:14 +00002356 int32_t pushBlankBuffer;
2357 if (!msg->findInt32("pushBlankBuffer", &pushBlankBuffer)) {
2358 pushBlankBuffer = 0;
2359 }
2360 stop(static_cast<bool>(pushBlankBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002361 break;
2362 }
2363 case kWhatFlush: {
2364 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002365 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002366 flush();
2367 break;
2368 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002369 case kWhatRelease: {
2370 mChannel->release();
2371 mClient.reset();
2372 mClientListener.reset();
2373 break;
2374 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002375 case kWhatCreateInputSurface: {
2376 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002377 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002378 createInputSurface();
2379 break;
2380 }
2381 case kWhatSetInputSurface: {
2382 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002383 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002384 sp<RefBase> obj;
2385 CHECK(msg->findObject("surface", &obj));
2386 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2387 setInputSurface(surface);
2388 break;
2389 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002390 case kWhatWorkDone: {
2391 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002392 bool shouldPost = false;
2393 {
2394 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2395 if (queue->empty()) {
2396 break;
2397 }
2398 work.swap(queue->front());
2399 queue->pop_front();
2400 shouldPost = !queue->empty();
2401 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002402 if (shouldPost) {
2403 (new AMessage(kWhatWorkDone, this))->post();
2404 }
2405
Pawin Vongmasa36653902018-11-15 00:10:25 -08002406 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002407 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002408 sp<AMessage> outputFormat = nullptr;
2409 {
2410 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2411 const std::unique_ptr<Config> &config = *configLocked;
2412 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2413 config->watch<C2StreamInitDataInfo::output>();
2414 if (!work->worklets.empty()
2415 && (work->worklets.front()->output.flags
2416 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002417
Wonsik Kim75e22f42021-04-14 23:34:51 -07002418 // copy buffer info to config
2419 std::vector<std::unique_ptr<C2Param>> updates;
2420 for (const std::unique_ptr<C2Param> &param
2421 : work->worklets.front()->output.configUpdate) {
2422 updates.push_back(C2Param::Copy(*param));
2423 }
2424 unsigned stream = 0;
2425 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2426 work->worklets.front()->output.buffers;
2427 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2428 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2429 // move all info into output-stream #0 domain
2430 updates.emplace_back(
2431 C2Param::CopyAsStream(*info, true /* output */, stream));
2432 }
2433
2434 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2435 // for now only do the first block
2436 if (!blocks.empty()) {
2437 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2438 // block.crop().left, block.crop().top,
2439 // block.crop().width, block.crop().height,
2440 // block.width(), block.height());
2441 const C2ConstGraphicBlock &block = blocks[0];
2442 updates.emplace_back(new C2StreamCropRectInfo::output(
2443 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002444 }
2445 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002446 }
George Burgess IVc813a592020-02-22 22:54:44 -08002447
Wonsik Kim75e22f42021-04-14 23:34:51 -07002448 sp<AMessage> oldFormat = config->mOutputFormat;
2449 config->updateConfiguration(updates, config->mOutputDomain);
2450 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002451
Wonsik Kim75e22f42021-04-14 23:34:51 -07002452 // copy standard infos to graphic buffers if not already present (otherwise, we
2453 // may overwrite the actual intermediate value with a final value)
2454 stream = 0;
2455 const static C2Param::Index stdGfxInfos[] = {
2456 C2StreamRotationInfo::output::PARAM_TYPE,
2457 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2458 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2459 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Taehwan Kim2d222b82022-05-12 14:19:26 +09002460 C2StreamHdr10PlusInfo::output::PARAM_TYPE, // will be deprecated
2461 C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE,
Wonsik Kim75e22f42021-04-14 23:34:51 -07002462 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2463 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2464 };
2465 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2466 if (buf->data().graphicBlocks().size()) {
2467 for (C2Param::Index ix : stdGfxInfos) {
2468 if (!buf->hasInfo(ix)) {
2469 const C2Param *param =
2470 config->getConfigParameterValue(ix.withStream(stream));
2471 if (param) {
2472 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2473 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2474 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002475 }
2476 }
2477 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002478 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002479 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002480 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002481 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302482 if (work->worklets.empty()
2483 || !work->worklets.back()
2484 || (work->worklets.back()->output.flags
2485 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2486 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2487 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002488 }
2489 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002490 initData = initDataWatcher.update();
2491 AmendOutputFormatWithCodecSpecificData(
2492 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2493 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002494 }
2495 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002496 }
2497 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002498 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002499 break;
2500 }
2501 case kWhatWatch: {
2502 // watch message already posted; no-op.
2503 break;
2504 }
2505 default: {
2506 ALOGE("unrecognized message");
2507 break;
2508 }
2509 }
2510 setDeadline(TimePoint::max(), 0ms, "none");
2511}
2512
2513void CCodec::setDeadline(
2514 const TimePoint &now,
2515 const std::chrono::milliseconds &timeout,
2516 const char *name) {
2517 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2518 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2519 deadline->set(now + (timeout * mult), name);
2520}
2521
ted.sun765db4d2020-06-23 14:03:41 +08002522status_t CCodec::configureTunneledVideoPlayback(
2523 std::shared_ptr<Codec2Client::Component> comp,
2524 sp<NativeHandle> *sidebandHandle,
2525 const sp<AMessage> &msg) {
2526 std::vector<std::unique_ptr<C2SettingResult>> failures;
2527
2528 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2529 C2PortTunneledModeTuning::output::AllocUnique(
2530 1,
2531 C2PortTunneledModeTuning::Struct::SIDEBAND,
2532 C2PortTunneledModeTuning::Struct::REALTIME,
2533 0);
2534 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2535 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2536 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2537 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2538 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2539 } else {
2540 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2541 tunneledPlayback->setFlexCount(0);
2542 }
2543 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2544 if (c2err != C2_OK) {
2545 return UNKNOWN_ERROR;
2546 }
2547
Houxiang Dai5a97b472021-03-22 17:56:04 +08002548 if (sidebandHandle == nullptr) {
2549 return OK;
2550 }
2551
ted.sun765db4d2020-06-23 14:03:41 +08002552 std::vector<std::unique_ptr<C2Param>> params;
2553 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2554 if (c2err == C2_OK && params.size() == 1u) {
2555 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2556 C2PortTunnelHandleTuning::output::From(params[0].get());
2557 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2558 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2559 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2560 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2561 memcpy(handle->data, videoTunnelSideband->m.values,
2562 sizeof(int32_t) * videoTunnelSideband->flexCount());
2563 return OK;
2564 } else {
2565 return NO_MEMORY;
2566 }
2567 }
2568 return UNKNOWN_ERROR;
2569}
2570
Pawin Vongmasa36653902018-11-15 00:10:25 -08002571void CCodec::initiateReleaseIfStuck() {
Wonsik Kim75e22f42021-04-14 23:34:51 -07002572 bool tunneled = false;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002573 bool isMediaTypeKnown = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002574 {
Wonsik Kimabca11e2021-04-30 13:11:41 -07002575 static const std::set<std::string> kKnownMediaTypes{
2576 MIMETYPE_VIDEO_VP8,
2577 MIMETYPE_VIDEO_VP9,
2578 MIMETYPE_VIDEO_AV1,
2579 MIMETYPE_VIDEO_AVC,
2580 MIMETYPE_VIDEO_HEVC,
2581 MIMETYPE_VIDEO_MPEG4,
2582 MIMETYPE_VIDEO_H263,
2583 MIMETYPE_VIDEO_MPEG2,
2584 MIMETYPE_VIDEO_RAW,
2585 MIMETYPE_VIDEO_DOLBY_VISION,
2586
2587 MIMETYPE_AUDIO_AMR_NB,
2588 MIMETYPE_AUDIO_AMR_WB,
2589 MIMETYPE_AUDIO_MPEG,
2590 MIMETYPE_AUDIO_AAC,
2591 MIMETYPE_AUDIO_QCELP,
2592 MIMETYPE_AUDIO_VORBIS,
2593 MIMETYPE_AUDIO_OPUS,
2594 MIMETYPE_AUDIO_G711_ALAW,
2595 MIMETYPE_AUDIO_G711_MLAW,
2596 MIMETYPE_AUDIO_RAW,
2597 MIMETYPE_AUDIO_FLAC,
2598 MIMETYPE_AUDIO_MSGSM,
2599 MIMETYPE_AUDIO_AC3,
2600 MIMETYPE_AUDIO_EAC3,
2601
2602 MIMETYPE_IMAGE_ANDROID_HEIC,
2603 };
Wonsik Kim75e22f42021-04-14 23:34:51 -07002604 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2605 const std::unique_ptr<Config> &config = *configLocked;
2606 tunneled = config->mTunneled;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002607 isMediaTypeKnown = (kKnownMediaTypes.count(config->mCodingMediaType) != 0);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002608 }
Shrikara B3b87a532022-08-26 14:18:14 +05302609 std::string name;
2610 bool pendingDeadline = false;
2611 {
2612 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2613 if (deadline->get() < std::chrono::steady_clock::now()) {
2614 name = deadline->getName();
2615 }
2616 if (deadline->get() != TimePoint::max()) {
2617 pendingDeadline = true;
2618 }
2619 }
Wonsik Kimabca11e2021-04-30 13:11:41 -07002620 if (!tunneled && isMediaTypeKnown && name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002621 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2622 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2623 if (elapsed >= kWorkDurationThreshold) {
2624 name = "queue";
2625 }
2626 if (elapsed > 0s) {
2627 pendingDeadline = true;
2628 }
2629 }
2630 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002631 // We're not stuck.
2632 if (pendingDeadline) {
2633 // If we are not stuck yet but still has deadline coming up,
2634 // post watch message to check back later.
2635 (new AMessage(kWhatWatch, this))->post();
2636 }
2637 return;
2638 }
2639
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002640 C2String compName;
2641 {
2642 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002643 if (!state->comp) {
2644 ALOGD("previous call to %s exceeded timeout "
2645 "and the component is already released", name.c_str());
2646 return;
2647 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002648 compName = state->comp->getName();
2649 }
2650 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2651
Pawin Vongmasa36653902018-11-15 00:10:25 -08002652 initiateRelease(false);
2653 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2654}
2655
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002656// static
2657PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002658 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002659 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002660 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002661 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2662 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002663 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002664 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2665 sp<IGraphicBufferProducer> gbp;
2666 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2667 status_t err = gbs->initCheck();
2668 if (err != OK) {
2669 ALOGE("Failed to create persistent input surface: error %d", err);
2670 return nullptr;
2671 }
2672 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002673 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002674 } else {
2675 return nullptr;
2676 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002677 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002678 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002679 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002680 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002681 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002682}
2683
Wonsik Kimffb889a2020-05-28 11:32:25 -07002684class IntfCache {
2685public:
2686 IntfCache() = default;
2687
2688 status_t init(const std::string &name) {
2689 std::shared_ptr<Codec2Client::Interface> intf{
2690 Codec2Client::CreateInterfaceByName(name.c_str())};
2691 if (!intf) {
2692 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2693 mInitStatus = NO_INIT;
2694 return NO_INIT;
2695 }
2696 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2697 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2698 C2ParamField{&sUsage, &sUsage.value}));
2699 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2700 if (err != C2_OK) {
2701 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2702 name.c_str(), err);
2703 mFields[0].status = err;
2704 }
2705 std::vector<std::unique_ptr<C2Param>> params;
2706 err = intf->query(
2707 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09002708 {
2709 C2StreamBufferTypeSetting::input::PARAM_TYPE,
2710 C2PortAllocatorsTuning::input::PARAM_TYPE
2711 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07002712 C2_MAY_BLOCK,
2713 &params);
2714 if (err != C2_OK && err != C2_BAD_INDEX) {
2715 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2716 name.c_str(), err);
2717 }
2718 while (!params.empty()) {
2719 C2Param *param = params.back().release();
2720 params.pop_back();
2721 if (!param) {
2722 continue;
2723 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002724 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
2725 mInputStreamFormat.reset(
2726 C2StreamBufferTypeSetting::input::From(param));
2727 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002728 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002729 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002730 }
2731 }
2732 mInitStatus = OK;
2733 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002734 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002735
2736 status_t initCheck() const { return mInitStatus; }
2737
2738 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2739 CHECK_EQ(1u, mFields.size());
2740 return mFields[0];
2741 }
2742
2743 const C2ApiFeaturesSetting &getApiFeatures() const {
2744 return mApiFeatures;
2745 }
2746
Taehwan Kim900b49c2021-12-13 11:16:22 +09002747 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
2748 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
2749 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
2750 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
2751 param->invalidate();
2752 return param;
2753 }();
2754 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
2755 }
2756
Wonsik Kimffb889a2020-05-28 11:32:25 -07002757 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2758 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2759 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2760 C2PortAllocatorsTuning::input::AllocUnique(0);
2761 param->invalidate();
2762 return param;
2763 }();
2764 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2765 }
2766
2767private:
2768 status_t mInitStatus{NO_INIT};
2769
2770 std::vector<C2FieldSupportedValuesQuery> mFields;
2771 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09002772 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002773 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2774};
2775
2776static const IntfCache &GetIntfCache(const std::string &name) {
2777 static IntfCache sNullIntfCache;
2778 static std::mutex sMutex;
2779 static std::map<std::string, IntfCache> sCache;
2780 std::unique_lock<std::mutex> lock{sMutex};
2781 auto it = sCache.find(name);
2782 if (it == sCache.end()) {
2783 lock.unlock();
2784 IntfCache intfCache;
2785 status_t err = intfCache.init(name);
2786 if (err != OK) {
2787 return sNullIntfCache;
2788 }
2789 lock.lock();
2790 it = sCache.insert({name, std::move(intfCache)}).first;
2791 }
2792 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002793}
2794
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002795static status_t GetCommonAllocatorIds(
2796 const std::vector<std::string> &names,
2797 C2Allocator::type_t type,
2798 std::set<C2Allocator::id_t> *ids) {
2799 int poolMask = GetCodec2PoolMask();
2800 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2801 C2Allocator::id_t defaultAllocatorId =
2802 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2803
2804 ids->clear();
2805 if (names.empty()) {
2806 return OK;
2807 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002808 bool firstIteration = true;
2809 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002810 const IntfCache &intfCache = GetIntfCache(name);
2811 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002812 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002813 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002814 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
2815 if (streamFormat) {
2816 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
2817 if (streamFormat.value == C2BufferData::GRAPHIC
2818 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
2819 allocatorType = C2Allocator::GRAPHIC;
2820 }
2821
2822 if (type != allocatorType) {
2823 // requested type is not supported at input allocators
2824 ids->clear();
2825 ids->insert(defaultAllocatorId);
2826 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
2827 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
2828 break;
2829 }
2830 }
2831
Wonsik Kimffb889a2020-05-28 11:32:25 -07002832 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002833 if (firstIteration) {
2834 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002835 if (allocators && allocators.flexCount() > 0) {
2836 ids->insert(allocators.m.values,
2837 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002838 }
2839 if (ids->empty()) {
2840 // The component does not advertise allocators. Use default.
2841 ids->insert(defaultAllocatorId);
2842 }
2843 continue;
2844 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002845 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002846 if (allocators && allocators.flexCount() > 0) {
2847 filtered = true;
2848 for (auto it = ids->begin(); it != ids->end(); ) {
2849 bool found = false;
2850 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2851 if (allocators.m.values[j] == *it) {
2852 found = true;
2853 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002854 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002855 }
2856 if (found) {
2857 ++it;
2858 } else {
2859 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002860 }
2861 }
2862 }
2863 if (!filtered) {
2864 // The component does not advertise supported allocators. Use default.
2865 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2866 if (ids->size() != (containsDefault ? 1 : 0)) {
2867 ids->clear();
2868 if (containsDefault) {
2869 ids->insert(defaultAllocatorId);
2870 }
2871 }
2872 }
2873 }
2874 // Finally, filter with pool masks
2875 for (auto it = ids->begin(); it != ids->end(); ) {
2876 if ((poolMask >> *it) & 1) {
2877 ++it;
2878 } else {
2879 it = ids->erase(it);
2880 }
2881 }
2882 return OK;
2883}
2884
2885static status_t CalculateMinMaxUsage(
2886 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2887 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2888 *minUsage = 0;
2889 *maxUsage = ~0ull;
2890 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002891 const IntfCache &intfCache = GetIntfCache(name);
2892 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002893 continue;
2894 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002895 const C2FieldSupportedValuesQuery &usageSupportedValues =
2896 intfCache.getUsageSupportedValues();
2897 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002898 continue;
2899 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002900 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002901 if (supported.type != C2FieldSupportedValues::FLAGS) {
2902 continue;
2903 }
2904 if (supported.values.empty()) {
2905 *maxUsage = 0;
2906 continue;
2907 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08002908 if (supported.values.size() > 1) {
2909 *minUsage |= supported.values[1].u64;
2910 } else {
2911 *minUsage |= supported.values[0].u64;
2912 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002913 int64_t currentMaxUsage = 0;
2914 for (const C2Value::Primitive &flags : supported.values) {
2915 currentMaxUsage |= flags.u64;
2916 }
2917 *maxUsage &= currentMaxUsage;
2918 }
2919 return OK;
2920}
2921
2922// static
2923status_t CCodec::CanFetchLinearBlock(
2924 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002925 for (const std::string &name : names) {
2926 const IntfCache &intfCache = GetIntfCache(name);
2927 if (intfCache.initCheck() != OK) {
2928 continue;
2929 }
2930 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2931 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2932 *isCompatible = false;
2933 return OK;
2934 }
2935 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002936 std::set<C2Allocator::id_t> allocators;
2937 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2938 if (allocators.empty()) {
2939 *isCompatible = false;
2940 return OK;
2941 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002942
2943 uint64_t minUsage = 0;
2944 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002945 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002946 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002947 *isCompatible = ((maxUsage & minUsage) == minUsage);
2948 return OK;
2949}
2950
2951static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2952 static std::mutex sMutex{};
2953 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2954 std::unique_lock<std::mutex> lock{sMutex};
2955 std::shared_ptr<C2BlockPool> pool;
2956 auto it = sPools.find(allocId);
2957 if (it == sPools.end()) {
2958 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2959 if (err == OK) {
2960 sPools.emplace(allocId, pool);
2961 } else {
2962 pool.reset();
2963 }
2964 } else {
2965 pool = it->second;
2966 }
2967 return pool;
2968}
2969
2970// static
2971std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2972 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002973 std::set<C2Allocator::id_t> allocators;
2974 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2975 if (allocators.empty()) {
2976 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2977 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002978
2979 uint64_t minUsage = 0;
2980 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002981 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002982 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002983 if ((maxUsage & minUsage) != minUsage) {
2984 allocators.clear();
2985 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2986 }
2987 std::shared_ptr<C2LinearBlock> block;
2988 for (C2Allocator::id_t allocId : allocators) {
2989 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2990 if (!pool) {
2991 continue;
2992 }
2993 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2994 if (err != C2_OK || !block) {
2995 block.reset();
2996 continue;
2997 }
2998 break;
2999 }
3000 return block;
3001}
3002
3003// static
3004status_t CCodec::CanFetchGraphicBlock(
3005 const std::vector<std::string> &names, bool *isCompatible) {
3006 uint64_t minUsage = 0;
3007 uint64_t maxUsage = ~0ull;
3008 std::set<C2Allocator::id_t> allocators;
3009 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3010 if (allocators.empty()) {
3011 *isCompatible = false;
3012 return OK;
3013 }
3014 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3015 *isCompatible = ((maxUsage & minUsage) == minUsage);
3016 return OK;
3017}
3018
3019// static
3020std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
3021 int32_t width,
3022 int32_t height,
3023 int32_t format,
3024 uint64_t usage,
3025 const std::vector<std::string> &names) {
3026 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
3027 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
3028 ALOGD("Unrecognized pixel format: %d", format);
3029 return nullptr;
3030 }
3031 uint64_t minUsage = 0;
3032 uint64_t maxUsage = ~0ull;
3033 std::set<C2Allocator::id_t> allocators;
3034 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3035 if (allocators.empty()) {
3036 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3037 }
3038 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3039 minUsage |= usage;
3040 if ((maxUsage & minUsage) != minUsage) {
3041 allocators.clear();
3042 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3043 }
3044 std::shared_ptr<C2GraphicBlock> block;
3045 for (C2Allocator::id_t allocId : allocators) {
3046 std::shared_ptr<C2BlockPool> pool;
3047 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3048 if (err != C2_OK || !pool) {
3049 continue;
3050 }
3051 err = pool->fetchGraphicBlock(
3052 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
3053 if (err != C2_OK || !block) {
3054 block.reset();
3055 continue;
3056 }
3057 break;
3058 }
3059 return block;
3060}
3061
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003062} // namespace android