blob: fffd60abb91fc0ea2319b0b5900d123a13b5d656 [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);
209
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700210 // Usage is queried during configure(), so setting it beforehand.
211 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
212 (void)mNode->setParameter(
213 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
214 &usage, sizeof(usage));
215
Yanqiang Fanc56f3e62021-09-28 16:54:07 +0800216 return GetStatus(mSource->configure(
217 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800218 }
219
220 void disconnect() override {
221 if (mNode == nullptr) {
222 return;
223 }
224 sp<IOMXBufferSource> source = mNode->getSource();
225 if (source == nullptr) {
226 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
227 return;
228 }
229 source->onOmxIdle();
230 source->onOmxLoaded();
231 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700232 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800233 }
234
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700235 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
236 if (status.isOk()) {
237 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
238 } else if (status.isDeadObject()) {
239 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800240 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700241 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800242 }
243
244 status_t start() override {
245 sp<IOMXBufferSource> source = mNode->getSource();
246 if (source == nullptr) {
247 return NO_INIT;
248 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900249
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800250 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800251 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900252
Wonsik Kim34d66012021-03-01 16:40:33 -0800253 OMX_PARAM_PORTDEFINITIONTYPE param;
254 param.nPortIndex = kPortIndexInput;
255 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
256 &param, sizeof(param));
257 if (err == OK) {
258 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900259 }
260
261 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800262 source->onInputBufferAdded(i);
263 }
264
265 source->onOmxExecuting();
266 return OK;
267 }
268
269 status_t signalEndOfInputStream() override {
270 return GetStatus(mSource->signalEndOfInputStream());
271 }
272
273 status_t configure(Config &config) {
274 std::stringstream status;
275 status_t err = OK;
276
277 // handle each configuration granually, in case we need to handle part of the configuration
278 // elsewhere
279
280 // TRICKY: we do not unset frame delay repeating
281 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
282 int64_t us = 1e6 / config.mMinFps + 0.5;
283 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
284 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
285 if (res != OK) {
286 status << " (=> " << asString(res) << ")";
287 err = res;
288 }
289 mConfig.mMinFps = config.mMinFps;
290 }
291
292 // pts gap
293 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
294 if (mNode != nullptr) {
295 OMX_PARAM_U32TYPE ptrGapParam = {};
296 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700297 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800298 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
299 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700300 // float -> uint32_t is undefined if the value is negative.
301 // First convert to int32_t to ensure the expected behavior.
302 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800303 (void)mNode->setParameter(
304 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
305 &ptrGapParam, sizeof(ptrGapParam));
306 }
307 }
308
309 // max fps
310 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700311 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800312 && config.mMaxFps != mConfig.mMaxFps) {
313 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
314 status << " maxFps=" << config.mMaxFps;
315 if (res != OK) {
316 status << " (=> " << asString(res) << ")";
317 err = res;
318 }
319 mConfig.mMaxFps = config.mMaxFps;
320 }
321
322 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
323 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
324 status << " timeOffset " << config.mTimeOffsetUs << "us";
325 if (res != OK) {
326 status << " (=> " << asString(res) << ")";
327 err = res;
328 }
329 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
330 }
331
332 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
333 status_t res =
334 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
335 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
336 if (res != OK) {
337 status << " (=> " << asString(res) << ")";
338 err = res;
339 }
340 mConfig.mCaptureFps = config.mCaptureFps;
341 mConfig.mCodedFps = config.mCodedFps;
342 }
343
344 if (config.mStartAtUs != mConfig.mStartAtUs
345 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
346 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
347 status << " start at " << config.mStartAtUs << "us";
348 if (res != OK) {
349 status << " (=> " << asString(res) << ")";
350 err = res;
351 }
352 mConfig.mStartAtUs = config.mStartAtUs;
353 mConfig.mStopped = config.mStopped;
354 }
355
356 // suspend-resume
357 if (config.mSuspended != mConfig.mSuspended) {
358 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
359 status << " " << (config.mSuspended ? "suspend" : "resume")
360 << " at " << config.mSuspendAtUs << "us";
361 if (res != OK) {
362 status << " (=> " << asString(res) << ")";
363 err = res;
364 }
365 mConfig.mSuspended = config.mSuspended;
366 mConfig.mSuspendAtUs = config.mSuspendAtUs;
367 }
368
369 if (config.mStopped != mConfig.mStopped && config.mStopped) {
370 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
371 status << " stop at " << config.mStopAtUs << "us";
372 if (res != OK) {
373 status << " (=> " << asString(res) << ")";
374 err = res;
375 } else {
376 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700377 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
378 [&res, &delayUs = config.mInputDelayUs](
379 auto status, auto stopTimeOffsetUs) {
380 res = static_cast<status_t>(status);
381 delayUs = stopTimeOffsetUs;
382 });
383 if (!trans.isOk()) {
384 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
385 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800386 if (res != OK) {
387 status << " (=> " << asString(res) << ")";
388 } else {
389 status << "=" << config.mInputDelayUs << "us";
390 }
391 mConfig.mInputDelayUs = config.mInputDelayUs;
392 }
393 mConfig.mStopAtUs = config.mStopAtUs;
394 mConfig.mStopped = config.mStopped;
395 }
396
397 // color aspects (android._color-aspects)
398
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700399 // consumer usage is queried earlier.
400
Wonsik Kima1335e12021-04-22 16:28:29 -0700401 // priority
402 if (mConfig.mPriority != config.mPriority) {
403 if (config.mPriority != INT_MAX) {
404 mNode->setPriority(config.mPriority);
405 }
406 mConfig.mPriority = config.mPriority;
407 }
408
Wonsik Kimbd557932019-07-02 15:51:20 -0700409 if (status.str().empty()) {
410 ALOGD("ISConfig not changed");
411 } else {
412 ALOGD("ISConfig%s", status.str().c_str());
413 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800414 return err;
415 }
416
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700417 void onInputBufferDone(c2_cntr64_t index) override {
418 mNode->onInputBufferDone(index);
419 }
420
Wonsik Kim673dd192021-01-29 14:58:12 -0800421 android_dataspace getDataspace() override {
422 return mNode->getDataspace();
423 }
424
Pawin Vongmasa36653902018-11-15 00:10:25 -0800425private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700426 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800427 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700428 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800429 uint32_t mWidth;
430 uint32_t mHeight;
431 Config mConfig;
432};
433
434class Codec2ClientInterfaceWrapper : public C2ComponentStore {
435 std::shared_ptr<Codec2Client> mClient;
436
437public:
438 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
439 : mClient(client) { }
440
441 virtual ~Codec2ClientInterfaceWrapper() = default;
442
443 virtual c2_status_t config_sm(
444 const std::vector<C2Param *> &params,
445 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
446 return mClient->config(params, C2_MAY_BLOCK, failures);
447 };
448
449 virtual c2_status_t copyBuffer(
450 std::shared_ptr<C2GraphicBuffer>,
451 std::shared_ptr<C2GraphicBuffer>) {
452 return C2_OMITTED;
453 }
454
455 virtual c2_status_t createComponent(
456 C2String, std::shared_ptr<C2Component> *const component) {
457 component->reset();
458 return C2_OMITTED;
459 }
460
461 virtual c2_status_t createInterface(
462 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
463 interface->reset();
464 return C2_OMITTED;
465 }
466
467 virtual c2_status_t query_sm(
468 const std::vector<C2Param *> &stackParams,
469 const std::vector<C2Param::Index> &heapParamIndices,
470 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
471 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
472 }
473
474 virtual c2_status_t querySupportedParams_nb(
475 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
476 return mClient->querySupportedParams(params);
477 }
478
479 virtual c2_status_t querySupportedValues_sm(
480 std::vector<C2FieldSupportedValuesQuery> &fields) const {
481 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
482 }
483
484 virtual C2String getName() const {
485 return mClient->getName();
486 }
487
488 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
489 return mClient->getParamReflector();
490 }
491
492 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
493 return std::vector<std::shared_ptr<const C2Component::Traits>>();
494 }
495};
496
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800497void RevertOutputFormatIfNeeded(
498 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
499 // We used to not report changes to these keys to the client.
500 const static std::set<std::string> sIgnoredKeys({
501 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800502 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800503 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800504 KEY_MAX_WIDTH,
505 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800506 "csd-0",
507 "csd-1",
508 "csd-2",
509 });
510 if (currentFormat == oldFormat) {
511 return;
512 }
513 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
514 AMessage::Type type;
515 for (size_t i = diff->countEntries(); i > 0; --i) {
516 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
517 diff->removeEntryAt(i - 1);
518 }
519 }
520 if (diff->countEntries() == 0) {
521 currentFormat = oldFormat;
522 }
523}
524
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700525void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700526 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700527 const sp<AMessage> &outputFormat) {
528 if (mediaType == MIMETYPE_VIDEO_AVC) {
529 // Codec specific data should be SPS and PPS in a single buffer,
530 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
531 // We separate the two and put them into the output format
532 // under the keys "csd-0" and "csd-1".
533
534 unsigned csdIndex = 0;
535
536 const uint8_t *nalStart;
537 size_t nalSize;
538 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
539 sp<ABuffer> csd = new ABuffer(nalSize + 4);
540 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
541 memcpy(csd->data() + 4, nalStart, nalSize);
542
543 outputFormat->setBuffer(
544 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
545
546 ++csdIndex;
547 }
548
549 if (csdIndex != 2) {
550 ALOGW("Expected two NAL units from AVC codec config, but %u found",
551 csdIndex);
552 }
553 } else {
554 // For everything else we just stash the codec specific data into
555 // the output format as a single piece of csd under "csd-0".
556 sp<ABuffer> csd = new ABuffer(size);
557 memcpy(csd->data(), data, size);
558 csd->setRange(0, size);
559 outputFormat->setBuffer("csd-0", csd);
560 }
561}
562
Pawin Vongmasa36653902018-11-15 00:10:25 -0800563} // namespace
564
565// CCodec::ClientListener
566
567struct CCodec::ClientListener : public Codec2Client::Listener {
568
569 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
570
571 virtual void onWorkDone(
572 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800573 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800574 (void)component;
575 sp<CCodec> codec(mCodec.promote());
576 if (!codec) {
577 return;
578 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800579 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800580 }
581
582 virtual void onTripped(
583 const std::weak_ptr<Codec2Client::Component>& component,
584 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
585 ) override {
586 // TODO
587 (void)component;
588 (void)settingResult;
589 }
590
591 virtual void onError(
592 const std::weak_ptr<Codec2Client::Component>& component,
593 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800594 {
595 // Component is only used for reporting as we use a separate listener for each instance
596 std::shared_ptr<Codec2Client::Component> comp = component.lock();
597 if (!comp) {
598 ALOGD("Component died with error: 0x%x", errorCode);
599 } else {
600 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
601 }
602 }
603
604 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800605 // Note: for now we do not propagate the error code to MediaCodec
606 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800607 sp<CCodec> codec(mCodec.promote());
608 if (!codec || !codec->mCallback) {
609 return;
610 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800611 codec->mCallback->onError(
612 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
613 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800614 }
615
616 virtual void onDeath(
617 const std::weak_ptr<Codec2Client::Component>& component) override {
618 { // Log the death of the component.
619 std::shared_ptr<Codec2Client::Component> comp = component.lock();
620 if (!comp) {
621 ALOGE("Codec2 component died.");
622 } else {
623 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
624 }
625 }
626
627 // Report to MediaCodec.
628 sp<CCodec> codec(mCodec.promote());
629 if (!codec || !codec->mCallback) {
630 return;
631 }
632 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
633 }
634
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800635 virtual void onFrameRendered(uint64_t bufferQueueId,
636 int32_t slotId,
637 int64_t timestampNs) override {
638 // TODO: implement
639 (void)bufferQueueId;
640 (void)slotId;
641 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800642 }
643
644 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800645 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800646 sp<CCodec> codec(mCodec.promote());
647 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800648 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800649 }
650 }
651
652private:
653 wp<CCodec> mCodec;
654};
655
656// CCodecCallbackImpl
657
658class CCodecCallbackImpl : public CCodecCallback {
659public:
660 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
661 ~CCodecCallbackImpl() override = default;
662
663 void onError(status_t err, enum ActionCode actionCode) override {
664 mCodec->mCallback->onError(err, actionCode);
665 }
666
667 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
668 mCodec->mCallback->onOutputFramesRendered(
669 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
670 }
671
Pawin Vongmasa36653902018-11-15 00:10:25 -0800672 void onOutputBuffersChanged() override {
673 mCodec->mCallback->onOutputBuffersChanged();
674 }
675
Guillaume Chelfi5ffbcb32021-04-12 14:23:43 +0200676 void onFirstTunnelFrameReady() override {
677 mCodec->mCallback->onFirstTunnelFrameReady();
678 }
679
Pawin Vongmasa36653902018-11-15 00:10:25 -0800680private:
681 CCodec *mCodec;
682};
683
684// CCodec
685
686CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700687 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
688 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800689}
690
691CCodec::~CCodec() {
692}
693
694std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
695 return mChannel;
696}
697
698status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
699 status_t err = job();
700 if (err != C2_OK) {
701 mCallback->onError(err, ACTION_CODE_FATAL);
702 }
703 return err;
704}
705
706void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
707 auto setAllocating = [this] {
708 Mutexed<State>::Locked state(mState);
709 if (state->get() != RELEASED) {
710 return INVALID_OPERATION;
711 }
712 state->set(ALLOCATING);
713 return OK;
714 };
715 if (tryAndReportOnError(setAllocating) != OK) {
716 return;
717 }
718
719 sp<RefBase> codecInfo;
720 CHECK(msg->findObject("codecInfo", &codecInfo));
721 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
722
723 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
724 allocMsg->setObject("codecInfo", codecInfo);
725 allocMsg->post();
726}
727
728void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
729 if (codecInfo == nullptr) {
730 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
731 return;
732 }
733 ALOGD("allocate(%s)", codecInfo->getCodecName());
734 mClientListener.reset(new ClientListener(this));
735
736 AString componentName = codecInfo->getCodecName();
737 std::shared_ptr<Codec2Client> client;
738
739 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700740 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800741 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800742 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800743 SetPreferredCodec2ComponentStore(
744 std::make_shared<Codec2ClientInterfaceWrapper>(client));
745 }
746
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900747 std::shared_ptr<Codec2Client::Component> comp;
748 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800749 componentName.c_str(),
750 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900751 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800752 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900753 if (status != C2_OK) {
754 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800755 Mutexed<State>::Locked state(mState);
756 state->set(RELEASED);
757 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900758 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759 state.lock();
760 return;
761 }
762 ALOGI("Created component [%s]", componentName.c_str());
763 mChannel->setComponent(comp);
764 auto setAllocated = [this, comp, client] {
765 Mutexed<State>::Locked state(mState);
766 if (state->get() != ALLOCATING) {
767 state->set(RELEASED);
768 return UNKNOWN_ERROR;
769 }
770 state->set(ALLOCATED);
771 state->comp = comp;
772 mClient = client;
773 return OK;
774 };
775 if (tryAndReportOnError(setAllocated) != OK) {
776 return;
777 }
778
779 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700780 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
781 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800782 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800783 if (err != OK) {
784 ALOGW("Failed to initialize configuration support");
785 // TODO: report error once we complete implementation.
786 }
787 config->queryConfiguration(comp);
788
789 mCallback->onComponentAllocated(componentName.c_str());
790}
791
792void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
793 auto checkAllocated = [this] {
794 Mutexed<State>::Locked state(mState);
795 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
796 };
797 if (tryAndReportOnError(checkAllocated) != OK) {
798 return;
799 }
800
801 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
802 msg->setMessage("format", format);
803 msg->post();
804}
805
806void CCodec::configure(const sp<AMessage> &msg) {
807 std::shared_ptr<Codec2Client::Component> comp;
808 auto checkAllocated = [this, &comp] {
809 Mutexed<State>::Locked state(mState);
810 if (state->get() != ALLOCATED) {
811 state->set(RELEASED);
812 return UNKNOWN_ERROR;
813 }
814 comp = state->comp;
815 return OK;
816 };
817 if (tryAndReportOnError(checkAllocated) != OK) {
818 return;
819 }
820
821 auto doConfig = [msg, comp, this]() -> status_t {
822 AString mime;
823 if (!msg->findString("mime", &mime)) {
824 return BAD_VALUE;
825 }
826
827 int32_t encoder;
828 if (!msg->findInt32("encoder", &encoder)) {
829 encoder = false;
830 }
831
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800832 int32_t flags;
833 if (!msg->findInt32("flags", &flags)) {
834 return BAD_VALUE;
835 }
836
Pawin Vongmasa36653902018-11-15 00:10:25 -0800837 // TODO: read from intf()
838 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
839 return UNKNOWN_ERROR;
840 }
841
842 int32_t storeMeta;
843 if (encoder
844 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
845 && storeMeta != kMetadataBufferTypeInvalid) {
846 if (storeMeta != kMetadataBufferTypeANWBuffer) {
847 ALOGD("Only ANW buffers are supported for legacy metadata mode");
848 return BAD_VALUE;
849 }
850 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
851 }
852
ted.sun765db4d2020-06-23 14:03:41 +0800853 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800854 sp<RefBase> obj;
855 sp<Surface> surface;
856 if (msg->findObject("native-window", &obj)) {
857 surface = static_cast<Surface *>(obj.get());
ted.sun765db4d2020-06-23 14:03:41 +0800858 // setup tunneled playback
859 if (surface != nullptr) {
860 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
861 const std::unique_ptr<Config> &config = *configLocked;
862 if ((config->mDomain & Config::IS_DECODER)
863 && (config->mDomain & Config::IS_VIDEO)) {
864 int32_t tunneled;
865 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
866 ALOGI("Configuring TUNNELED video playback.");
867
868 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
869 if (err != OK) {
870 ALOGE("configureTunneledVideoPlayback failed!");
871 return err;
872 }
873 config->mTunneled = true;
874 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +0100875
876 int32_t pushBlankBuffersOnStop = 0;
877 if (msg->findInt32(KEY_PUSH_BLANK_BUFFERS_ON_STOP, &pushBlankBuffersOnStop)) {
878 config->mPushBlankBuffersOnStop = pushBlankBuffersOnStop == 1;
879 }
ted.sun765db4d2020-06-23 14:03:41 +0800880 }
881 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800882 setSurface(surface);
883 }
884
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700885 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
886 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800887 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800888 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
889 ALOGD("[%s] buffers are %sbound to CCodec for this session",
890 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800891
Wonsik Kim1114eea2019-02-25 14:35:24 -0800892 // Enforce required parameters
893 int32_t i32;
894 float flt;
895 if (config->mDomain & Config::IS_AUDIO) {
896 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
897 ALOGD("sample rate is missing, which is required for audio components.");
898 return BAD_VALUE;
899 }
900 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
901 ALOGD("channel count is missing, which is required for audio components.");
902 return BAD_VALUE;
903 }
904 if ((config->mDomain & Config::IS_ENCODER)
905 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
906 && !msg->findInt32(KEY_BIT_RATE, &i32)
907 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
908 ALOGD("bitrate is missing, which is required for audio encoders.");
909 return BAD_VALUE;
910 }
911 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800912 int32_t width = 0;
913 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800914 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800915 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800916 ALOGD("width is missing, which is required for image/video components.");
917 return BAD_VALUE;
918 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800919 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800920 ALOGD("height is missing, which is required for image/video components.");
921 return BAD_VALUE;
922 }
923 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700924 int32_t mode = BITRATE_MODE_VBR;
925 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700926 if (!msg->findInt32(KEY_QUALITY, &i32)) {
927 ALOGD("quality is missing, which is required for video encoders in CQ.");
928 return BAD_VALUE;
929 }
930 } else {
931 if (!msg->findInt32(KEY_BIT_RATE, &i32)
932 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
933 ALOGD("bitrate is missing, which is required for video encoders.");
934 return BAD_VALUE;
935 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800936 }
937 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
938 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
939 ALOGD("I frame interval is missing, which is required for video encoders.");
940 return BAD_VALUE;
941 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700942 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
943 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
944 ALOGD("frame rate is missing, which is required for video encoders.");
945 return BAD_VALUE;
946 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800947 }
948 }
949
Pawin Vongmasa36653902018-11-15 00:10:25 -0800950 /*
951 * Handle input surface configuration
952 */
953 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
954 && (config->mDomain & Config::IS_ENCODER)) {
955 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
956 {
957 config->mISConfig->mMinFps = 0;
958 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800959 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800960 config->mISConfig->mMinFps = 1e6 / value;
961 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700962 if (!msg->findFloat(
963 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
964 config->mISConfig->mMaxFps = -1;
965 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800966 config->mISConfig->mMinAdjustedFps = 0;
967 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800968 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800969 if (value < 0 && value >= INT32_MIN) {
970 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700971 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800972 } else if (value > 0 && value <= INT32_MAX) {
973 config->mISConfig->mMinAdjustedFps = 1e6 / value;
974 }
975 }
976 }
977
978 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700979 bool captureFpsFound = false;
980 double timeLapseFps;
981 float captureRate;
982 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
983 config->mISConfig->mCaptureFps = timeLapseFps;
984 captureFpsFound = true;
985 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
986 config->mISConfig->mCaptureFps = captureRate;
987 captureFpsFound = true;
988 }
989 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800990 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
991 }
992 }
993
994 {
995 config->mISConfig->mSuspended = false;
996 config->mISConfig->mSuspendAtUs = -1;
997 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800998 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800999 config->mISConfig->mSuspended = true;
1000 }
1001 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001002 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -07001003 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001004 }
1005
1006 /*
1007 * Handle desired color format.
1008 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001009 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001010 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001011 int32_t format = 0;
1012 // Query vendor format for Flexible YUV
1013 std::vector<std::unique_ptr<C2Param>> heapParams;
1014 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
Wonsik Kim50811882022-04-28 15:57:27 -07001015 int vendorSdkVersion = base::GetIntProperty(
1016 "ro.vendor.build.version.sdk", android_get_device_api_level());
1017 if (vendorSdkVersion >= __ANDROID_API_S__ && mClient->query(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001018 {},
1019 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1020 C2_MAY_BLOCK,
1021 &heapParams) == C2_OK
1022 && heapParams.size() == 1u) {
1023 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1024 heapParams[0].get());
1025 } else {
1026 pixelFormatInfo = nullptr;
1027 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001028 // bit depth -> format
1029 std::map<uint32_t, uint32_t> flexPixelFormat;
1030 std::map<uint32_t, uint32_t> flexPlanarPixelFormat;
1031 std::map<uint32_t, uint32_t> flexSemiPlanarPixelFormat;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001032 if (pixelFormatInfo && *pixelFormatInfo) {
1033 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1034 const C2FlexiblePixelFormatDescriptorStruct &desc =
1035 pixelFormatInfo->m.values[i];
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001036 if (desc.subsampling != C2Color::YUV_420
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001037 // TODO(b/180076105): some device report wrong layout
1038 // || desc.layout == C2Color::INTERLEAVED_PACKED
1039 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1040 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1041 continue;
1042 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001043 if (flexPixelFormat.count(desc.bitDepth) == 0) {
1044 flexPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001045 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001046 if (desc.layout == C2Color::PLANAR_PACKED
1047 && flexPlanarPixelFormat.count(desc.bitDepth) == 0) {
1048 flexPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001049 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001050 if (desc.layout == C2Color::SEMIPLANAR_PACKED
1051 && flexSemiPlanarPixelFormat.count(desc.bitDepth) == 0) {
1052 flexSemiPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001053 }
1054 }
1055 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001056 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001057 // Also handle default color format (encoders require color format, so this is only
1058 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001059 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001060 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001061 const char *prefix = "";
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001062 if (flexSemiPlanarPixelFormat.count(8) != 0) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001063 format = COLOR_FormatYUV420SemiPlanar;
1064 prefix = "semi-";
1065 } else {
1066 format = COLOR_FormatYUV420Planar;
1067 }
1068 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1069 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001070 } else {
1071 format = COLOR_FormatSurface;
1072 }
1073 defaultColorFormat = format;
1074 }
1075 } else {
1076 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
1077 switch (format) {
1078 case COLOR_FormatYUV420Flexible:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001079 format = COLOR_FormatYUV420Planar;
1080 if (flexPixelFormat.count(8) != 0) {
1081 format = flexPixelFormat[8];
1082 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001083 break;
1084 case COLOR_FormatYUV420Planar:
1085 case COLOR_FormatYUV420PackedPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001086 if (flexPlanarPixelFormat.count(8) != 0) {
1087 format = flexPlanarPixelFormat[8];
1088 } else if (flexPixelFormat.count(8) != 0) {
1089 format = flexPixelFormat[8];
1090 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001091 break;
1092 case COLOR_FormatYUV420SemiPlanar:
1093 case COLOR_FormatYUV420PackedSemiPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001094 if (flexSemiPlanarPixelFormat.count(8) != 0) {
1095 format = flexSemiPlanarPixelFormat[8];
1096 } else if (flexPixelFormat.count(8) != 0) {
1097 format = flexPixelFormat[8];
1098 }
1099 break;
1100 case COLOR_FormatYUVP010:
1101 format = COLOR_FormatYUVP010;
1102 if (flexSemiPlanarPixelFormat.count(10) != 0) {
1103 format = flexSemiPlanarPixelFormat[10];
1104 } else if (flexPixelFormat.count(10) != 0) {
1105 format = flexPixelFormat[10];
1106 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001107 break;
1108 default:
1109 // No-op
1110 break;
1111 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001112 }
1113 }
1114
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001115 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001116 msg->setInt32("android._color-format", format);
1117 }
1118 }
1119
Wonsik Kim77e97c72021-01-20 10:33:22 -08001120 /*
1121 * Handle dataspace
1122 */
1123 int32_t usingRecorder;
1124 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1125 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1126 int32_t width, height;
1127 if (msg->findInt32("width", &width)
1128 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001129 ColorAspects aspects;
1130 getColorAspectsFromFormat(msg, aspects);
1131 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001132 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001133 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1134 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001135 }
1136 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1137 ALOGD("setting dataspace to %x", dataSpace);
1138 }
1139
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001140 int32_t subscribeToAllVendorParams;
1141 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1142 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1143 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1144 }
1145 }
1146
Pawin Vongmasa36653902018-11-15 00:10:25 -08001147 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001148 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1149 // the behavior here.
1150 sp<AMessage> sdkParams = msg;
1151 int32_t videoBitrate;
1152 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1153 sdkParams = msg->dup();
1154 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1155 }
ted.sun765db4d2020-06-23 14:03:41 +08001156 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001157 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001158 if (err != OK) {
1159 ALOGW("failed to convert configuration to c2 params");
1160 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001161
1162 int32_t maxBframes = 0;
1163 if ((config->mDomain & Config::IS_ENCODER)
1164 && (config->mDomain & Config::IS_VIDEO)
1165 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1166 && maxBframes > 0) {
1167 std::unique_ptr<C2StreamGopTuning::output> gop =
1168 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1169 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1170 gop->m.values[1] = {
1171 C2Config::picture_type_t(P_FRAME | B_FRAME),
1172 uint32_t(maxBframes)
1173 };
1174 configUpdate.push_back(std::move(gop));
1175 }
1176
Ray Essicka0ae6972021-03-10 19:40:01 -08001177 if ((config->mDomain & Config::IS_ENCODER)
1178 && (config->mDomain & Config::IS_VIDEO)) {
1179 // we may not use all 3 of these entries
1180 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1181 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1182 0u /* stream */);
1183
1184 int ix = 0;
1185
1186 int32_t iMax = INT32_MAX;
1187 int32_t iMin = INT32_MIN;
1188 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1189 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1190 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1191 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1192 }
1193
1194 int32_t pMax = INT32_MAX;
1195 int32_t pMin = INT32_MIN;
1196 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1197 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1198 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1199 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1200 }
1201
1202 int32_t bMax = INT32_MAX;
1203 int32_t bMin = INT32_MIN;
1204 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1205 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1206 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1207 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1208 }
1209
1210 // adjust to reflect actual use.
1211 qp->setFlexCount(ix);
1212
1213 configUpdate.push_back(std::move(qp));
1214 }
1215
Wonsik Kima1335e12021-04-22 16:28:29 -07001216 int32_t background = 0;
1217 if ((config->mDomain & Config::IS_VIDEO)
1218 && msg->findInt32("android._background-mode", &background)
1219 && background) {
1220 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1221 if (config->mISConfig) {
1222 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1223 }
1224 }
1225
Pawin Vongmasa36653902018-11-15 00:10:25 -08001226 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1227 if (err != OK) {
1228 ALOGW("failed to configure c2 params");
1229 return err;
1230 }
1231
1232 std::vector<std::unique_ptr<C2Param>> params;
1233 C2StreamUsageTuning::input usage(0u, 0u);
1234 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001235 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001236
Wonsik Kim3baecda2021-02-07 22:19:56 -08001237 C2Param::Index colorAspectsRequestIndex =
1238 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001239 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001240 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001241 };
Chaejung Lim86c22dc2021-12-23 00:41:05 -08001242 int32_t colorTransferRequest = 0;
1243 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1244 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1245 colorTransferRequest = 0;
1246 }
1247 c2_status_t c2err = C2_OK;
1248 if (colorTransferRequest != 0) {
1249 c2err = comp->query(
1250 { &usage, &maxInputSize, &prepend },
1251 indices,
1252 C2_DONT_BLOCK,
1253 &params);
1254 } else {
1255 c2err = comp->query(
1256 { &usage, &maxInputSize, &prepend },
1257 {},
1258 C2_DONT_BLOCK,
1259 &params);
1260 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001261 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1262 ALOGE("Failed to query component interface: %d", c2err);
1263 return UNKNOWN_ERROR;
1264 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001265 if (usage) {
1266 if (usage.value & C2MemoryUsage::CPU_READ) {
1267 config->mInputFormat->setInt32("using-sw-read-often", true);
1268 }
1269 if (config->mISConfig) {
1270 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1271 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1272 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001273 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001274 }
1275
1276 // NOTE: we don't blindly use client specified input size if specified as clients
1277 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1278 // client specified size is only used to ask for bigger buffers than component suggested
1279 // size.
1280 int32_t clientInputSize = 0;
1281 bool clientSpecifiedInputSize =
1282 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1283 // TEMP: enforce minimum buffer size of 1MB for video decoders
1284 // and 16K / 4K for audio encoders/decoders
1285 if (maxInputSize.value == 0) {
1286 if (config->mDomain & Config::IS_AUDIO) {
1287 maxInputSize.value = encoder ? 16384 : 4096;
1288 } else if (!encoder) {
1289 maxInputSize.value = 1048576u;
1290 }
1291 }
1292
1293 // verify that CSD fits into this size (if defined)
1294 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1295 sp<ABuffer> csd;
1296 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1297 if (csd && csd->size() > maxInputSize.value) {
1298 maxInputSize.value = csd->size();
1299 }
1300 }
1301 }
1302
1303 // TODO: do this based on component requiring linear allocator for input
1304 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1305 if (clientSpecifiedInputSize) {
1306 // Warn that we're overriding client's max input size if necessary.
1307 if ((uint32_t)clientInputSize < maxInputSize.value) {
1308 ALOGD("client requested max input size %d, which is smaller than "
1309 "what component recommended (%u); overriding with component "
1310 "recommendation.", clientInputSize, maxInputSize.value);
1311 ALOGW("This behavior is subject to change. It is recommended that "
1312 "app developers double check whether the requested "
1313 "max input size is in reasonable range.");
1314 } else {
1315 maxInputSize.value = clientInputSize;
1316 }
1317 }
1318 // Pass max input size on input format to the buffer channel (if supplied by the
1319 // component or by a default)
1320 if (maxInputSize.value) {
1321 config->mInputFormat->setInt32(
1322 KEY_MAX_INPUT_SIZE,
1323 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1324 }
1325 }
1326
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001327 int32_t clientPrepend;
1328 if ((config->mDomain & Config::IS_VIDEO)
1329 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001330 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001331 && clientPrepend
1332 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001333 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001334 return BAD_VALUE;
1335 }
1336
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001337 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001338 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1339 // propagate HDR static info to output format for both encoders and decoders
1340 // if component supports this info, we will update from component, but only the raw port,
1341 // so don't propagate if component already filled it in.
1342 sp<ABuffer> hdrInfo;
1343 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1344 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1345 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1346 }
1347
1348 // Set desired color format from configuration parameter
1349 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001350 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1351 format = defaultColorFormat;
1352 }
1353 if (config->mDomain & Config::IS_ENCODER) {
1354 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001355 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1356 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001357 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001358 } else {
1359 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001360 }
1361 }
1362
1363 // propagate encoder delay and padding to output format
1364 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1365 int delay = 0;
1366 if (msg->findInt32("encoder-delay", &delay)) {
1367 config->mOutputFormat->setInt32("encoder-delay", delay);
1368 }
1369 int padding = 0;
1370 if (msg->findInt32("encoder-padding", &padding)) {
1371 config->mOutputFormat->setInt32("encoder-padding", padding);
1372 }
1373 }
1374
Pawin Vongmasa36653902018-11-15 00:10:25 -08001375 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001376 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001377 int32_t mask;
1378 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1379 if (config->mDomain & Config::IS_ENCODER) {
1380 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1381 } else {
1382 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1383 }
1384 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001385
1386 // set PCM encoding
1387 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1388 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1389 if (encoder) {
1390 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1391 } else {
1392 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1393 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 }
1395
Wonsik Kim3baecda2021-02-07 22:19:56 -08001396 std::unique_ptr<C2Param> colorTransferRequestParam;
1397 for (std::unique_ptr<C2Param> &param : params) {
1398 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1399 ALOGI("found color transfer request param");
1400 colorTransferRequestParam = std::move(param);
1401 }
1402 }
Wonsik Kim3baecda2021-02-07 22:19:56 -08001403
1404 if (colorTransferRequest != 0) {
1405 if (colorTransferRequestParam && *colorTransferRequestParam) {
1406 C2StreamColorAspectsInfo::output *info =
1407 static_cast<C2StreamColorAspectsInfo::output *>(
1408 colorTransferRequestParam.get());
1409 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1410 colorTransferRequest = 0;
1411 }
1412 } else {
1413 colorTransferRequest = 0;
1414 }
1415 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1416 }
1417
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001418 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1419 // Need to get stride/vstride
1420 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1421 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1422 // TODO: retrieve these values without allocating a buffer.
1423 // Currently allocating a buffer is necessary to retrieve the layout.
1424 int64_t blockUsage =
1425 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1426 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1427 width, height, pixelFormat, blockUsage, {comp->getName()});
1428 sp<GraphicBlockBuffer> buffer;
1429 if (block) {
1430 buffer = GraphicBlockBuffer::Allocate(
1431 config->mInputFormat,
1432 block,
1433 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1434 } else {
1435 ALOGD("Failed to allocate a graphic block "
1436 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1437 width, height, pixelFormat, (long long)blockUsage);
1438 // This means that byte buffer mode is not supported in this configuration
1439 // anyway. Skip setting stride/vstride to input format.
1440 }
1441 if (buffer) {
1442 sp<ABuffer> imageData = buffer->getImageData();
1443 MediaImage2 *img = nullptr;
1444 if (imageData && imageData->data()
1445 && imageData->size() >= sizeof(MediaImage2)) {
1446 img = (MediaImage2*)imageData->data();
1447 }
1448 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1449 int32_t stride = img->mPlane[0].mRowInc;
1450 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1451 if (img->mNumPlanes > 1 && stride > 0) {
1452 int64_t offsetDelta =
1453 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1454 if (offsetDelta % stride == 0) {
1455 int32_t vstride = int32_t(offsetDelta / stride);
1456 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1457 } else {
1458 ALOGD("Cannot report accurate slice height: "
1459 "offsetDelta = %lld stride = %d",
1460 (long long)offsetDelta, stride);
1461 }
1462 }
1463 }
1464 }
1465 }
1466 }
1467
Wonsik Kimec585c32021-10-01 01:11:00 -07001468 if (config->mTunneled) {
1469 config->mOutputFormat->setInt32("android._tunneled", 1);
1470 }
1471
Yushin Cho91873b52021-12-21 04:08:35 -08001472 // Convert an encoding statistics level to corresponding encoding statistics
1473 // kinds
1474 int32_t encodingStatisticsLevel = VIDEO_ENCODING_STATISTICS_LEVEL_NONE;
1475 if ((config->mDomain & Config::IS_ENCODER)
1476 && (config->mDomain & Config::IS_VIDEO)
1477 && msg->findInt32(KEY_VIDEO_ENCODING_STATISTICS_LEVEL, &encodingStatisticsLevel)) {
1478 // Higher level include all the enc stats belong to lower level.
1479 switch (encodingStatisticsLevel) {
1480 // case VIDEO_ENCODING_STATISTICS_LEVEL_2: // reserved for the future level 2
1481 // with more enc stat kinds
1482 // Future extended encoding statistics for the level 2 should be added here
1483 case VIDEO_ENCODING_STATISTICS_LEVEL_1:
1484 config->subscribeToConfigUpdate(comp,
1485 {kParamIndexAverageBlockQuantization, kParamIndexPictureType});
1486 break;
1487 case VIDEO_ENCODING_STATISTICS_LEVEL_NONE:
1488 break;
1489 }
1490 }
1491 ALOGD("encoding statistics level = %d", encodingStatisticsLevel);
1492
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001493 ALOGD("setup formats input: %s",
1494 config->mInputFormat->debugString().c_str());
1495 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001496 config->mOutputFormat->debugString().c_str());
1497 return OK;
1498 };
1499 if (tryAndReportOnError(doConfig) != OK) {
1500 return;
1501 }
1502
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001503 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1504 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001505
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001506 config->queryConfiguration(comp);
1507
Pawin Vongmasa36653902018-11-15 00:10:25 -08001508 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1509}
1510
1511void CCodec::initiateCreateInputSurface() {
1512 status_t err = [this] {
1513 Mutexed<State>::Locked state(mState);
1514 if (state->get() != ALLOCATED) {
1515 return UNKNOWN_ERROR;
1516 }
1517 // TODO: read it from intf() properly.
1518 if (state->comp->getName().find("encoder") == std::string::npos) {
1519 return INVALID_OPERATION;
1520 }
1521 return OK;
1522 }();
1523 if (err != OK) {
1524 mCallback->onInputSurfaceCreationFailed(err);
1525 return;
1526 }
1527
1528 (new AMessage(kWhatCreateInputSurface, this))->post();
1529}
1530
Lajos Molnar47118272019-01-31 16:28:04 -08001531sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1532 using namespace android::hardware::media::omx::V1_0;
1533 using namespace android::hardware::media::omx::V1_0::utils;
1534 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1535 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1536 android::sp<IOmx> omx = IOmx::getService();
Sungtak Lee47dcb482022-04-15 10:47:08 -07001537 if (omx == nullptr) {
1538 return nullptr;
1539 }
Lajos Molnar47118272019-01-31 16:28:04 -08001540 typedef android::hardware::graphics::bufferqueue::V1_0::
1541 IGraphicBufferProducer HGraphicBufferProducer;
1542 typedef android::hardware::media::omx::V1_0::
1543 IGraphicBufferSource HGraphicBufferSource;
1544 OmxStatus s;
1545 android::sp<HGraphicBufferProducer> gbp;
1546 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001547
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001548 using ::android::hardware::Return;
1549 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001550 [&s, &gbp, &gbs](
1551 OmxStatus status,
1552 const android::sp<HGraphicBufferProducer>& producer,
1553 const android::sp<HGraphicBufferSource>& source) {
1554 s = status;
1555 gbp = producer;
1556 gbs = source;
1557 });
1558 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001559 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001560 }
1561
1562 return nullptr;
1563}
1564
1565sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1566 sp<PersistentSurface> surface(CreateInputSurface());
1567
1568 if (surface == nullptr) {
1569 surface = CreateOmxInputSurface();
1570 }
1571
1572 return surface;
1573}
1574
Pawin Vongmasa36653902018-11-15 00:10:25 -08001575void CCodec::createInputSurface() {
1576 status_t err;
1577 sp<IGraphicBufferProducer> bufferProducer;
1578
Pawin Vongmasa36653902018-11-15 00:10:25 -08001579 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001580 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001581 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001582 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1583 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001584 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001585 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001586 }
1587
Lajos Molnar47118272019-01-31 16:28:04 -08001588 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001589 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1590 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1591 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001592
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001593 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001594 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1595 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001596 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001597 inputSurface));
1598 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001599 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001600 int32_t width = 0;
1601 (void)outputFormat->findInt32("width", &width);
1602 int32_t height = 0;
1603 (void)outputFormat->findInt32("height", &height);
1604 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001605 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001606 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001607 } else {
1608 ALOGE("Corrupted input surface");
1609 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1610 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001611 }
1612
1613 if (err != OK) {
1614 ALOGE("Failed to set up input surface: %d", err);
1615 mCallback->onInputSurfaceCreationFailed(err);
1616 return;
1617 }
1618
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001619 // Formats can change after setupInputSurface
1620 sp<AMessage> inputFormat;
1621 {
1622 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1623 const std::unique_ptr<Config> &config = *configLocked;
1624 inputFormat = config->mInputFormat;
1625 outputFormat = config->mOutputFormat;
1626 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001627 mCallback->onInputSurfaceCreated(
1628 inputFormat,
1629 outputFormat,
1630 new BufferProducerWrapper(bufferProducer));
1631}
1632
1633status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001634 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1635 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001636 config->mUsingSurface = true;
1637
1638 // we are now using surface - apply default color aspects to input format - as well as
1639 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001640 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001641
1642 // configure dataspace
1643 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
Wonsik Kim66b19552021-08-02 16:07:49 -07001644
1645 // The output format contains app-configured color aspects, and the input format
1646 // has the default color aspects. Use the default for the unspecified params.
1647 ColorAspects inputColorAspects, colorAspects;
1648 getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
1649 getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
1650 if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
1651 colorAspects.mRange = inputColorAspects.mRange;
1652 }
1653 if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
1654 colorAspects.mPrimaries = inputColorAspects.mPrimaries;
1655 }
1656 if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
1657 colorAspects.mTransfer = inputColorAspects.mTransfer;
1658 }
1659 if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
1660 colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
1661 }
1662 android_dataspace dataSpace = getDataSpaceForColorAspects(
1663 colorAspects, /* mayExtend = */ false);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001664 surface->setDataSpace(dataSpace);
Wonsik Kim66b19552021-08-02 16:07:49 -07001665 setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
1666 config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
1667
1668 ALOGD("input format %s to %s",
1669 inputFormatChanged ? "changed" : "unchanged",
1670 config->mInputFormat->debugString().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001671
1672 status_t err = mChannel->setInputSurface(surface);
1673 if (err != OK) {
1674 // undo input format update
1675 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001676 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001677 return err;
1678 }
1679 config->mInputSurface = surface;
1680
1681 if (config->mISConfig) {
1682 surface->configure(*config->mISConfig);
1683 } else {
1684 ALOGD("ISConfig: no configuration");
1685 }
1686
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001687 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001688}
1689
1690void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1691 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1692 msg->setObject("surface", surface);
1693 msg->post();
1694}
1695
1696void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001697 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001698 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001699 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001700 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1701 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001702 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001703 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001704 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001705 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1706 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1707 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1708 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001709 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1710 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1711 if (err != OK) {
1712 ALOGE("Failed to set up input surface: %d", err);
1713 mCallback->onInputSurfaceDeclined(err);
1714 return;
1715 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001716 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001717 int32_t width = 0;
1718 (void)outputFormat->findInt32("width", &width);
1719 int32_t height = 0;
1720 (void)outputFormat->findInt32("height", &height);
1721 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001722 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001723 if (err != OK) {
1724 ALOGE("Failed to set up input surface: %d", err);
1725 mCallback->onInputSurfaceDeclined(err);
1726 return;
1727 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001728 } else {
1729 ALOGE("Failed to set input surface: Corrupted surface.");
1730 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1731 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001732 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001733 // Formats can change after setupInputSurface
1734 sp<AMessage> inputFormat;
1735 {
1736 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1737 const std::unique_ptr<Config> &config = *configLocked;
1738 inputFormat = config->mInputFormat;
1739 outputFormat = config->mOutputFormat;
1740 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001741 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1742}
1743
1744void CCodec::initiateStart() {
1745 auto setStarting = [this] {
1746 Mutexed<State>::Locked state(mState);
1747 if (state->get() != ALLOCATED) {
1748 return UNKNOWN_ERROR;
1749 }
1750 state->set(STARTING);
1751 return OK;
1752 };
1753 if (tryAndReportOnError(setStarting) != OK) {
1754 return;
1755 }
1756
1757 (new AMessage(kWhatStart, this))->post();
1758}
1759
1760void CCodec::start() {
1761 std::shared_ptr<Codec2Client::Component> comp;
1762 auto checkStarting = [this, &comp] {
1763 Mutexed<State>::Locked state(mState);
1764 if (state->get() != STARTING) {
1765 return UNKNOWN_ERROR;
1766 }
1767 comp = state->comp;
1768 return OK;
1769 };
1770 if (tryAndReportOnError(checkStarting) != OK) {
1771 return;
1772 }
1773
1774 c2_status_t err = comp->start();
1775 if (err != C2_OK) {
1776 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1777 ACTION_CODE_FATAL);
1778 return;
1779 }
1780 sp<AMessage> inputFormat;
1781 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001782 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001783 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001784 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001785 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1786 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001787 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001788 // start triggers format dup
1789 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001790 if (config->mInputSurface) {
1791 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001792 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001793 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001794 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001795 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001796 if (err2 != OK) {
1797 mCallback->onError(err2, ACTION_CODE_FATAL);
1798 return;
1799 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001800 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001801 if (err2 != OK) {
1802 mCallback->onError(err2, ACTION_CODE_FATAL);
1803 return;
1804 }
1805
1806 auto setRunning = [this] {
1807 Mutexed<State>::Locked state(mState);
1808 if (state->get() != STARTING) {
1809 return UNKNOWN_ERROR;
1810 }
1811 state->set(RUNNING);
1812 return OK;
1813 };
1814 if (tryAndReportOnError(setRunning) != OK) {
1815 return;
1816 }
Arun Johnson5997bb02022-04-01 19:35:44 +00001817
1818 err2 = mChannel->requestInitialInputBuffers();
1819
1820 if (err2 != OK) {
1821 ALOGE("Initial request for Input Buffers failed");
1822 mCallback->onError(err2,ACTION_CODE_FATAL);
1823 return;
1824 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001825 mCallback->onStartCompleted();
1826
Pawin Vongmasa36653902018-11-15 00:10:25 -08001827}
1828
1829void CCodec::initiateShutdown(bool keepComponentAllocated) {
1830 if (keepComponentAllocated) {
1831 initiateStop();
1832 } else {
1833 initiateRelease();
1834 }
1835}
1836
1837void CCodec::initiateStop() {
1838 {
1839 Mutexed<State>::Locked state(mState);
1840 if (state->get() == ALLOCATED
1841 || state->get() == RELEASED
1842 || state->get() == STOPPING
1843 || state->get() == RELEASING) {
1844 // We're already stopped, released, or doing it right now.
1845 state.unlock();
1846 mCallback->onStopCompleted();
1847 state.lock();
1848 return;
1849 }
1850 state->set(STOPPING);
1851 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +01001852 {
1853 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1854 const std::unique_ptr<Config> &config = *configLocked;
1855 if (config->mPushBlankBuffersOnStop) {
1856 mChannel->pushBlankBufferToOutputSurface();
1857 }
1858 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001859 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001860 (new AMessage(kWhatStop, this))->post();
1861}
1862
1863void CCodec::stop() {
1864 std::shared_ptr<Codec2Client::Component> comp;
1865 {
1866 Mutexed<State>::Locked state(mState);
1867 if (state->get() == RELEASING) {
1868 state.unlock();
1869 // We're already stopped or release is in progress.
1870 mCallback->onStopCompleted();
1871 state.lock();
1872 return;
1873 } else if (state->get() != STOPPING) {
1874 state.unlock();
1875 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1876 state.lock();
1877 return;
1878 }
1879 comp = state->comp;
1880 }
1881 status_t err = comp->stop();
1882 if (err != C2_OK) {
1883 // TODO: convert err into status_t
1884 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1885 }
1886
1887 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001888 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1889 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001890 if (config->mInputSurface) {
1891 config->mInputSurface->disconnect();
1892 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001893 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001894 }
1895 }
1896 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001897 Mutexed<State>::Locked state(mState);
1898 if (state->get() == STOPPING) {
1899 state->set(ALLOCATED);
1900 }
1901 }
1902 mCallback->onStopCompleted();
1903}
1904
1905void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001906 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001907 {
1908 Mutexed<State>::Locked state(mState);
1909 if (state->get() == RELEASED || state->get() == RELEASING) {
1910 // We're already released or doing it right now.
1911 if (sendCallback) {
1912 state.unlock();
1913 mCallback->onReleaseCompleted();
1914 state.lock();
1915 }
1916 return;
1917 }
1918 if (state->get() == ALLOCATING) {
1919 state->set(RELEASING);
1920 // With the altered state allocate() would fail and clean up.
1921 if (sendCallback) {
1922 state.unlock();
1923 mCallback->onReleaseCompleted();
1924 state.lock();
1925 }
1926 return;
1927 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001928 if (state->get() == STARTING
1929 || state->get() == RUNNING
1930 || state->get() == STOPPING) {
1931 // Input surface may have been started, so clean up is needed.
1932 clearInputSurfaceIfNeeded = true;
1933 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001934 state->set(RELEASING);
1935 }
1936
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001937 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001938 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1939 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001940 if (config->mInputSurface) {
1941 config->mInputSurface->disconnect();
1942 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001943 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001944 }
1945 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +01001946 {
1947 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1948 const std::unique_ptr<Config> &config = *configLocked;
1949 if (config->mPushBlankBuffersOnStop) {
1950 mChannel->pushBlankBufferToOutputSurface();
1951 }
1952 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001953
Wonsik Kim936a89c2020-05-08 16:07:50 -07001954 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001955 // thiz holds strong ref to this while the thread is running.
1956 sp<CCodec> thiz(this);
1957 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1958}
1959
1960void CCodec::release(bool sendCallback) {
1961 std::shared_ptr<Codec2Client::Component> comp;
1962 {
1963 Mutexed<State>::Locked state(mState);
1964 if (state->get() == RELEASED) {
1965 if (sendCallback) {
1966 state.unlock();
1967 mCallback->onReleaseCompleted();
1968 state.lock();
1969 }
1970 return;
1971 }
1972 comp = state->comp;
1973 }
1974 comp->release();
1975
1976 {
1977 Mutexed<State>::Locked state(mState);
1978 state->set(RELEASED);
1979 state->comp.reset();
1980 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001981 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001982 if (sendCallback) {
1983 mCallback->onReleaseCompleted();
1984 }
1985}
1986
1987status_t CCodec::setSurface(const sp<Surface> &surface) {
Wonsik Kim75e22f42021-04-14 23:34:51 -07001988 {
1989 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1990 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08001991 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
1992 status_t err = OK;
1993
Wonsik Kim75e22f42021-04-14 23:34:51 -07001994 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08001995 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07001996 nativeWindow.get(),
1997 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
1998 if (err != OK) {
1999 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
2000 nativeWindow.get(), config->mSidebandHandle->handle(), err);
2001 return err;
2002 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002003 } else {
2004 // Explicitly reset the sideband handle of the window for
2005 // non-tunneled video in case the window was previously used
2006 // for a tunneled video playback.
2007 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
2008 if (err != OK) {
2009 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
2010 return err;
2011 }
ted.sun765db4d2020-06-23 14:03:41 +08002012 }
2013 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002014 return mChannel->setSurface(surface);
2015}
2016
2017void CCodec::signalFlush() {
2018 status_t err = [this] {
2019 Mutexed<State>::Locked state(mState);
2020 if (state->get() == FLUSHED) {
2021 return ALREADY_EXISTS;
2022 }
2023 if (state->get() != RUNNING) {
2024 return UNKNOWN_ERROR;
2025 }
2026 state->set(FLUSHING);
2027 return OK;
2028 }();
2029 switch (err) {
2030 case ALREADY_EXISTS:
2031 mCallback->onFlushCompleted();
2032 return;
2033 case OK:
2034 break;
2035 default:
2036 mCallback->onError(err, ACTION_CODE_FATAL);
2037 return;
2038 }
2039
2040 mChannel->stop();
2041 (new AMessage(kWhatFlush, this))->post();
2042}
2043
2044void CCodec::flush() {
2045 std::shared_ptr<Codec2Client::Component> comp;
2046 auto checkFlushing = [this, &comp] {
2047 Mutexed<State>::Locked state(mState);
2048 if (state->get() != FLUSHING) {
2049 return UNKNOWN_ERROR;
2050 }
2051 comp = state->comp;
2052 return OK;
2053 };
2054 if (tryAndReportOnError(checkFlushing) != OK) {
2055 return;
2056 }
2057
2058 std::list<std::unique_ptr<C2Work>> flushedWork;
2059 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2060 {
2061 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2062 flushedWork.splice(flushedWork.end(), *queue);
2063 }
2064 if (err != C2_OK) {
2065 // TODO: convert err into status_t
2066 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2067 }
2068
2069 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002070
2071 {
2072 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002073 if (state->get() == FLUSHING) {
2074 state->set(FLUSHED);
2075 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002076 }
2077 mCallback->onFlushCompleted();
2078}
2079
2080void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002081 std::shared_ptr<Codec2Client::Component> comp;
2082 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002083 Mutexed<State>::Locked state(mState);
2084 if (state->get() != FLUSHED) {
2085 return UNKNOWN_ERROR;
2086 }
2087 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002088 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002089 return OK;
2090 };
2091 if (tryAndReportOnError(setResuming) != OK) {
2092 return;
2093 }
2094
Wonsik Kime75a5da2020-02-14 17:29:03 -08002095 {
2096 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2097 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002098 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002099 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002100 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002101 }
2102
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002103 (void)mChannel->start(nullptr, nullptr, [&]{
2104 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2105 const std::unique_ptr<Config> &config = *configLocked;
2106 return config->mBuffersBoundToCodec;
2107 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002108
2109 {
2110 Mutexed<State>::Locked state(mState);
2111 if (state->get() != RESUMING) {
2112 state.unlock();
2113 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2114 state.lock();
2115 return;
2116 }
2117 state->set(RUNNING);
2118 }
2119
2120 (void)mChannel->requestInitialInputBuffers();
2121}
2122
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002123void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002124 std::shared_ptr<Codec2Client::Component> comp;
2125 auto checkState = [this, &comp] {
2126 Mutexed<State>::Locked state(mState);
2127 if (state->get() == RELEASED) {
2128 return INVALID_OPERATION;
2129 }
2130 comp = state->comp;
2131 return OK;
2132 };
2133 if (tryAndReportOnError(checkState) != OK) {
2134 return;
2135 }
2136
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002137 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2138 // the behavior here.
2139 sp<AMessage> params = msg;
2140 int32_t bitrate;
2141 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2142 params = msg->dup();
2143 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2144 }
2145
Houxiang Dai5a97b472021-03-22 17:56:04 +08002146 int32_t syncId = 0;
2147 if (params->findInt32("audio-hw-sync", &syncId)
2148 || params->findInt32("hw-av-sync-id", &syncId)) {
2149 configureTunneledVideoPlayback(comp, nullptr, params);
2150 }
2151
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002152 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2153 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002154
2155 /**
2156 * Handle input surface parameters
2157 */
2158 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002159 && (config->mDomain & Config::IS_ENCODER)
2160 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002161 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002162
2163 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2164 config->mISConfig->mStopped = false;
2165 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2166 config->mISConfig->mStopped = true;
2167 }
2168
2169 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002170 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002171 config->mISConfig->mSuspended = value;
2172 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002173 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002174 }
2175
2176 (void)config->mInputSurface->configure(*config->mISConfig);
2177 if (config->mISConfig->mStopped) {
2178 config->mInputFormat->setInt64(
2179 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2180 }
2181 }
2182
2183 std::vector<std::unique_ptr<C2Param>> configUpdate;
2184 (void)config->getConfigUpdateFromSdkParams(
2185 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2186 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2187 // Parameter synchronization is not defined when using input surface. For now, route
2188 // these directly to the component.
2189 if (config->mInputSurface == nullptr
2190 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2191 || comp->getName().find("c2.android.") == 0)) {
2192 mChannel->setParameters(configUpdate);
2193 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002194 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002195 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002196 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002197 }
2198}
2199
2200void CCodec::signalEndOfInputStream() {
2201 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2202}
2203
2204void CCodec::signalRequestIDRFrame() {
2205 std::shared_ptr<Codec2Client::Component> comp;
2206 {
2207 Mutexed<State>::Locked state(mState);
2208 if (state->get() == RELEASED) {
2209 ALOGD("no IDR request sent since component is released");
2210 return;
2211 }
2212 comp = state->comp;
2213 }
2214 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002215 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2216 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002217 std::vector<std::unique_ptr<C2Param>> params;
2218 params.push_back(
2219 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2220 config->setParameters(comp, params, C2_MAY_BLOCK);
2221}
2222
Wonsik Kim874ad382021-03-12 09:59:36 -08002223status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2224 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2225 const std::unique_ptr<Config> &config = *configLocked;
2226 return config->querySupportedParameters(names);
2227}
2228
2229status_t CCodec::describeParameter(
2230 const std::string &name, CodecParameterDescriptor *desc) {
2231 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2232 const std::unique_ptr<Config> &config = *configLocked;
2233 return config->describe(name, desc);
2234}
2235
2236status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2237 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2238 if (!comp) {
2239 return INVALID_OPERATION;
2240 }
2241 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2242 const std::unique_ptr<Config> &config = *configLocked;
2243 return config->subscribeToVendorConfigUpdate(comp, names);
2244}
2245
2246status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2247 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2248 if (!comp) {
2249 return INVALID_OPERATION;
2250 }
2251 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2252 const std::unique_ptr<Config> &config = *configLocked;
2253 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2254}
2255
Wonsik Kimab34ed62019-01-31 15:28:46 -08002256void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002257 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002258 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2259 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002260 }
2261 (new AMessage(kWhatWorkDone, this))->post();
2262}
2263
Wonsik Kimab34ed62019-01-31 15:28:46 -08002264void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2265 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002266 if (arrayIndex == 0) {
2267 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002268 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2269 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002270 if (config->mInputSurface) {
2271 config->mInputSurface->onInputBufferDone(frameIndex);
2272 }
2273 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002274}
2275
2276void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2277 TimePoint now = std::chrono::steady_clock::now();
2278 CCodecWatchdog::getInstance()->watch(this);
2279 switch (msg->what()) {
2280 case kWhatAllocate: {
2281 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002282 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002283 sp<RefBase> obj;
2284 CHECK(msg->findObject("codecInfo", &obj));
2285 allocate((MediaCodecInfo *)obj.get());
2286 break;
2287 }
2288 case kWhatConfigure: {
2289 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002290 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002291 sp<AMessage> format;
2292 CHECK(msg->findMessage("format", &format));
2293 configure(format);
2294 break;
2295 }
2296 case kWhatStart: {
2297 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002298 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002299 start();
2300 break;
2301 }
2302 case kWhatStop: {
2303 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002304 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002305 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002306 break;
2307 }
2308 case kWhatFlush: {
2309 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002310 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002311 flush();
2312 break;
2313 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002314 case kWhatRelease: {
2315 mChannel->release();
2316 mClient.reset();
2317 mClientListener.reset();
2318 break;
2319 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002320 case kWhatCreateInputSurface: {
2321 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002322 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002323 createInputSurface();
2324 break;
2325 }
2326 case kWhatSetInputSurface: {
2327 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002328 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002329 sp<RefBase> obj;
2330 CHECK(msg->findObject("surface", &obj));
2331 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2332 setInputSurface(surface);
2333 break;
2334 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002335 case kWhatWorkDone: {
2336 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002337 bool shouldPost = false;
2338 {
2339 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2340 if (queue->empty()) {
2341 break;
2342 }
2343 work.swap(queue->front());
2344 queue->pop_front();
2345 shouldPost = !queue->empty();
2346 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002347 if (shouldPost) {
2348 (new AMessage(kWhatWorkDone, this))->post();
2349 }
2350
Pawin Vongmasa36653902018-11-15 00:10:25 -08002351 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002352 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002353 sp<AMessage> outputFormat = nullptr;
2354 {
2355 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2356 const std::unique_ptr<Config> &config = *configLocked;
2357 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2358 config->watch<C2StreamInitDataInfo::output>();
2359 if (!work->worklets.empty()
2360 && (work->worklets.front()->output.flags
2361 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002362
Wonsik Kim75e22f42021-04-14 23:34:51 -07002363 // copy buffer info to config
2364 std::vector<std::unique_ptr<C2Param>> updates;
2365 for (const std::unique_ptr<C2Param> &param
2366 : work->worklets.front()->output.configUpdate) {
2367 updates.push_back(C2Param::Copy(*param));
2368 }
2369 unsigned stream = 0;
2370 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2371 work->worklets.front()->output.buffers;
2372 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2373 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2374 // move all info into output-stream #0 domain
2375 updates.emplace_back(
2376 C2Param::CopyAsStream(*info, true /* output */, stream));
2377 }
2378
2379 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2380 // for now only do the first block
2381 if (!blocks.empty()) {
2382 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2383 // block.crop().left, block.crop().top,
2384 // block.crop().width, block.crop().height,
2385 // block.width(), block.height());
2386 const C2ConstGraphicBlock &block = blocks[0];
2387 updates.emplace_back(new C2StreamCropRectInfo::output(
2388 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002389 }
2390 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002391 }
George Burgess IVc813a592020-02-22 22:54:44 -08002392
Wonsik Kim75e22f42021-04-14 23:34:51 -07002393 sp<AMessage> oldFormat = config->mOutputFormat;
2394 config->updateConfiguration(updates, config->mOutputDomain);
2395 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002396
Wonsik Kim75e22f42021-04-14 23:34:51 -07002397 // copy standard infos to graphic buffers if not already present (otherwise, we
2398 // may overwrite the actual intermediate value with a final value)
2399 stream = 0;
2400 const static C2Param::Index stdGfxInfos[] = {
2401 C2StreamRotationInfo::output::PARAM_TYPE,
2402 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2403 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2404 C2StreamHdrStaticInfo::output::PARAM_TYPE,
2405 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
2406 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2407 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2408 };
2409 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2410 if (buf->data().graphicBlocks().size()) {
2411 for (C2Param::Index ix : stdGfxInfos) {
2412 if (!buf->hasInfo(ix)) {
2413 const C2Param *param =
2414 config->getConfigParameterValue(ix.withStream(stream));
2415 if (param) {
2416 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2417 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2418 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002419 }
2420 }
2421 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002422 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002423 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002424 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002425 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302426 if (work->worklets.empty()
2427 || !work->worklets.back()
2428 || (work->worklets.back()->output.flags
2429 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2430 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2431 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002432 }
2433 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002434 initData = initDataWatcher.update();
2435 AmendOutputFormatWithCodecSpecificData(
2436 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2437 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002438 }
2439 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002440 }
2441 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002442 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002443 break;
2444 }
2445 case kWhatWatch: {
2446 // watch message already posted; no-op.
2447 break;
2448 }
2449 default: {
2450 ALOGE("unrecognized message");
2451 break;
2452 }
2453 }
2454 setDeadline(TimePoint::max(), 0ms, "none");
2455}
2456
2457void CCodec::setDeadline(
2458 const TimePoint &now,
2459 const std::chrono::milliseconds &timeout,
2460 const char *name) {
2461 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2462 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2463 deadline->set(now + (timeout * mult), name);
2464}
2465
ted.sun765db4d2020-06-23 14:03:41 +08002466status_t CCodec::configureTunneledVideoPlayback(
2467 std::shared_ptr<Codec2Client::Component> comp,
2468 sp<NativeHandle> *sidebandHandle,
2469 const sp<AMessage> &msg) {
2470 std::vector<std::unique_ptr<C2SettingResult>> failures;
2471
2472 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2473 C2PortTunneledModeTuning::output::AllocUnique(
2474 1,
2475 C2PortTunneledModeTuning::Struct::SIDEBAND,
2476 C2PortTunneledModeTuning::Struct::REALTIME,
2477 0);
2478 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2479 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2480 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2481 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2482 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2483 } else {
2484 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2485 tunneledPlayback->setFlexCount(0);
2486 }
2487 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2488 if (c2err != C2_OK) {
2489 return UNKNOWN_ERROR;
2490 }
2491
Houxiang Dai5a97b472021-03-22 17:56:04 +08002492 if (sidebandHandle == nullptr) {
2493 return OK;
2494 }
2495
ted.sun765db4d2020-06-23 14:03:41 +08002496 std::vector<std::unique_ptr<C2Param>> params;
2497 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2498 if (c2err == C2_OK && params.size() == 1u) {
2499 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2500 C2PortTunnelHandleTuning::output::From(params[0].get());
2501 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2502 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2503 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2504 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2505 memcpy(handle->data, videoTunnelSideband->m.values,
2506 sizeof(int32_t) * videoTunnelSideband->flexCount());
2507 return OK;
2508 } else {
2509 return NO_MEMORY;
2510 }
2511 }
2512 return UNKNOWN_ERROR;
2513}
2514
Pawin Vongmasa36653902018-11-15 00:10:25 -08002515void CCodec::initiateReleaseIfStuck() {
2516 std::string name;
2517 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002518 {
2519 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002520 if (deadline->get() < std::chrono::steady_clock::now()) {
2521 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002522 }
2523 if (deadline->get() != TimePoint::max()) {
2524 pendingDeadline = true;
2525 }
2526 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002527 bool tunneled = false;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002528 bool isMediaTypeKnown = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002529 {
Wonsik Kimabca11e2021-04-30 13:11:41 -07002530 static const std::set<std::string> kKnownMediaTypes{
2531 MIMETYPE_VIDEO_VP8,
2532 MIMETYPE_VIDEO_VP9,
2533 MIMETYPE_VIDEO_AV1,
2534 MIMETYPE_VIDEO_AVC,
2535 MIMETYPE_VIDEO_HEVC,
2536 MIMETYPE_VIDEO_MPEG4,
2537 MIMETYPE_VIDEO_H263,
2538 MIMETYPE_VIDEO_MPEG2,
2539 MIMETYPE_VIDEO_RAW,
2540 MIMETYPE_VIDEO_DOLBY_VISION,
2541
2542 MIMETYPE_AUDIO_AMR_NB,
2543 MIMETYPE_AUDIO_AMR_WB,
2544 MIMETYPE_AUDIO_MPEG,
2545 MIMETYPE_AUDIO_AAC,
2546 MIMETYPE_AUDIO_QCELP,
2547 MIMETYPE_AUDIO_VORBIS,
2548 MIMETYPE_AUDIO_OPUS,
2549 MIMETYPE_AUDIO_G711_ALAW,
2550 MIMETYPE_AUDIO_G711_MLAW,
2551 MIMETYPE_AUDIO_RAW,
2552 MIMETYPE_AUDIO_FLAC,
2553 MIMETYPE_AUDIO_MSGSM,
2554 MIMETYPE_AUDIO_AC3,
2555 MIMETYPE_AUDIO_EAC3,
2556
2557 MIMETYPE_IMAGE_ANDROID_HEIC,
2558 };
Wonsik Kim75e22f42021-04-14 23:34:51 -07002559 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2560 const std::unique_ptr<Config> &config = *configLocked;
2561 tunneled = config->mTunneled;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002562 isMediaTypeKnown = (kKnownMediaTypes.count(config->mCodingMediaType) != 0);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002563 }
Wonsik Kimabca11e2021-04-30 13:11:41 -07002564 if (!tunneled && isMediaTypeKnown && name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002565 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2566 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2567 if (elapsed >= kWorkDurationThreshold) {
2568 name = "queue";
2569 }
2570 if (elapsed > 0s) {
2571 pendingDeadline = true;
2572 }
2573 }
2574 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002575 // We're not stuck.
2576 if (pendingDeadline) {
2577 // If we are not stuck yet but still has deadline coming up,
2578 // post watch message to check back later.
2579 (new AMessage(kWhatWatch, this))->post();
2580 }
2581 return;
2582 }
2583
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002584 C2String compName;
2585 {
2586 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002587 if (!state->comp) {
2588 ALOGD("previous call to %s exceeded timeout "
2589 "and the component is already released", name.c_str());
2590 return;
2591 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002592 compName = state->comp->getName();
2593 }
2594 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2595
Pawin Vongmasa36653902018-11-15 00:10:25 -08002596 initiateRelease(false);
2597 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2598}
2599
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002600// static
2601PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002602 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002603 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002604 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002605 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2606 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002607 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002608 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2609 sp<IGraphicBufferProducer> gbp;
2610 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2611 status_t err = gbs->initCheck();
2612 if (err != OK) {
2613 ALOGE("Failed to create persistent input surface: error %d", err);
2614 return nullptr;
2615 }
2616 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002617 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002618 } else {
2619 return nullptr;
2620 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002621 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002622 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002623 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002624 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002625 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002626}
2627
Wonsik Kimffb889a2020-05-28 11:32:25 -07002628class IntfCache {
2629public:
2630 IntfCache() = default;
2631
2632 status_t init(const std::string &name) {
2633 std::shared_ptr<Codec2Client::Interface> intf{
2634 Codec2Client::CreateInterfaceByName(name.c_str())};
2635 if (!intf) {
2636 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2637 mInitStatus = NO_INIT;
2638 return NO_INIT;
2639 }
2640 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2641 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2642 C2ParamField{&sUsage, &sUsage.value}));
2643 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2644 if (err != C2_OK) {
2645 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2646 name.c_str(), err);
2647 mFields[0].status = err;
2648 }
2649 std::vector<std::unique_ptr<C2Param>> params;
2650 err = intf->query(
2651 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09002652 {
2653 C2StreamBufferTypeSetting::input::PARAM_TYPE,
2654 C2PortAllocatorsTuning::input::PARAM_TYPE
2655 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07002656 C2_MAY_BLOCK,
2657 &params);
2658 if (err != C2_OK && err != C2_BAD_INDEX) {
2659 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2660 name.c_str(), err);
2661 }
2662 while (!params.empty()) {
2663 C2Param *param = params.back().release();
2664 params.pop_back();
2665 if (!param) {
2666 continue;
2667 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002668 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
2669 mInputStreamFormat.reset(
2670 C2StreamBufferTypeSetting::input::From(param));
2671 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002672 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002673 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002674 }
2675 }
2676 mInitStatus = OK;
2677 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002678 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002679
2680 status_t initCheck() const { return mInitStatus; }
2681
2682 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2683 CHECK_EQ(1u, mFields.size());
2684 return mFields[0];
2685 }
2686
2687 const C2ApiFeaturesSetting &getApiFeatures() const {
2688 return mApiFeatures;
2689 }
2690
Taehwan Kim900b49c2021-12-13 11:16:22 +09002691 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
2692 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
2693 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
2694 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
2695 param->invalidate();
2696 return param;
2697 }();
2698 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
2699 }
2700
Wonsik Kimffb889a2020-05-28 11:32:25 -07002701 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2702 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2703 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2704 C2PortAllocatorsTuning::input::AllocUnique(0);
2705 param->invalidate();
2706 return param;
2707 }();
2708 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2709 }
2710
2711private:
2712 status_t mInitStatus{NO_INIT};
2713
2714 std::vector<C2FieldSupportedValuesQuery> mFields;
2715 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09002716 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002717 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2718};
2719
2720static const IntfCache &GetIntfCache(const std::string &name) {
2721 static IntfCache sNullIntfCache;
2722 static std::mutex sMutex;
2723 static std::map<std::string, IntfCache> sCache;
2724 std::unique_lock<std::mutex> lock{sMutex};
2725 auto it = sCache.find(name);
2726 if (it == sCache.end()) {
2727 lock.unlock();
2728 IntfCache intfCache;
2729 status_t err = intfCache.init(name);
2730 if (err != OK) {
2731 return sNullIntfCache;
2732 }
2733 lock.lock();
2734 it = sCache.insert({name, std::move(intfCache)}).first;
2735 }
2736 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002737}
2738
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002739static status_t GetCommonAllocatorIds(
2740 const std::vector<std::string> &names,
2741 C2Allocator::type_t type,
2742 std::set<C2Allocator::id_t> *ids) {
2743 int poolMask = GetCodec2PoolMask();
2744 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2745 C2Allocator::id_t defaultAllocatorId =
2746 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2747
2748 ids->clear();
2749 if (names.empty()) {
2750 return OK;
2751 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002752 bool firstIteration = true;
2753 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002754 const IntfCache &intfCache = GetIntfCache(name);
2755 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002756 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002757 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002758 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
2759 if (streamFormat) {
2760 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
2761 if (streamFormat.value == C2BufferData::GRAPHIC
2762 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
2763 allocatorType = C2Allocator::GRAPHIC;
2764 }
2765
2766 if (type != allocatorType) {
2767 // requested type is not supported at input allocators
2768 ids->clear();
2769 ids->insert(defaultAllocatorId);
2770 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
2771 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
2772 break;
2773 }
2774 }
2775
Wonsik Kimffb889a2020-05-28 11:32:25 -07002776 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002777 if (firstIteration) {
2778 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002779 if (allocators && allocators.flexCount() > 0) {
2780 ids->insert(allocators.m.values,
2781 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002782 }
2783 if (ids->empty()) {
2784 // The component does not advertise allocators. Use default.
2785 ids->insert(defaultAllocatorId);
2786 }
2787 continue;
2788 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002789 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002790 if (allocators && allocators.flexCount() > 0) {
2791 filtered = true;
2792 for (auto it = ids->begin(); it != ids->end(); ) {
2793 bool found = false;
2794 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2795 if (allocators.m.values[j] == *it) {
2796 found = true;
2797 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002798 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002799 }
2800 if (found) {
2801 ++it;
2802 } else {
2803 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002804 }
2805 }
2806 }
2807 if (!filtered) {
2808 // The component does not advertise supported allocators. Use default.
2809 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2810 if (ids->size() != (containsDefault ? 1 : 0)) {
2811 ids->clear();
2812 if (containsDefault) {
2813 ids->insert(defaultAllocatorId);
2814 }
2815 }
2816 }
2817 }
2818 // Finally, filter with pool masks
2819 for (auto it = ids->begin(); it != ids->end(); ) {
2820 if ((poolMask >> *it) & 1) {
2821 ++it;
2822 } else {
2823 it = ids->erase(it);
2824 }
2825 }
2826 return OK;
2827}
2828
2829static status_t CalculateMinMaxUsage(
2830 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2831 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2832 *minUsage = 0;
2833 *maxUsage = ~0ull;
2834 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002835 const IntfCache &intfCache = GetIntfCache(name);
2836 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002837 continue;
2838 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002839 const C2FieldSupportedValuesQuery &usageSupportedValues =
2840 intfCache.getUsageSupportedValues();
2841 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002842 continue;
2843 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002844 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002845 if (supported.type != C2FieldSupportedValues::FLAGS) {
2846 continue;
2847 }
2848 if (supported.values.empty()) {
2849 *maxUsage = 0;
2850 continue;
2851 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08002852 if (supported.values.size() > 1) {
2853 *minUsage |= supported.values[1].u64;
2854 } else {
2855 *minUsage |= supported.values[0].u64;
2856 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002857 int64_t currentMaxUsage = 0;
2858 for (const C2Value::Primitive &flags : supported.values) {
2859 currentMaxUsage |= flags.u64;
2860 }
2861 *maxUsage &= currentMaxUsage;
2862 }
2863 return OK;
2864}
2865
2866// static
2867status_t CCodec::CanFetchLinearBlock(
2868 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002869 for (const std::string &name : names) {
2870 const IntfCache &intfCache = GetIntfCache(name);
2871 if (intfCache.initCheck() != OK) {
2872 continue;
2873 }
2874 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2875 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2876 *isCompatible = false;
2877 return OK;
2878 }
2879 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002880 std::set<C2Allocator::id_t> allocators;
2881 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2882 if (allocators.empty()) {
2883 *isCompatible = false;
2884 return OK;
2885 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002886
2887 uint64_t minUsage = 0;
2888 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002889 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002890 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002891 *isCompatible = ((maxUsage & minUsage) == minUsage);
2892 return OK;
2893}
2894
2895static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2896 static std::mutex sMutex{};
2897 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2898 std::unique_lock<std::mutex> lock{sMutex};
2899 std::shared_ptr<C2BlockPool> pool;
2900 auto it = sPools.find(allocId);
2901 if (it == sPools.end()) {
2902 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2903 if (err == OK) {
2904 sPools.emplace(allocId, pool);
2905 } else {
2906 pool.reset();
2907 }
2908 } else {
2909 pool = it->second;
2910 }
2911 return pool;
2912}
2913
2914// static
2915std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2916 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002917 std::set<C2Allocator::id_t> allocators;
2918 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2919 if (allocators.empty()) {
2920 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2921 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002922
2923 uint64_t minUsage = 0;
2924 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002925 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002926 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002927 if ((maxUsage & minUsage) != minUsage) {
2928 allocators.clear();
2929 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2930 }
2931 std::shared_ptr<C2LinearBlock> block;
2932 for (C2Allocator::id_t allocId : allocators) {
2933 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2934 if (!pool) {
2935 continue;
2936 }
2937 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2938 if (err != C2_OK || !block) {
2939 block.reset();
2940 continue;
2941 }
2942 break;
2943 }
2944 return block;
2945}
2946
2947// static
2948status_t CCodec::CanFetchGraphicBlock(
2949 const std::vector<std::string> &names, bool *isCompatible) {
2950 uint64_t minUsage = 0;
2951 uint64_t maxUsage = ~0ull;
2952 std::set<C2Allocator::id_t> allocators;
2953 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2954 if (allocators.empty()) {
2955 *isCompatible = false;
2956 return OK;
2957 }
2958 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2959 *isCompatible = ((maxUsage & minUsage) == minUsage);
2960 return OK;
2961}
2962
2963// static
2964std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2965 int32_t width,
2966 int32_t height,
2967 int32_t format,
2968 uint64_t usage,
2969 const std::vector<std::string> &names) {
2970 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2971 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2972 ALOGD("Unrecognized pixel format: %d", format);
2973 return nullptr;
2974 }
2975 uint64_t minUsage = 0;
2976 uint64_t maxUsage = ~0ull;
2977 std::set<C2Allocator::id_t> allocators;
2978 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2979 if (allocators.empty()) {
2980 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2981 }
2982 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2983 minUsage |= usage;
2984 if ((maxUsage & minUsage) != minUsage) {
2985 allocators.clear();
2986 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2987 }
2988 std::shared_ptr<C2GraphicBlock> block;
2989 for (C2Allocator::id_t allocId : allocators) {
2990 std::shared_ptr<C2BlockPool> pool;
2991 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2992 if (err != C2_OK || !pool) {
2993 continue;
2994 }
2995 err = pool->fetchGraphicBlock(
2996 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2997 if (err != C2_OK || !block) {
2998 block.reset();
2999 continue;
3000 }
3001 break;
3002 }
3003 return block;
3004}
3005
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003006} // namespace android