blob: abfac8b3cf1b5ebb06b4284c6bb02cd25dd1000a [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>
Songyue Han1e6769b2023-08-30 18:09:27 +000048#include <media/stagefright/MediaCodecMetricsConstants.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080049#include <media/stagefright/PersistentSurface.h>
Brian Lindahlff74e9d2023-07-20 14:44:04 -060050#include <media/stagefright/RenderedFrameInfo.h>
ted.sun765db4d2020-06-23 14:03:41 +080051#include <utils/NativeHandle.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080052
53#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080054#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070055#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080056#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080057#include "InputSurfaceWrapper.h"
58
59extern "C" android::PersistentSurface *CreateInputSurface();
60
61namespace android {
62
63using namespace std::chrono_literals;
64using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
65using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080066using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080067
Wonsik Kim9917d4a2019-10-24 12:56:38 -070068typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070069typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070070
Pawin Vongmasa36653902018-11-15 00:10:25 -080071namespace {
72
73class CCodecWatchdog : public AHandler {
74private:
75 enum {
76 kWhatWatch,
77 };
78 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
79
80public:
81 static sp<CCodecWatchdog> getInstance() {
82 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
83 static std::once_flag flag;
84 // Call Init() only once.
85 std::call_once(flag, Init, instance);
86 return instance;
87 }
88
89 ~CCodecWatchdog() = default;
90
91 void watch(sp<CCodec> codec) {
92 bool shouldPost = false;
93 {
94 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
95 // If a watch message is in flight, piggy-back this instance as well.
96 // Otherwise, post a new watch message.
97 shouldPost = codecs->empty();
98 codecs->emplace(codec);
99 }
100 if (shouldPost) {
101 ALOGV("posting watch message");
102 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
103 }
104 }
105
106protected:
107 void onMessageReceived(const sp<AMessage> &msg) {
108 switch (msg->what()) {
109 case kWhatWatch: {
110 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
111 ALOGV("watch for %zu codecs", codecs->size());
112 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
113 sp<CCodec> codec = it->promote();
114 if (codec == nullptr) {
115 continue;
116 }
117 codec->initiateReleaseIfStuck();
118 }
119 codecs->clear();
120 break;
121 }
122
123 default: {
124 TRESPASS("CCodecWatchdog: unrecognized message");
125 }
126 }
127 }
128
129private:
130 CCodecWatchdog() : mLooper(new ALooper) {}
131
132 static void Init(const sp<CCodecWatchdog> &thiz) {
133 ALOGV("Init");
134 thiz->mLooper->setName("CCodecWatchdog");
135 thiz->mLooper->registerHandler(thiz);
136 thiz->mLooper->start();
137 }
138
139 sp<ALooper> mLooper;
140
141 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
142};
143
144class C2InputSurfaceWrapper : public InputSurfaceWrapper {
145public:
146 explicit C2InputSurfaceWrapper(
147 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
148 mSurface(surface) {
149 }
150
151 ~C2InputSurfaceWrapper() override = default;
152
153 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
154 if (mConnection != nullptr) {
155 return ALREADY_EXISTS;
156 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800157 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800158 }
159
160 void disconnect() override {
161 if (mConnection != nullptr) {
162 mConnection->disconnect();
163 mConnection = nullptr;
164 }
165 }
166
167 status_t start() override {
168 // InputSurface does not distinguish started state
169 return OK;
170 }
171
172 status_t signalEndOfInputStream() override {
173 C2InputSurfaceEosTuning eos(true);
174 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800175 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800176 if (err != C2_OK) {
177 return UNKNOWN_ERROR;
178 }
179 return OK;
180 }
181
182 status_t configure(Config &config __unused) {
183 // TODO
184 return OK;
185 }
186
187private:
188 std::shared_ptr<Codec2Client::InputSurface> mSurface;
189 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
190};
191
192class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
193public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700194 typedef hardware::media::omx::V1_0::Status OmxStatus;
195
Pawin Vongmasa36653902018-11-15 00:10:25 -0800196 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700197 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800198 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700199 uint32_t height,
200 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800201 : mSource(source), mWidth(width), mHeight(height) {
202 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700203 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800204 }
205 ~GraphicBufferSourceWrapper() override = default;
206
207 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
208 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700209 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800210 mNode->setFrameSize(mWidth, mHeight);
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700211 // Usage is queried during configure(), so setting it beforehand.
Sungtak Lee0cd4fbc2023-02-02 00:59:01 +0000212 // 64 bit set parameter is existing only in C2OMXNode.
213 OMX_U64 usage64 = mConfig.mUsage;
214 status_t res = mNode->setParameter(
215 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits64,
216 &usage64, sizeof(usage64));
217
218 if (res != OK) {
219 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
220 (void)mNode->setParameter(
221 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
222 &usage, sizeof(usage));
223 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700224
Yanqiang Fanc56f3e62021-09-28 16:54:07 +0800225 return GetStatus(mSource->configure(
226 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800227 }
228
229 void disconnect() override {
230 if (mNode == nullptr) {
231 return;
232 }
233 sp<IOMXBufferSource> source = mNode->getSource();
234 if (source == nullptr) {
235 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
236 return;
237 }
238 source->onOmxIdle();
239 source->onOmxLoaded();
240 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700241 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800242 }
243
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700244 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
245 if (status.isOk()) {
246 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
247 } else if (status.isDeadObject()) {
248 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800249 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700250 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800251 }
252
253 status_t start() override {
254 sp<IOMXBufferSource> source = mNode->getSource();
255 if (source == nullptr) {
256 return NO_INIT;
257 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900258
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800259 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800260 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900261
Wonsik Kim34d66012021-03-01 16:40:33 -0800262 OMX_PARAM_PORTDEFINITIONTYPE param;
263 param.nPortIndex = kPortIndexInput;
264 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
265 &param, sizeof(param));
266 if (err == OK) {
267 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900268 }
269
270 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800271 source->onInputBufferAdded(i);
272 }
273
274 source->onOmxExecuting();
275 return OK;
276 }
277
278 status_t signalEndOfInputStream() override {
279 return GetStatus(mSource->signalEndOfInputStream());
280 }
281
282 status_t configure(Config &config) {
283 std::stringstream status;
284 status_t err = OK;
285
286 // handle each configuration granually, in case we need to handle part of the configuration
287 // elsewhere
288
289 // TRICKY: we do not unset frame delay repeating
290 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
291 int64_t us = 1e6 / config.mMinFps + 0.5;
292 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
293 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
294 if (res != OK) {
295 status << " (=> " << asString(res) << ")";
296 err = res;
297 }
298 mConfig.mMinFps = config.mMinFps;
299 }
300
301 // pts gap
302 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
303 if (mNode != nullptr) {
304 OMX_PARAM_U32TYPE ptrGapParam = {};
305 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700306 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800307 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
308 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700309 // float -> uint32_t is undefined if the value is negative.
310 // First convert to int32_t to ensure the expected behavior.
311 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800312 (void)mNode->setParameter(
313 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
314 &ptrGapParam, sizeof(ptrGapParam));
315 }
316 }
317
318 // max fps
319 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700320 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800321 && config.mMaxFps != mConfig.mMaxFps) {
322 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
323 status << " maxFps=" << config.mMaxFps;
324 if (res != OK) {
325 status << " (=> " << asString(res) << ")";
326 err = res;
327 }
328 mConfig.mMaxFps = config.mMaxFps;
329 }
330
331 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
332 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
333 status << " timeOffset " << config.mTimeOffsetUs << "us";
334 if (res != OK) {
335 status << " (=> " << asString(res) << ")";
336 err = res;
337 }
338 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
339 }
340
341 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
342 status_t res =
343 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
344 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
345 if (res != OK) {
346 status << " (=> " << asString(res) << ")";
347 err = res;
348 }
349 mConfig.mCaptureFps = config.mCaptureFps;
350 mConfig.mCodedFps = config.mCodedFps;
351 }
352
353 if (config.mStartAtUs != mConfig.mStartAtUs
354 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
355 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
356 status << " start at " << config.mStartAtUs << "us";
357 if (res != OK) {
358 status << " (=> " << asString(res) << ")";
359 err = res;
360 }
361 mConfig.mStartAtUs = config.mStartAtUs;
362 mConfig.mStopped = config.mStopped;
363 }
364
365 // suspend-resume
366 if (config.mSuspended != mConfig.mSuspended) {
367 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
368 status << " " << (config.mSuspended ? "suspend" : "resume")
369 << " at " << config.mSuspendAtUs << "us";
370 if (res != OK) {
371 status << " (=> " << asString(res) << ")";
372 err = res;
373 }
374 mConfig.mSuspended = config.mSuspended;
375 mConfig.mSuspendAtUs = config.mSuspendAtUs;
376 }
377
378 if (config.mStopped != mConfig.mStopped && config.mStopped) {
379 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
380 status << " stop at " << config.mStopAtUs << "us";
381 if (res != OK) {
382 status << " (=> " << asString(res) << ")";
383 err = res;
384 } else {
385 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700386 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
387 [&res, &delayUs = config.mInputDelayUs](
388 auto status, auto stopTimeOffsetUs) {
389 res = static_cast<status_t>(status);
390 delayUs = stopTimeOffsetUs;
391 });
392 if (!trans.isOk()) {
393 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
394 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800395 if (res != OK) {
396 status << " (=> " << asString(res) << ")";
397 } else {
398 status << "=" << config.mInputDelayUs << "us";
399 }
400 mConfig.mInputDelayUs = config.mInputDelayUs;
401 }
402 mConfig.mStopAtUs = config.mStopAtUs;
403 mConfig.mStopped = config.mStopped;
404 }
405
406 // color aspects (android._color-aspects)
407
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700408 // consumer usage is queried earlier.
409
Wonsik Kima1335e12021-04-22 16:28:29 -0700410 // priority
411 if (mConfig.mPriority != config.mPriority) {
412 if (config.mPriority != INT_MAX) {
413 mNode->setPriority(config.mPriority);
414 }
415 mConfig.mPriority = config.mPriority;
416 }
417
Wonsik Kimbd557932019-07-02 15:51:20 -0700418 if (status.str().empty()) {
419 ALOGD("ISConfig not changed");
420 } else {
421 ALOGD("ISConfig%s", status.str().c_str());
422 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800423 return err;
424 }
425
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700426 void onInputBufferDone(c2_cntr64_t index) override {
427 mNode->onInputBufferDone(index);
428 }
429
Wonsik Kim673dd192021-01-29 14:58:12 -0800430 android_dataspace getDataspace() override {
431 return mNode->getDataspace();
432 }
433
Pawin Vongmasa36653902018-11-15 00:10:25 -0800434private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700435 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800436 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700437 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800438 uint32_t mWidth;
439 uint32_t mHeight;
440 Config mConfig;
441};
442
443class Codec2ClientInterfaceWrapper : public C2ComponentStore {
444 std::shared_ptr<Codec2Client> mClient;
445
446public:
447 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
448 : mClient(client) { }
449
450 virtual ~Codec2ClientInterfaceWrapper() = default;
451
452 virtual c2_status_t config_sm(
453 const std::vector<C2Param *> &params,
454 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
455 return mClient->config(params, C2_MAY_BLOCK, failures);
456 };
457
458 virtual c2_status_t copyBuffer(
459 std::shared_ptr<C2GraphicBuffer>,
460 std::shared_ptr<C2GraphicBuffer>) {
461 return C2_OMITTED;
462 }
463
464 virtual c2_status_t createComponent(
465 C2String, std::shared_ptr<C2Component> *const component) {
466 component->reset();
467 return C2_OMITTED;
468 }
469
470 virtual c2_status_t createInterface(
471 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
472 interface->reset();
473 return C2_OMITTED;
474 }
475
476 virtual c2_status_t query_sm(
477 const std::vector<C2Param *> &stackParams,
478 const std::vector<C2Param::Index> &heapParamIndices,
479 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
480 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
481 }
482
483 virtual c2_status_t querySupportedParams_nb(
484 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
485 return mClient->querySupportedParams(params);
486 }
487
488 virtual c2_status_t querySupportedValues_sm(
489 std::vector<C2FieldSupportedValuesQuery> &fields) const {
490 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
491 }
492
493 virtual C2String getName() const {
494 return mClient->getName();
495 }
496
497 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
498 return mClient->getParamReflector();
499 }
500
501 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
502 return std::vector<std::shared_ptr<const C2Component::Traits>>();
503 }
504};
505
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800506void RevertOutputFormatIfNeeded(
507 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
508 // We used to not report changes to these keys to the client.
509 const static std::set<std::string> sIgnoredKeys({
510 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800511 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800512 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800513 KEY_MAX_WIDTH,
514 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800515 "csd-0",
516 "csd-1",
517 "csd-2",
518 });
519 if (currentFormat == oldFormat) {
520 return;
521 }
522 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
523 AMessage::Type type;
524 for (size_t i = diff->countEntries(); i > 0; --i) {
525 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
526 diff->removeEntryAt(i - 1);
527 }
528 }
529 if (diff->countEntries() == 0) {
530 currentFormat = oldFormat;
531 }
532}
533
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700534void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700535 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700536 const sp<AMessage> &outputFormat) {
537 if (mediaType == MIMETYPE_VIDEO_AVC) {
538 // Codec specific data should be SPS and PPS in a single buffer,
539 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
540 // We separate the two and put them into the output format
541 // under the keys "csd-0" and "csd-1".
542
543 unsigned csdIndex = 0;
544
545 const uint8_t *nalStart;
546 size_t nalSize;
547 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
548 sp<ABuffer> csd = new ABuffer(nalSize + 4);
549 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
550 memcpy(csd->data() + 4, nalStart, nalSize);
551
552 outputFormat->setBuffer(
553 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
554
555 ++csdIndex;
556 }
557
558 if (csdIndex != 2) {
559 ALOGW("Expected two NAL units from AVC codec config, but %u found",
560 csdIndex);
561 }
562 } else {
563 // For everything else we just stash the codec specific data into
564 // the output format as a single piece of csd under "csd-0".
565 sp<ABuffer> csd = new ABuffer(size);
566 memcpy(csd->data(), data, size);
567 csd->setRange(0, size);
568 outputFormat->setBuffer("csd-0", csd);
569 }
570}
571
Pawin Vongmasa36653902018-11-15 00:10:25 -0800572} // namespace
573
574// CCodec::ClientListener
575
576struct CCodec::ClientListener : public Codec2Client::Listener {
577
578 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
579
580 virtual void onWorkDone(
581 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800582 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800583 (void)component;
584 sp<CCodec> codec(mCodec.promote());
585 if (!codec) {
586 return;
587 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800588 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800589 }
590
591 virtual void onTripped(
592 const std::weak_ptr<Codec2Client::Component>& component,
593 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
594 ) override {
595 // TODO
596 (void)component;
597 (void)settingResult;
598 }
599
600 virtual void onError(
601 const std::weak_ptr<Codec2Client::Component>& component,
602 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800603 {
604 // Component is only used for reporting as we use a separate listener for each instance
605 std::shared_ptr<Codec2Client::Component> comp = component.lock();
606 if (!comp) {
607 ALOGD("Component died with error: 0x%x", errorCode);
608 } else {
609 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
610 }
611 }
612
613 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800614 // Note: for now we do not propagate the error code to MediaCodec
615 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800616 sp<CCodec> codec(mCodec.promote());
617 if (!codec || !codec->mCallback) {
618 return;
619 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800620 codec->mCallback->onError(
621 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
622 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800623 }
624
625 virtual void onDeath(
626 const std::weak_ptr<Codec2Client::Component>& component) override {
627 { // Log the death of the component.
628 std::shared_ptr<Codec2Client::Component> comp = component.lock();
629 if (!comp) {
630 ALOGE("Codec2 component died.");
631 } else {
632 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
633 }
634 }
635
636 // Report to MediaCodec.
637 sp<CCodec> codec(mCodec.promote());
638 if (!codec || !codec->mCallback) {
639 return;
640 }
641 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
642 }
643
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800644 virtual void onFrameRendered(uint64_t bufferQueueId,
645 int32_t slotId,
646 int64_t timestampNs) override {
647 // TODO: implement
648 (void)bufferQueueId;
649 (void)slotId;
650 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800651 }
652
653 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800654 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800655 sp<CCodec> codec(mCodec.promote());
656 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800657 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800658 }
659 }
660
661private:
662 wp<CCodec> mCodec;
663};
664
665// CCodecCallbackImpl
666
667class CCodecCallbackImpl : public CCodecCallback {
668public:
669 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
670 ~CCodecCallbackImpl() override = default;
671
672 void onError(status_t err, enum ActionCode actionCode) override {
673 mCodec->mCallback->onError(err, actionCode);
674 }
675
676 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
Brian Lindahlff74e9d2023-07-20 14:44:04 -0600677 mCodec->mCallback->onOutputFramesRendered({RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
Pawin Vongmasa36653902018-11-15 00:10:25 -0800678 }
679
Pawin Vongmasa36653902018-11-15 00:10:25 -0800680 void onOutputBuffersChanged() override {
681 mCodec->mCallback->onOutputBuffersChanged();
682 }
683
Guillaume Chelfi5ffbcb32021-04-12 14:23:43 +0200684 void onFirstTunnelFrameReady() override {
685 mCodec->mCallback->onFirstTunnelFrameReady();
686 }
687
Pawin Vongmasa36653902018-11-15 00:10:25 -0800688private:
689 CCodec *mCodec;
690};
691
692// CCodec
693
694CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700695 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
696 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800697}
698
699CCodec::~CCodec() {
700}
701
702std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
703 return mChannel;
704}
705
706status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
707 status_t err = job();
708 if (err != C2_OK) {
709 mCallback->onError(err, ACTION_CODE_FATAL);
710 }
711 return err;
712}
713
714void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
715 auto setAllocating = [this] {
716 Mutexed<State>::Locked state(mState);
717 if (state->get() != RELEASED) {
718 return INVALID_OPERATION;
719 }
720 state->set(ALLOCATING);
721 return OK;
722 };
723 if (tryAndReportOnError(setAllocating) != OK) {
724 return;
725 }
726
727 sp<RefBase> codecInfo;
728 CHECK(msg->findObject("codecInfo", &codecInfo));
729 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
730
731 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
732 allocMsg->setObject("codecInfo", codecInfo);
733 allocMsg->post();
734}
735
736void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
737 if (codecInfo == nullptr) {
738 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
739 return;
740 }
741 ALOGD("allocate(%s)", codecInfo->getCodecName());
742 mClientListener.reset(new ClientListener(this));
743
744 AString componentName = codecInfo->getCodecName();
745 std::shared_ptr<Codec2Client> client;
746
747 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700748 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800749 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800750 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800751 SetPreferredCodec2ComponentStore(
752 std::make_shared<Codec2ClientInterfaceWrapper>(client));
753 }
754
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900755 std::shared_ptr<Codec2Client::Component> comp;
756 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800757 componentName.c_str(),
758 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900759 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800760 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900761 if (status != C2_OK) {
762 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800763 Mutexed<State>::Locked state(mState);
764 state->set(RELEASED);
765 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900766 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800767 state.lock();
768 return;
769 }
770 ALOGI("Created component [%s]", componentName.c_str());
771 mChannel->setComponent(comp);
772 auto setAllocated = [this, comp, client] {
773 Mutexed<State>::Locked state(mState);
774 if (state->get() != ALLOCATING) {
775 state->set(RELEASED);
776 return UNKNOWN_ERROR;
777 }
778 state->set(ALLOCATED);
779 state->comp = comp;
780 mClient = client;
781 return OK;
782 };
783 if (tryAndReportOnError(setAllocated) != OK) {
784 return;
785 }
786
787 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700788 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
789 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800790 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800791 if (err != OK) {
792 ALOGW("Failed to initialize configuration support");
793 // TODO: report error once we complete implementation.
794 }
795 config->queryConfiguration(comp);
796
797 mCallback->onComponentAllocated(componentName.c_str());
798}
799
800void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
801 auto checkAllocated = [this] {
802 Mutexed<State>::Locked state(mState);
803 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
804 };
805 if (tryAndReportOnError(checkAllocated) != OK) {
806 return;
807 }
808
809 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
810 msg->setMessage("format", format);
811 msg->post();
812}
813
814void CCodec::configure(const sp<AMessage> &msg) {
815 std::shared_ptr<Codec2Client::Component> comp;
816 auto checkAllocated = [this, &comp] {
817 Mutexed<State>::Locked state(mState);
818 if (state->get() != ALLOCATED) {
819 state->set(RELEASED);
820 return UNKNOWN_ERROR;
821 }
822 comp = state->comp;
823 return OK;
824 };
825 if (tryAndReportOnError(checkAllocated) != OK) {
826 return;
827 }
828
829 auto doConfig = [msg, comp, this]() -> status_t {
830 AString mime;
831 if (!msg->findString("mime", &mime)) {
832 return BAD_VALUE;
833 }
834
835 int32_t encoder;
836 if (!msg->findInt32("encoder", &encoder)) {
837 encoder = false;
838 }
839
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800840 int32_t flags;
841 if (!msg->findInt32("flags", &flags)) {
842 return BAD_VALUE;
843 }
844
Pawin Vongmasa36653902018-11-15 00:10:25 -0800845 // TODO: read from intf()
846 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
847 return UNKNOWN_ERROR;
848 }
849
850 int32_t storeMeta;
851 if (encoder
852 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
853 && storeMeta != kMetadataBufferTypeInvalid) {
854 if (storeMeta != kMetadataBufferTypeANWBuffer) {
855 ALOGD("Only ANW buffers are supported for legacy metadata mode");
856 return BAD_VALUE;
857 }
858 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
859 }
860
ted.sun765db4d2020-06-23 14:03:41 +0800861 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800862 sp<RefBase> obj;
863 sp<Surface> surface;
864 if (msg->findObject("native-window", &obj)) {
865 surface = static_cast<Surface *>(obj.get());
ted.sun765db4d2020-06-23 14:03:41 +0800866 // setup tunneled playback
867 if (surface != nullptr) {
868 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
869 const std::unique_ptr<Config> &config = *configLocked;
870 if ((config->mDomain & Config::IS_DECODER)
871 && (config->mDomain & Config::IS_VIDEO)) {
872 int32_t tunneled;
873 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
874 ALOGI("Configuring TUNNELED video playback.");
875
876 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
877 if (err != OK) {
878 ALOGE("configureTunneledVideoPlayback failed!");
879 return err;
880 }
881 config->mTunneled = true;
882 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +0100883
884 int32_t pushBlankBuffersOnStop = 0;
885 if (msg->findInt32(KEY_PUSH_BLANK_BUFFERS_ON_STOP, &pushBlankBuffersOnStop)) {
886 config->mPushBlankBuffersOnStop = pushBlankBuffersOnStop == 1;
887 }
shuanglong.wang480a8362023-02-17 20:55:51 +0800888 // secure compoment or protected content default with
889 // "push-blank-buffers-on-shutdown" flag
890 if (!config->mPushBlankBuffersOnStop) {
891 int32_t usageProtected;
892 if (comp->getName().find(".secure") != std::string::npos) {
893 config->mPushBlankBuffersOnStop = true;
894 } else if (msg->findInt32("protected", &usageProtected) && usageProtected) {
895 config->mPushBlankBuffersOnStop = true;
896 }
897 }
ted.sun765db4d2020-06-23 14:03:41 +0800898 }
899 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800900 setSurface(surface);
901 }
902
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700903 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
904 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800905 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800906 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
907 ALOGD("[%s] buffers are %sbound to CCodec for this session",
908 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800909
Wonsik Kim1114eea2019-02-25 14:35:24 -0800910 // Enforce required parameters
911 int32_t i32;
912 float flt;
913 if (config->mDomain & Config::IS_AUDIO) {
914 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
915 ALOGD("sample rate is missing, which is required for audio components.");
916 return BAD_VALUE;
917 }
918 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
919 ALOGD("channel count is missing, which is required for audio components.");
920 return BAD_VALUE;
921 }
922 if ((config->mDomain & Config::IS_ENCODER)
923 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
924 && !msg->findInt32(KEY_BIT_RATE, &i32)
925 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
926 ALOGD("bitrate is missing, which is required for audio encoders.");
927 return BAD_VALUE;
928 }
929 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800930 int32_t width = 0;
931 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800932 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800933 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800934 ALOGD("width is missing, which is required for image/video components.");
935 return BAD_VALUE;
936 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800937 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800938 ALOGD("height is missing, which is required for image/video components.");
939 return BAD_VALUE;
940 }
941 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700942 int32_t mode = BITRATE_MODE_VBR;
943 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700944 if (!msg->findInt32(KEY_QUALITY, &i32)) {
945 ALOGD("quality is missing, which is required for video encoders in CQ.");
946 return BAD_VALUE;
947 }
948 } else {
949 if (!msg->findInt32(KEY_BIT_RATE, &i32)
950 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
951 ALOGD("bitrate is missing, which is required for video encoders.");
952 return BAD_VALUE;
953 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800954 }
955 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
956 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
957 ALOGD("I frame interval is missing, which is required for video encoders.");
958 return BAD_VALUE;
959 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700960 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
961 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
962 ALOGD("frame rate is missing, which is required for video encoders.");
963 return BAD_VALUE;
964 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800965 }
966 }
967
Pawin Vongmasa36653902018-11-15 00:10:25 -0800968 /*
969 * Handle input surface configuration
970 */
971 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
972 && (config->mDomain & Config::IS_ENCODER)) {
973 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
974 {
975 config->mISConfig->mMinFps = 0;
976 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800977 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800978 config->mISConfig->mMinFps = 1e6 / value;
979 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700980 if (!msg->findFloat(
981 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
982 config->mISConfig->mMaxFps = -1;
983 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800984 config->mISConfig->mMinAdjustedFps = 0;
985 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800986 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800987 if (value < 0 && value >= INT32_MIN) {
988 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700989 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800990 } else if (value > 0 && value <= INT32_MAX) {
991 config->mISConfig->mMinAdjustedFps = 1e6 / value;
992 }
993 }
994 }
995
996 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700997 bool captureFpsFound = false;
998 double timeLapseFps;
999 float captureRate;
1000 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
1001 config->mISConfig->mCaptureFps = timeLapseFps;
1002 captureFpsFound = true;
1003 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
1004 config->mISConfig->mCaptureFps = captureRate;
1005 captureFpsFound = true;
1006 }
1007 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001008 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
1009 }
1010 }
1011
1012 {
1013 config->mISConfig->mSuspended = false;
1014 config->mISConfig->mSuspendAtUs = -1;
1015 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001016 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001017 config->mISConfig->mSuspended = true;
1018 }
1019 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001020 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -07001021 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001022 }
1023
1024 /*
1025 * Handle desired color format.
1026 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001027 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001028 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001029 int32_t format = 0;
1030 // Query vendor format for Flexible YUV
1031 std::vector<std::unique_ptr<C2Param>> heapParams;
1032 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
Wonsik Kim50811882022-04-28 15:57:27 -07001033 int vendorSdkVersion = base::GetIntProperty(
1034 "ro.vendor.build.version.sdk", android_get_device_api_level());
guochuang709b48b2022-10-25 20:40:42 +08001035 if (mClient->query(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001036 {},
1037 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1038 C2_MAY_BLOCK,
1039 &heapParams) == C2_OK
1040 && heapParams.size() == 1u) {
1041 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1042 heapParams[0].get());
1043 } else {
1044 pixelFormatInfo = nullptr;
1045 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001046 // bit depth -> format
1047 std::map<uint32_t, uint32_t> flexPixelFormat;
1048 std::map<uint32_t, uint32_t> flexPlanarPixelFormat;
1049 std::map<uint32_t, uint32_t> flexSemiPlanarPixelFormat;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001050 if (pixelFormatInfo && *pixelFormatInfo) {
1051 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1052 const C2FlexiblePixelFormatDescriptorStruct &desc =
1053 pixelFormatInfo->m.values[i];
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001054 if (desc.subsampling != C2Color::YUV_420
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001055 // TODO(b/180076105): some device report wrong layout
1056 // || desc.layout == C2Color::INTERLEAVED_PACKED
1057 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1058 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1059 continue;
1060 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001061 if (flexPixelFormat.count(desc.bitDepth) == 0) {
1062 flexPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001063 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001064 if (desc.layout == C2Color::PLANAR_PACKED
1065 && flexPlanarPixelFormat.count(desc.bitDepth) == 0) {
1066 flexPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001067 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001068 if (desc.layout == C2Color::SEMIPLANAR_PACKED
1069 && flexSemiPlanarPixelFormat.count(desc.bitDepth) == 0) {
1070 flexSemiPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001071 }
1072 }
1073 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001074 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001075 // Also handle default color format (encoders require color format, so this is only
1076 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001077 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001078 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001079 const char *prefix = "";
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001080 if (flexSemiPlanarPixelFormat.count(8) != 0) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001081 format = COLOR_FormatYUV420SemiPlanar;
1082 prefix = "semi-";
1083 } else {
1084 format = COLOR_FormatYUV420Planar;
1085 }
1086 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1087 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001088 } else {
1089 format = COLOR_FormatSurface;
1090 }
1091 defaultColorFormat = format;
1092 }
1093 } else {
1094 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001095 if (vendorSdkVersion < __ANDROID_API_S__ &&
Taehwan Kim43e715d2022-09-22 12:04:59 +09001096 (format == COLOR_FormatYUV420Planar ||
Wonsik Kim2b8579f2022-05-04 13:30:33 -07001097 format == COLOR_FormatYUV420PackedPlanar ||
1098 format == COLOR_FormatYUV420SemiPlanar ||
1099 format == COLOR_FormatYUV420PackedSemiPlanar)) {
1100 // pre-S framework used to map these color formats into YV12.
1101 // Codecs from older vendor partition may be relying on
1102 // this assumption.
1103 format = HAL_PIXEL_FORMAT_YV12;
1104 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001105 switch (format) {
1106 case COLOR_FormatYUV420Flexible:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001107 format = COLOR_FormatYUV420Planar;
1108 if (flexPixelFormat.count(8) != 0) {
1109 format = flexPixelFormat[8];
1110 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001111 break;
1112 case COLOR_FormatYUV420Planar:
1113 case COLOR_FormatYUV420PackedPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001114 if (flexPlanarPixelFormat.count(8) != 0) {
1115 format = flexPlanarPixelFormat[8];
1116 } else if (flexPixelFormat.count(8) != 0) {
1117 format = flexPixelFormat[8];
1118 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001119 break;
1120 case COLOR_FormatYUV420SemiPlanar:
1121 case COLOR_FormatYUV420PackedSemiPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001122 if (flexSemiPlanarPixelFormat.count(8) != 0) {
1123 format = flexSemiPlanarPixelFormat[8];
1124 } else if (flexPixelFormat.count(8) != 0) {
1125 format = flexPixelFormat[8];
1126 }
1127 break;
1128 case COLOR_FormatYUVP010:
1129 format = COLOR_FormatYUVP010;
1130 if (flexSemiPlanarPixelFormat.count(10) != 0) {
1131 format = flexSemiPlanarPixelFormat[10];
1132 } else if (flexPixelFormat.count(10) != 0) {
1133 format = flexPixelFormat[10];
1134 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001135 break;
1136 default:
1137 // No-op
1138 break;
1139 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001140 }
1141 }
1142
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001143 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001144 msg->setInt32("android._color-format", format);
1145 }
1146 }
1147
Wonsik Kim77e97c72021-01-20 10:33:22 -08001148 /*
1149 * Handle dataspace
1150 */
1151 int32_t usingRecorder;
1152 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1153 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1154 int32_t width, height;
1155 if (msg->findInt32("width", &width)
1156 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001157 ColorAspects aspects;
1158 getColorAspectsFromFormat(msg, aspects);
1159 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001160 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001161 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1162 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001163 }
1164 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1165 ALOGD("setting dataspace to %x", dataSpace);
1166 }
1167
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001168 int32_t subscribeToAllVendorParams;
1169 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1170 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1171 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1172 }
1173 }
1174
Pawin Vongmasa36653902018-11-15 00:10:25 -08001175 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001176 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1177 // the behavior here.
1178 sp<AMessage> sdkParams = msg;
1179 int32_t videoBitrate;
1180 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1181 sdkParams = msg->dup();
1182 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1183 }
ted.sun765db4d2020-06-23 14:03:41 +08001184 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001185 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001186 if (err != OK) {
1187 ALOGW("failed to convert configuration to c2 params");
1188 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001189
1190 int32_t maxBframes = 0;
1191 if ((config->mDomain & Config::IS_ENCODER)
1192 && (config->mDomain & Config::IS_VIDEO)
1193 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1194 && maxBframes > 0) {
1195 std::unique_ptr<C2StreamGopTuning::output> gop =
1196 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1197 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1198 gop->m.values[1] = {
1199 C2Config::picture_type_t(P_FRAME | B_FRAME),
1200 uint32_t(maxBframes)
1201 };
1202 configUpdate.push_back(std::move(gop));
1203 }
1204
Ray Essicka0ae6972021-03-10 19:40:01 -08001205 if ((config->mDomain & Config::IS_ENCODER)
1206 && (config->mDomain & Config::IS_VIDEO)) {
1207 // we may not use all 3 of these entries
1208 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1209 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1210 0u /* stream */);
1211
1212 int ix = 0;
1213
1214 int32_t iMax = INT32_MAX;
1215 int32_t iMin = INT32_MIN;
1216 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1217 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1218 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1219 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1220 }
1221
1222 int32_t pMax = INT32_MAX;
1223 int32_t pMin = INT32_MIN;
1224 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1225 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1226 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1227 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1228 }
1229
1230 int32_t bMax = INT32_MAX;
1231 int32_t bMin = INT32_MIN;
1232 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1233 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1234 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1235 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1236 }
1237
1238 // adjust to reflect actual use.
1239 qp->setFlexCount(ix);
1240
1241 configUpdate.push_back(std::move(qp));
1242 }
1243
Wonsik Kima1335e12021-04-22 16:28:29 -07001244 int32_t background = 0;
1245 if ((config->mDomain & Config::IS_VIDEO)
1246 && msg->findInt32("android._background-mode", &background)
1247 && background) {
1248 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1249 if (config->mISConfig) {
1250 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1251 }
1252 }
1253
Pawin Vongmasa36653902018-11-15 00:10:25 -08001254 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1255 if (err != OK) {
1256 ALOGW("failed to configure c2 params");
1257 return err;
1258 }
1259
1260 std::vector<std::unique_ptr<C2Param>> params;
1261 C2StreamUsageTuning::input usage(0u, 0u);
1262 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001263 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001264
Wonsik Kim3baecda2021-02-07 22:19:56 -08001265 C2Param::Index colorAspectsRequestIndex =
1266 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001267 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001268 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001269 };
Chaejung Lim86c22dc2021-12-23 00:41:05 -08001270 int32_t colorTransferRequest = 0;
1271 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1272 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1273 colorTransferRequest = 0;
1274 }
1275 c2_status_t c2err = C2_OK;
1276 if (colorTransferRequest != 0) {
1277 c2err = comp->query(
1278 { &usage, &maxInputSize, &prepend },
1279 indices,
1280 C2_DONT_BLOCK,
1281 &params);
1282 } else {
1283 c2err = comp->query(
1284 { &usage, &maxInputSize, &prepend },
1285 {},
1286 C2_DONT_BLOCK,
1287 &params);
1288 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001289 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1290 ALOGE("Failed to query component interface: %d", c2err);
1291 return UNKNOWN_ERROR;
1292 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001293 if (usage) {
1294 if (usage.value & C2MemoryUsage::CPU_READ) {
1295 config->mInputFormat->setInt32("using-sw-read-often", true);
1296 }
1297 if (config->mISConfig) {
1298 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1299 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1300 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001301 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001302 }
1303
1304 // NOTE: we don't blindly use client specified input size if specified as clients
1305 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1306 // client specified size is only used to ask for bigger buffers than component suggested
1307 // size.
1308 int32_t clientInputSize = 0;
1309 bool clientSpecifiedInputSize =
1310 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1311 // TEMP: enforce minimum buffer size of 1MB for video decoders
1312 // and 16K / 4K for audio encoders/decoders
1313 if (maxInputSize.value == 0) {
1314 if (config->mDomain & Config::IS_AUDIO) {
1315 maxInputSize.value = encoder ? 16384 : 4096;
1316 } else if (!encoder) {
1317 maxInputSize.value = 1048576u;
1318 }
1319 }
1320
1321 // verify that CSD fits into this size (if defined)
1322 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1323 sp<ABuffer> csd;
1324 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1325 if (csd && csd->size() > maxInputSize.value) {
1326 maxInputSize.value = csd->size();
1327 }
1328 }
1329 }
1330
1331 // TODO: do this based on component requiring linear allocator for input
1332 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1333 if (clientSpecifiedInputSize) {
1334 // Warn that we're overriding client's max input size if necessary.
1335 if ((uint32_t)clientInputSize < maxInputSize.value) {
1336 ALOGD("client requested max input size %d, which is smaller than "
1337 "what component recommended (%u); overriding with component "
1338 "recommendation.", clientInputSize, maxInputSize.value);
1339 ALOGW("This behavior is subject to change. It is recommended that "
1340 "app developers double check whether the requested "
1341 "max input size is in reasonable range.");
1342 } else {
1343 maxInputSize.value = clientInputSize;
1344 }
1345 }
1346 // Pass max input size on input format to the buffer channel (if supplied by the
1347 // component or by a default)
1348 if (maxInputSize.value) {
1349 config->mInputFormat->setInt32(
1350 KEY_MAX_INPUT_SIZE,
1351 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1352 }
1353 }
1354
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001355 int32_t clientPrepend;
1356 if ((config->mDomain & Config::IS_VIDEO)
1357 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001358 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001359 && clientPrepend
1360 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001361 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001362 return BAD_VALUE;
1363 }
1364
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001365 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001366 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1367 // propagate HDR static info to output format for both encoders and decoders
1368 // if component supports this info, we will update from component, but only the raw port,
1369 // so don't propagate if component already filled it in.
1370 sp<ABuffer> hdrInfo;
1371 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1372 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1373 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1374 }
1375
1376 // Set desired color format from configuration parameter
1377 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001378 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1379 format = defaultColorFormat;
1380 }
1381 if (config->mDomain & Config::IS_ENCODER) {
1382 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001383 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1384 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001385 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001386 } else {
1387 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001388 }
1389 }
1390
1391 // propagate encoder delay and padding to output format
1392 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1393 int delay = 0;
1394 if (msg->findInt32("encoder-delay", &delay)) {
1395 config->mOutputFormat->setInt32("encoder-delay", delay);
1396 }
1397 int padding = 0;
1398 if (msg->findInt32("encoder-padding", &padding)) {
1399 config->mOutputFormat->setInt32("encoder-padding", padding);
1400 }
1401 }
1402
Pawin Vongmasa36653902018-11-15 00:10:25 -08001403 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001404 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001405 int32_t mask;
1406 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1407 if (config->mDomain & Config::IS_ENCODER) {
1408 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1409 } else {
1410 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1411 }
1412 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001413
1414 // set PCM encoding
1415 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1416 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1417 if (encoder) {
1418 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1419 } else {
1420 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1421 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001422 }
1423
Wonsik Kim3baecda2021-02-07 22:19:56 -08001424 std::unique_ptr<C2Param> colorTransferRequestParam;
1425 for (std::unique_ptr<C2Param> &param : params) {
1426 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1427 ALOGI("found color transfer request param");
1428 colorTransferRequestParam = std::move(param);
1429 }
1430 }
Wonsik Kim3baecda2021-02-07 22:19:56 -08001431
1432 if (colorTransferRequest != 0) {
1433 if (colorTransferRequestParam && *colorTransferRequestParam) {
1434 C2StreamColorAspectsInfo::output *info =
1435 static_cast<C2StreamColorAspectsInfo::output *>(
1436 colorTransferRequestParam.get());
1437 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1438 colorTransferRequest = 0;
1439 }
1440 } else {
1441 colorTransferRequest = 0;
1442 }
1443 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1444 }
1445
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001446 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1447 // Need to get stride/vstride
1448 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1449 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1450 // TODO: retrieve these values without allocating a buffer.
1451 // Currently allocating a buffer is necessary to retrieve the layout.
1452 int64_t blockUsage =
1453 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1454 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
Taehwan Kim2772e1c2022-03-31 17:15:08 +09001455 width, height, componentColorFormat, blockUsage, {comp->getName()});
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001456 sp<GraphicBlockBuffer> buffer;
1457 if (block) {
1458 buffer = GraphicBlockBuffer::Allocate(
1459 config->mInputFormat,
1460 block,
1461 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1462 } else {
1463 ALOGD("Failed to allocate a graphic block "
1464 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1465 width, height, pixelFormat, (long long)blockUsage);
1466 // This means that byte buffer mode is not supported in this configuration
1467 // anyway. Skip setting stride/vstride to input format.
1468 }
1469 if (buffer) {
1470 sp<ABuffer> imageData = buffer->getImageData();
1471 MediaImage2 *img = nullptr;
1472 if (imageData && imageData->data()
1473 && imageData->size() >= sizeof(MediaImage2)) {
1474 img = (MediaImage2*)imageData->data();
1475 }
1476 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1477 int32_t stride = img->mPlane[0].mRowInc;
1478 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1479 if (img->mNumPlanes > 1 && stride > 0) {
1480 int64_t offsetDelta =
1481 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1482 if (offsetDelta % stride == 0) {
1483 int32_t vstride = int32_t(offsetDelta / stride);
1484 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1485 } else {
1486 ALOGD("Cannot report accurate slice height: "
1487 "offsetDelta = %lld stride = %d",
1488 (long long)offsetDelta, stride);
1489 }
1490 }
1491 }
1492 }
1493 }
1494 }
1495
Wonsik Kimec585c32021-10-01 01:11:00 -07001496 if (config->mTunneled) {
1497 config->mOutputFormat->setInt32("android._tunneled", 1);
1498 }
1499
Yushin Cho91873b52021-12-21 04:08:35 -08001500 // Convert an encoding statistics level to corresponding encoding statistics
1501 // kinds
1502 int32_t encodingStatisticsLevel = VIDEO_ENCODING_STATISTICS_LEVEL_NONE;
1503 if ((config->mDomain & Config::IS_ENCODER)
1504 && (config->mDomain & Config::IS_VIDEO)
1505 && msg->findInt32(KEY_VIDEO_ENCODING_STATISTICS_LEVEL, &encodingStatisticsLevel)) {
1506 // Higher level include all the enc stats belong to lower level.
1507 switch (encodingStatisticsLevel) {
1508 // case VIDEO_ENCODING_STATISTICS_LEVEL_2: // reserved for the future level 2
1509 // with more enc stat kinds
1510 // Future extended encoding statistics for the level 2 should be added here
1511 case VIDEO_ENCODING_STATISTICS_LEVEL_1:
Wonsik Kimeebab652022-06-02 13:01:55 -07001512 config->subscribeToConfigUpdate(
1513 comp,
1514 {
1515 C2AndroidStreamAverageBlockQuantizationInfo::output::PARAM_TYPE,
1516 C2StreamPictureTypeInfo::output::PARAM_TYPE,
1517 });
Yushin Cho91873b52021-12-21 04:08:35 -08001518 break;
1519 case VIDEO_ENCODING_STATISTICS_LEVEL_NONE:
1520 break;
1521 }
1522 }
1523 ALOGD("encoding statistics level = %d", encodingStatisticsLevel);
1524
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001525 ALOGD("setup formats input: %s",
1526 config->mInputFormat->debugString().c_str());
1527 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001528 config->mOutputFormat->debugString().c_str());
1529 return OK;
1530 };
1531 if (tryAndReportOnError(doConfig) != OK) {
1532 return;
1533 }
1534
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001535 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1536 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001537
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001538 config->queryConfiguration(comp);
1539
Songyue Han1e6769b2023-08-30 18:09:27 +00001540 mMetrics = new AMessage;
1541 mChannel->resetBuffersPixelFormat((config->mDomain & Config::IS_ENCODER) ? true : false);
1542
Pawin Vongmasa36653902018-11-15 00:10:25 -08001543 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1544}
1545
1546void CCodec::initiateCreateInputSurface() {
1547 status_t err = [this] {
1548 Mutexed<State>::Locked state(mState);
1549 if (state->get() != ALLOCATED) {
1550 return UNKNOWN_ERROR;
1551 }
1552 // TODO: read it from intf() properly.
1553 if (state->comp->getName().find("encoder") == std::string::npos) {
1554 return INVALID_OPERATION;
1555 }
1556 return OK;
1557 }();
1558 if (err != OK) {
1559 mCallback->onInputSurfaceCreationFailed(err);
1560 return;
1561 }
1562
1563 (new AMessage(kWhatCreateInputSurface, this))->post();
1564}
1565
Lajos Molnar47118272019-01-31 16:28:04 -08001566sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1567 using namespace android::hardware::media::omx::V1_0;
1568 using namespace android::hardware::media::omx::V1_0::utils;
1569 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1570 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1571 android::sp<IOmx> omx = IOmx::getService();
Sungtak Lee47dcb482022-04-15 10:47:08 -07001572 if (omx == nullptr) {
1573 return nullptr;
1574 }
Lajos Molnar47118272019-01-31 16:28:04 -08001575 typedef android::hardware::graphics::bufferqueue::V1_0::
1576 IGraphicBufferProducer HGraphicBufferProducer;
1577 typedef android::hardware::media::omx::V1_0::
1578 IGraphicBufferSource HGraphicBufferSource;
1579 OmxStatus s;
1580 android::sp<HGraphicBufferProducer> gbp;
1581 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001582
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001583 using ::android::hardware::Return;
1584 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001585 [&s, &gbp, &gbs](
1586 OmxStatus status,
1587 const android::sp<HGraphicBufferProducer>& producer,
1588 const android::sp<HGraphicBufferSource>& source) {
1589 s = status;
1590 gbp = producer;
1591 gbs = source;
1592 });
1593 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001594 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001595 }
1596
1597 return nullptr;
1598}
1599
1600sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1601 sp<PersistentSurface> surface(CreateInputSurface());
1602
1603 if (surface == nullptr) {
1604 surface = CreateOmxInputSurface();
1605 }
1606
1607 return surface;
1608}
1609
Pawin Vongmasa36653902018-11-15 00:10:25 -08001610void CCodec::createInputSurface() {
1611 status_t err;
1612 sp<IGraphicBufferProducer> bufferProducer;
1613
Pawin Vongmasa36653902018-11-15 00:10:25 -08001614 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001615 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001616 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001617 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1618 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001619 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001620 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001621 }
1622
Lajos Molnar47118272019-01-31 16:28:04 -08001623 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001624 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1625 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1626 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001627
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001628 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001629 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1630 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001631 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001632 inputSurface));
1633 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001634 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001635 int32_t width = 0;
1636 (void)outputFormat->findInt32("width", &width);
1637 int32_t height = 0;
1638 (void)outputFormat->findInt32("height", &height);
1639 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001640 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001641 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001642 } else {
1643 ALOGE("Corrupted input surface");
1644 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1645 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001646 }
1647
1648 if (err != OK) {
1649 ALOGE("Failed to set up input surface: %d", err);
1650 mCallback->onInputSurfaceCreationFailed(err);
1651 return;
1652 }
1653
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001654 // Formats can change after setupInputSurface
1655 sp<AMessage> inputFormat;
1656 {
1657 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1658 const std::unique_ptr<Config> &config = *configLocked;
1659 inputFormat = config->mInputFormat;
1660 outputFormat = config->mOutputFormat;
1661 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001662 mCallback->onInputSurfaceCreated(
1663 inputFormat,
1664 outputFormat,
1665 new BufferProducerWrapper(bufferProducer));
1666}
1667
1668status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001669 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1670 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001671 config->mUsingSurface = true;
1672
1673 // we are now using surface - apply default color aspects to input format - as well as
1674 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001675 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001676
1677 // configure dataspace
1678 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
Wonsik Kim66b19552021-08-02 16:07:49 -07001679
1680 // The output format contains app-configured color aspects, and the input format
1681 // has the default color aspects. Use the default for the unspecified params.
1682 ColorAspects inputColorAspects, colorAspects;
1683 getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
1684 getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
1685 if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
1686 colorAspects.mRange = inputColorAspects.mRange;
1687 }
1688 if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
1689 colorAspects.mPrimaries = inputColorAspects.mPrimaries;
1690 }
1691 if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
1692 colorAspects.mTransfer = inputColorAspects.mTransfer;
1693 }
1694 if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
1695 colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
1696 }
1697 android_dataspace dataSpace = getDataSpaceForColorAspects(
1698 colorAspects, /* mayExtend = */ false);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001699 surface->setDataSpace(dataSpace);
Wonsik Kim66b19552021-08-02 16:07:49 -07001700 setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
1701 config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
1702
1703 ALOGD("input format %s to %s",
1704 inputFormatChanged ? "changed" : "unchanged",
1705 config->mInputFormat->debugString().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001706
1707 status_t err = mChannel->setInputSurface(surface);
1708 if (err != OK) {
1709 // undo input format update
1710 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001711 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001712 return err;
1713 }
1714 config->mInputSurface = surface;
1715
1716 if (config->mISConfig) {
1717 surface->configure(*config->mISConfig);
1718 } else {
1719 ALOGD("ISConfig: no configuration");
1720 }
1721
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001722 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001723}
1724
1725void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1726 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1727 msg->setObject("surface", surface);
1728 msg->post();
1729}
1730
1731void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001732 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001733 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001734 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001735 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1736 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001737 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001738 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001739 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001740 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1741 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1742 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1743 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001744 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1745 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1746 if (err != OK) {
1747 ALOGE("Failed to set up input surface: %d", err);
1748 mCallback->onInputSurfaceDeclined(err);
1749 return;
1750 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001751 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001752 int32_t width = 0;
1753 (void)outputFormat->findInt32("width", &width);
1754 int32_t height = 0;
1755 (void)outputFormat->findInt32("height", &height);
1756 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001757 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001758 if (err != OK) {
1759 ALOGE("Failed to set up input surface: %d", err);
1760 mCallback->onInputSurfaceDeclined(err);
1761 return;
1762 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001763 } else {
1764 ALOGE("Failed to set input surface: Corrupted surface.");
1765 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1766 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001767 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001768 // Formats can change after setupInputSurface
1769 sp<AMessage> inputFormat;
1770 {
1771 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1772 const std::unique_ptr<Config> &config = *configLocked;
1773 inputFormat = config->mInputFormat;
1774 outputFormat = config->mOutputFormat;
1775 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001776 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1777}
1778
1779void CCodec::initiateStart() {
1780 auto setStarting = [this] {
1781 Mutexed<State>::Locked state(mState);
1782 if (state->get() != ALLOCATED) {
1783 return UNKNOWN_ERROR;
1784 }
1785 state->set(STARTING);
1786 return OK;
1787 };
1788 if (tryAndReportOnError(setStarting) != OK) {
1789 return;
1790 }
1791
1792 (new AMessage(kWhatStart, this))->post();
1793}
1794
1795void CCodec::start() {
1796 std::shared_ptr<Codec2Client::Component> comp;
1797 auto checkStarting = [this, &comp] {
1798 Mutexed<State>::Locked state(mState);
1799 if (state->get() != STARTING) {
1800 return UNKNOWN_ERROR;
1801 }
1802 comp = state->comp;
1803 return OK;
1804 };
1805 if (tryAndReportOnError(checkStarting) != OK) {
1806 return;
1807 }
1808
1809 c2_status_t err = comp->start();
1810 if (err != C2_OK) {
1811 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1812 ACTION_CODE_FATAL);
1813 return;
1814 }
Wonsik Kimd55ed3b2023-06-22 14:42:17 -07001815
1816 // clear the deadline after the component starts
1817 setDeadline(TimePoint::max(), 0ms, "none");
1818
Pawin Vongmasa36653902018-11-15 00:10:25 -08001819 sp<AMessage> inputFormat;
1820 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001821 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001822 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001823 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001824 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1825 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001826 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001827 // start triggers format dup
1828 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001829 if (config->mInputSurface) {
1830 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001831 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001832 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001833 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001834 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001835 if (err2 != OK) {
1836 mCallback->onError(err2, ACTION_CODE_FATAL);
1837 return;
1838 }
Arun Johnson106fe7a2023-04-26 17:49:43 +00001839
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001840 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001841 if (err2 != OK) {
1842 mCallback->onError(err2, ACTION_CODE_FATAL);
1843 return;
1844 }
1845
1846 auto setRunning = [this] {
1847 Mutexed<State>::Locked state(mState);
1848 if (state->get() != STARTING) {
1849 return UNKNOWN_ERROR;
1850 }
1851 state->set(RUNNING);
1852 return OK;
1853 };
1854 if (tryAndReportOnError(setRunning) != OK) {
1855 return;
1856 }
Arun Johnson5997bb02022-04-01 19:35:44 +00001857
Wonsik Kim34b28b42022-05-20 15:49:32 -07001858 // preparation of input buffers may not succeed due to the lack of
1859 // memory; returning correct error code (NO_MEMORY) as an error allows
1860 // MediaCodec to try reclaim and restart codec gracefully.
1861 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
1862 err2 = mChannel->prepareInitialInputBuffers(&clientInputBuffers);
1863 if (err2 != OK) {
1864 ALOGE("Initial preparation for Input Buffers failed");
1865 mCallback->onError(err2, ACTION_CODE_FATAL);
1866 return;
1867 }
1868
Pawin Vongmasa36653902018-11-15 00:10:25 -08001869 mCallback->onStartCompleted();
1870
Wonsik Kim34b28b42022-05-20 15:49:32 -07001871 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001872}
1873
1874void CCodec::initiateShutdown(bool keepComponentAllocated) {
1875 if (keepComponentAllocated) {
1876 initiateStop();
1877 } else {
1878 initiateRelease();
1879 }
1880}
1881
1882void CCodec::initiateStop() {
1883 {
1884 Mutexed<State>::Locked state(mState);
1885 if (state->get() == ALLOCATED
1886 || state->get() == RELEASED
1887 || state->get() == STOPPING
1888 || state->get() == RELEASING) {
1889 // We're already stopped, released, or doing it right now.
1890 state.unlock();
1891 mCallback->onStopCompleted();
1892 state.lock();
1893 return;
1894 }
1895 state->set(STOPPING);
1896 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001897 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00001898 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
1899 sp<AMessage> stopMessage(new AMessage(kWhatStop, this));
1900 stopMessage->setInt32("pushBlankBuffer", pushBlankBuffer);
1901 stopMessage->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001902}
1903
Sungtak Lee99144332023-01-26 11:03:14 +00001904void CCodec::stop(bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001905 std::shared_ptr<Codec2Client::Component> comp;
1906 {
1907 Mutexed<State>::Locked state(mState);
1908 if (state->get() == RELEASING) {
1909 state.unlock();
1910 // We're already stopped or release is in progress.
1911 mCallback->onStopCompleted();
1912 state.lock();
1913 return;
1914 } else if (state->get() != STOPPING) {
1915 state.unlock();
1916 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1917 state.lock();
1918 return;
1919 }
1920 comp = state->comp;
1921 }
1922 status_t err = comp->stop();
Sungtak Lee99144332023-01-26 11:03:14 +00001923 mChannel->stopUseOutputSurface(pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001924 if (err != C2_OK) {
1925 // TODO: convert err into status_t
1926 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1927 }
1928
1929 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001930 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1931 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001932 if (config->mInputSurface) {
1933 config->mInputSurface->disconnect();
1934 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001935 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001936 }
1937 }
1938 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001939 Mutexed<State>::Locked state(mState);
1940 if (state->get() == STOPPING) {
1941 state->set(ALLOCATED);
1942 }
1943 }
1944 mCallback->onStopCompleted();
1945}
1946
1947void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001948 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001949 {
1950 Mutexed<State>::Locked state(mState);
1951 if (state->get() == RELEASED || state->get() == RELEASING) {
1952 // We're already released or doing it right now.
1953 if (sendCallback) {
1954 state.unlock();
1955 mCallback->onReleaseCompleted();
1956 state.lock();
1957 }
1958 return;
1959 }
1960 if (state->get() == ALLOCATING) {
1961 state->set(RELEASING);
1962 // With the altered state allocate() would fail and clean up.
1963 if (sendCallback) {
1964 state.unlock();
1965 mCallback->onReleaseCompleted();
1966 state.lock();
1967 }
1968 return;
1969 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001970 if (state->get() == STARTING
1971 || state->get() == RUNNING
1972 || state->get() == STOPPING) {
1973 // Input surface may have been started, so clean up is needed.
1974 clearInputSurfaceIfNeeded = true;
1975 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001976 state->set(RELEASING);
1977 }
1978
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001979 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001980 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1981 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001982 if (config->mInputSurface) {
1983 config->mInputSurface->disconnect();
1984 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001985 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001986 }
1987 }
1988
Wonsik Kim936a89c2020-05-08 16:07:50 -07001989 mChannel->reset();
Sungtak Lee99144332023-01-26 11:03:14 +00001990 bool pushBlankBuffer = mConfig.lock().get()->mPushBlankBuffersOnStop;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001991 // thiz holds strong ref to this while the thread is running.
1992 sp<CCodec> thiz(this);
Sungtak Lee99144332023-01-26 11:03:14 +00001993 std::thread([thiz, sendCallback, pushBlankBuffer]
1994 { thiz->release(sendCallback, pushBlankBuffer); }).detach();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001995}
1996
Sungtak Lee99144332023-01-26 11:03:14 +00001997void CCodec::release(bool sendCallback, bool pushBlankBuffer) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001998 std::shared_ptr<Codec2Client::Component> comp;
1999 {
2000 Mutexed<State>::Locked state(mState);
2001 if (state->get() == RELEASED) {
2002 if (sendCallback) {
2003 state.unlock();
2004 mCallback->onReleaseCompleted();
2005 state.lock();
2006 }
2007 return;
2008 }
2009 comp = state->comp;
2010 }
2011 comp->release();
Sungtak Lee99144332023-01-26 11:03:14 +00002012 mChannel->stopUseOutputSurface(pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002013
2014 {
2015 Mutexed<State>::Locked state(mState);
2016 state->set(RELEASED);
2017 state->comp.reset();
2018 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002019 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002020 if (sendCallback) {
2021 mCallback->onReleaseCompleted();
2022 }
2023}
2024
2025status_t CCodec::setSurface(const sp<Surface> &surface) {
Sungtak Lee99144332023-01-26 11:03:14 +00002026 bool pushBlankBuffer = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002027 {
2028 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2029 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002030 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
2031 status_t err = OK;
2032
Wonsik Kim75e22f42021-04-14 23:34:51 -07002033 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002034 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07002035 nativeWindow.get(),
2036 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
2037 if (err != OK) {
2038 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
2039 nativeWindow.get(), config->mSidebandHandle->handle(), err);
2040 return err;
2041 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08002042 } else {
2043 // Explicitly reset the sideband handle of the window for
2044 // non-tunneled video in case the window was previously used
2045 // for a tunneled video playback.
2046 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
2047 if (err != OK) {
2048 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
2049 return err;
2050 }
ted.sun765db4d2020-06-23 14:03:41 +08002051 }
Sungtak Lee99144332023-01-26 11:03:14 +00002052 pushBlankBuffer = config->mPushBlankBuffersOnStop;
ted.sun765db4d2020-06-23 14:03:41 +08002053 }
Sungtak Lee99144332023-01-26 11:03:14 +00002054 return mChannel->setSurface(surface, pushBlankBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002055}
2056
2057void CCodec::signalFlush() {
2058 status_t err = [this] {
2059 Mutexed<State>::Locked state(mState);
2060 if (state->get() == FLUSHED) {
2061 return ALREADY_EXISTS;
2062 }
2063 if (state->get() != RUNNING) {
2064 return UNKNOWN_ERROR;
2065 }
2066 state->set(FLUSHING);
2067 return OK;
2068 }();
2069 switch (err) {
2070 case ALREADY_EXISTS:
2071 mCallback->onFlushCompleted();
2072 return;
2073 case OK:
2074 break;
2075 default:
2076 mCallback->onError(err, ACTION_CODE_FATAL);
2077 return;
2078 }
2079
2080 mChannel->stop();
2081 (new AMessage(kWhatFlush, this))->post();
2082}
2083
2084void CCodec::flush() {
2085 std::shared_ptr<Codec2Client::Component> comp;
2086 auto checkFlushing = [this, &comp] {
2087 Mutexed<State>::Locked state(mState);
2088 if (state->get() != FLUSHING) {
2089 return UNKNOWN_ERROR;
2090 }
2091 comp = state->comp;
2092 return OK;
2093 };
2094 if (tryAndReportOnError(checkFlushing) != OK) {
2095 return;
2096 }
2097
2098 std::list<std::unique_ptr<C2Work>> flushedWork;
2099 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2100 {
2101 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2102 flushedWork.splice(flushedWork.end(), *queue);
2103 }
2104 if (err != C2_OK) {
2105 // TODO: convert err into status_t
2106 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2107 }
2108
2109 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002110
2111 {
2112 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002113 if (state->get() == FLUSHING) {
2114 state->set(FLUSHED);
2115 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002116 }
2117 mCallback->onFlushCompleted();
2118}
2119
2120void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002121 std::shared_ptr<Codec2Client::Component> comp;
2122 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002123 Mutexed<State>::Locked state(mState);
2124 if (state->get() != FLUSHED) {
2125 return UNKNOWN_ERROR;
2126 }
2127 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002128 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002129 return OK;
2130 };
2131 if (tryAndReportOnError(setResuming) != OK) {
2132 return;
2133 }
2134
Wonsik Kime75a5da2020-02-14 17:29:03 -08002135 {
2136 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2137 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002138 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002139 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002140 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002141 }
2142
Arun Johnson106fe7a2023-04-26 17:49:43 +00002143 std::map<size_t, sp<MediaCodecBuffer>> clientInputBuffers;
Arun Johnson326166e2023-07-28 19:11:52 +00002144 status_t err = mChannel->prepareInitialInputBuffers(&clientInputBuffers, true);
Arun Johnson106fe7a2023-04-26 17:49:43 +00002145 if (err != OK) {
2146 if (err == NO_MEMORY) {
2147 // NO_MEMORY happens here when all the buffers are still
2148 // with the codec. That is not an error as it is momentarily
2149 // and the buffers are send to the client as soon as the codec
2150 // releases them
2151 ALOGI("Resuming with all input buffers still with codec");
2152 } else {
2153 ALOGE("Resume request for Input Buffers failed");
2154 mCallback->onError(err, ACTION_CODE_FATAL);
2155 return;
2156 }
2157 }
2158
2159 // channel start should be called after prepareInitialBuffers
2160 // Calling before can cause a failure during prepare when
2161 // buffers are sent to the client before preparation from onWorkDone
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002162 (void)mChannel->start(nullptr, nullptr, [&]{
2163 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2164 const std::unique_ptr<Config> &config = *configLocked;
2165 return config->mBuffersBoundToCodec;
2166 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002167 {
2168 Mutexed<State>::Locked state(mState);
2169 if (state->get() != RESUMING) {
2170 state.unlock();
2171 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2172 state.lock();
2173 return;
2174 }
2175 state->set(RUNNING);
2176 }
2177
Wonsik Kim34b28b42022-05-20 15:49:32 -07002178 mChannel->requestInitialInputBuffers(std::move(clientInputBuffers));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002179}
2180
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002181void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002182 std::shared_ptr<Codec2Client::Component> comp;
2183 auto checkState = [this, &comp] {
2184 Mutexed<State>::Locked state(mState);
2185 if (state->get() == RELEASED) {
2186 return INVALID_OPERATION;
2187 }
2188 comp = state->comp;
2189 return OK;
2190 };
2191 if (tryAndReportOnError(checkState) != OK) {
2192 return;
2193 }
2194
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002195 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2196 // the behavior here.
2197 sp<AMessage> params = msg;
2198 int32_t bitrate;
2199 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2200 params = msg->dup();
2201 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2202 }
2203
Houxiang Dai5a97b472021-03-22 17:56:04 +08002204 int32_t syncId = 0;
2205 if (params->findInt32("audio-hw-sync", &syncId)
2206 || params->findInt32("hw-av-sync-id", &syncId)) {
2207 configureTunneledVideoPlayback(comp, nullptr, params);
2208 }
2209
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002210 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2211 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002212
2213 /**
2214 * Handle input surface parameters
2215 */
2216 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002217 && (config->mDomain & Config::IS_ENCODER)
2218 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002219 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002220
2221 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2222 config->mISConfig->mStopped = false;
2223 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2224 config->mISConfig->mStopped = true;
2225 }
2226
2227 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002228 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002229 config->mISConfig->mSuspended = value;
2230 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002231 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002232 }
2233
2234 (void)config->mInputSurface->configure(*config->mISConfig);
2235 if (config->mISConfig->mStopped) {
2236 config->mInputFormat->setInt64(
2237 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2238 }
2239 }
2240
2241 std::vector<std::unique_ptr<C2Param>> configUpdate;
2242 (void)config->getConfigUpdateFromSdkParams(
2243 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2244 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2245 // Parameter synchronization is not defined when using input surface. For now, route
2246 // these directly to the component.
2247 if (config->mInputSurface == nullptr
2248 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2249 || comp->getName().find("c2.android.") == 0)) {
2250 mChannel->setParameters(configUpdate);
2251 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002252 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002253 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002254 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002255 }
2256}
2257
2258void CCodec::signalEndOfInputStream() {
2259 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2260}
2261
2262void CCodec::signalRequestIDRFrame() {
2263 std::shared_ptr<Codec2Client::Component> comp;
2264 {
2265 Mutexed<State>::Locked state(mState);
2266 if (state->get() == RELEASED) {
2267 ALOGD("no IDR request sent since component is released");
2268 return;
2269 }
2270 comp = state->comp;
2271 }
2272 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002273 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2274 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002275 std::vector<std::unique_ptr<C2Param>> params;
2276 params.push_back(
2277 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2278 config->setParameters(comp, params, C2_MAY_BLOCK);
2279}
2280
Wonsik Kim874ad382021-03-12 09:59:36 -08002281status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2282 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2283 const std::unique_ptr<Config> &config = *configLocked;
2284 return config->querySupportedParameters(names);
2285}
2286
2287status_t CCodec::describeParameter(
2288 const std::string &name, CodecParameterDescriptor *desc) {
2289 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2290 const std::unique_ptr<Config> &config = *configLocked;
2291 return config->describe(name, desc);
2292}
2293
2294status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2295 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2296 if (!comp) {
2297 return INVALID_OPERATION;
2298 }
2299 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2300 const std::unique_ptr<Config> &config = *configLocked;
2301 return config->subscribeToVendorConfigUpdate(comp, names);
2302}
2303
2304status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2305 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2306 if (!comp) {
2307 return INVALID_OPERATION;
2308 }
2309 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2310 const std::unique_ptr<Config> &config = *configLocked;
2311 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2312}
2313
Wonsik Kimab34ed62019-01-31 15:28:46 -08002314void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002315 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002316 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2317 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002318 }
2319 (new AMessage(kWhatWorkDone, this))->post();
2320}
2321
Wonsik Kimab34ed62019-01-31 15:28:46 -08002322void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2323 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002324 if (arrayIndex == 0) {
2325 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002326 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2327 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002328 if (config->mInputSurface) {
2329 config->mInputSurface->onInputBufferDone(frameIndex);
2330 }
2331 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002332}
2333
2334void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2335 TimePoint now = std::chrono::steady_clock::now();
2336 CCodecWatchdog::getInstance()->watch(this);
2337 switch (msg->what()) {
2338 case kWhatAllocate: {
2339 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002340 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002341 sp<RefBase> obj;
2342 CHECK(msg->findObject("codecInfo", &obj));
2343 allocate((MediaCodecInfo *)obj.get());
2344 break;
2345 }
2346 case kWhatConfigure: {
2347 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002348 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002349 sp<AMessage> format;
2350 CHECK(msg->findMessage("format", &format));
2351 configure(format);
2352 break;
2353 }
2354 case kWhatStart: {
2355 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002356 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002357 start();
2358 break;
2359 }
2360 case kWhatStop: {
2361 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002362 setDeadline(now, 1500ms, "stop");
Sungtak Lee99144332023-01-26 11:03:14 +00002363 int32_t pushBlankBuffer;
2364 if (!msg->findInt32("pushBlankBuffer", &pushBlankBuffer)) {
2365 pushBlankBuffer = 0;
2366 }
2367 stop(static_cast<bool>(pushBlankBuffer));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002368 break;
2369 }
2370 case kWhatFlush: {
2371 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002372 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002373 flush();
2374 break;
2375 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002376 case kWhatRelease: {
2377 mChannel->release();
2378 mClient.reset();
2379 mClientListener.reset();
2380 break;
2381 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002382 case kWhatCreateInputSurface: {
2383 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002384 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002385 createInputSurface();
2386 break;
2387 }
2388 case kWhatSetInputSurface: {
2389 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002390 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002391 sp<RefBase> obj;
2392 CHECK(msg->findObject("surface", &obj));
2393 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2394 setInputSurface(surface);
2395 break;
2396 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002397 case kWhatWorkDone: {
2398 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002399 bool shouldPost = false;
2400 {
2401 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2402 if (queue->empty()) {
2403 break;
2404 }
2405 work.swap(queue->front());
2406 queue->pop_front();
2407 shouldPost = !queue->empty();
2408 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002409 if (shouldPost) {
2410 (new AMessage(kWhatWorkDone, this))->post();
2411 }
2412
Pawin Vongmasa36653902018-11-15 00:10:25 -08002413 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002414 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002415 sp<AMessage> outputFormat = nullptr;
2416 {
2417 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2418 const std::unique_ptr<Config> &config = *configLocked;
2419 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2420 config->watch<C2StreamInitDataInfo::output>();
2421 if (!work->worklets.empty()
2422 && (work->worklets.front()->output.flags
2423 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002424
Wonsik Kim75e22f42021-04-14 23:34:51 -07002425 // copy buffer info to config
2426 std::vector<std::unique_ptr<C2Param>> updates;
2427 for (const std::unique_ptr<C2Param> &param
2428 : work->worklets.front()->output.configUpdate) {
2429 updates.push_back(C2Param::Copy(*param));
2430 }
2431 unsigned stream = 0;
2432 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2433 work->worklets.front()->output.buffers;
2434 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2435 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2436 // move all info into output-stream #0 domain
2437 updates.emplace_back(
2438 C2Param::CopyAsStream(*info, true /* output */, stream));
2439 }
2440
2441 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2442 // for now only do the first block
2443 if (!blocks.empty()) {
2444 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2445 // block.crop().left, block.crop().top,
2446 // block.crop().width, block.crop().height,
2447 // block.width(), block.height());
2448 const C2ConstGraphicBlock &block = blocks[0];
2449 updates.emplace_back(new C2StreamCropRectInfo::output(
2450 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002451 }
2452 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002453 }
George Burgess IVc813a592020-02-22 22:54:44 -08002454
Wonsik Kim75e22f42021-04-14 23:34:51 -07002455 sp<AMessage> oldFormat = config->mOutputFormat;
2456 config->updateConfiguration(updates, config->mOutputDomain);
2457 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002458
Wonsik Kim75e22f42021-04-14 23:34:51 -07002459 // copy standard infos to graphic buffers if not already present (otherwise, we
2460 // may overwrite the actual intermediate value with a final value)
2461 stream = 0;
2462 const static C2Param::Index stdGfxInfos[] = {
2463 C2StreamRotationInfo::output::PARAM_TYPE,
2464 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2465 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2466 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Taehwan Kim2d222b82022-05-12 14:19:26 +09002467 C2StreamHdr10PlusInfo::output::PARAM_TYPE, // will be deprecated
2468 C2StreamHdrDynamicMetadataInfo::output::PARAM_TYPE,
Wonsik Kim75e22f42021-04-14 23:34:51 -07002469 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2470 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2471 };
2472 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2473 if (buf->data().graphicBlocks().size()) {
2474 for (C2Param::Index ix : stdGfxInfos) {
2475 if (!buf->hasInfo(ix)) {
2476 const C2Param *param =
2477 config->getConfigParameterValue(ix.withStream(stream));
2478 if (param) {
2479 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2480 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2481 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002482 }
2483 }
2484 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002485 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002486 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002487 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002488 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302489 if (work->worklets.empty()
2490 || !work->worklets.back()
2491 || (work->worklets.back()->output.flags
2492 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2493 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2494 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002495 }
2496 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002497 initData = initDataWatcher.update();
2498 AmendOutputFormatWithCodecSpecificData(
2499 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2500 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002501 }
2502 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002503 }
2504 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002505 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Songyue Han1e6769b2023-08-30 18:09:27 +00002506 // log metrics to MediaCodec
2507 if (mMetrics->countEntries() == 0) {
2508 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2509 const std::unique_ptr<Config> &config = *configLocked;
2510 uint32_t pf = PIXEL_FORMAT_UNKNOWN;
2511 if (!config->mInputSurface) {
2512 pf = mChannel->getBuffersPixelFormat(config->mDomain & Config::IS_ENCODER);
2513 }
2514 if (pf != PIXEL_FORMAT_UNKNOWN) {
2515 mMetrics->setInt64(kCodecPixelFormat, pf);
2516 mCallback->onMetricsUpdated(mMetrics);
2517 }
2518 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002519 break;
2520 }
2521 case kWhatWatch: {
2522 // watch message already posted; no-op.
2523 break;
2524 }
2525 default: {
2526 ALOGE("unrecognized message");
2527 break;
2528 }
2529 }
2530 setDeadline(TimePoint::max(), 0ms, "none");
2531}
2532
2533void CCodec::setDeadline(
2534 const TimePoint &now,
2535 const std::chrono::milliseconds &timeout,
2536 const char *name) {
2537 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2538 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2539 deadline->set(now + (timeout * mult), name);
2540}
2541
ted.sun765db4d2020-06-23 14:03:41 +08002542status_t CCodec::configureTunneledVideoPlayback(
2543 std::shared_ptr<Codec2Client::Component> comp,
2544 sp<NativeHandle> *sidebandHandle,
2545 const sp<AMessage> &msg) {
2546 std::vector<std::unique_ptr<C2SettingResult>> failures;
2547
2548 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2549 C2PortTunneledModeTuning::output::AllocUnique(
2550 1,
2551 C2PortTunneledModeTuning::Struct::SIDEBAND,
2552 C2PortTunneledModeTuning::Struct::REALTIME,
2553 0);
2554 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2555 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2556 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2557 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2558 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2559 } else {
2560 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2561 tunneledPlayback->setFlexCount(0);
2562 }
2563 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2564 if (c2err != C2_OK) {
2565 return UNKNOWN_ERROR;
2566 }
2567
Houxiang Dai5a97b472021-03-22 17:56:04 +08002568 if (sidebandHandle == nullptr) {
2569 return OK;
2570 }
2571
ted.sun765db4d2020-06-23 14:03:41 +08002572 std::vector<std::unique_ptr<C2Param>> params;
2573 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2574 if (c2err == C2_OK && params.size() == 1u) {
2575 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2576 C2PortTunnelHandleTuning::output::From(params[0].get());
2577 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2578 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2579 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2580 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2581 memcpy(handle->data, videoTunnelSideband->m.values,
2582 sizeof(int32_t) * videoTunnelSideband->flexCount());
2583 return OK;
2584 } else {
2585 return NO_MEMORY;
2586 }
2587 }
2588 return UNKNOWN_ERROR;
2589}
2590
Pawin Vongmasa36653902018-11-15 00:10:25 -08002591void CCodec::initiateReleaseIfStuck() {
Shrikara B3b87a532022-08-26 14:18:14 +05302592 std::string name;
2593 bool pendingDeadline = false;
2594 {
2595 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2596 if (deadline->get() < std::chrono::steady_clock::now()) {
2597 name = deadline->getName();
2598 }
2599 if (deadline->get() != TimePoint::max()) {
2600 pendingDeadline = true;
2601 }
2602 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002603 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002604 // We're not stuck.
2605 if (pendingDeadline) {
2606 // If we are not stuck yet but still has deadline coming up,
2607 // post watch message to check back later.
2608 (new AMessage(kWhatWatch, this))->post();
2609 }
2610 return;
2611 }
2612
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002613 C2String compName;
2614 {
2615 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002616 if (!state->comp) {
2617 ALOGD("previous call to %s exceeded timeout "
2618 "and the component is already released", name.c_str());
2619 return;
2620 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002621 compName = state->comp->getName();
2622 }
2623 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2624
Pawin Vongmasa36653902018-11-15 00:10:25 -08002625 initiateRelease(false);
2626 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2627}
2628
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002629// static
2630PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002631 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002632 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002633 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002634 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2635 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002636 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002637 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2638 sp<IGraphicBufferProducer> gbp;
2639 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2640 status_t err = gbs->initCheck();
2641 if (err != OK) {
2642 ALOGE("Failed to create persistent input surface: error %d", err);
2643 return nullptr;
2644 }
2645 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002646 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002647 } else {
2648 return nullptr;
2649 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002650 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002651 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002652 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002653 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002654 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002655}
2656
Wonsik Kimffb889a2020-05-28 11:32:25 -07002657class IntfCache {
2658public:
2659 IntfCache() = default;
2660
2661 status_t init(const std::string &name) {
2662 std::shared_ptr<Codec2Client::Interface> intf{
2663 Codec2Client::CreateInterfaceByName(name.c_str())};
2664 if (!intf) {
2665 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2666 mInitStatus = NO_INIT;
2667 return NO_INIT;
2668 }
2669 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2670 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2671 C2ParamField{&sUsage, &sUsage.value}));
2672 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2673 if (err != C2_OK) {
2674 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2675 name.c_str(), err);
2676 mFields[0].status = err;
2677 }
2678 std::vector<std::unique_ptr<C2Param>> params;
2679 err = intf->query(
2680 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09002681 {
2682 C2StreamBufferTypeSetting::input::PARAM_TYPE,
2683 C2PortAllocatorsTuning::input::PARAM_TYPE
2684 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07002685 C2_MAY_BLOCK,
2686 &params);
2687 if (err != C2_OK && err != C2_BAD_INDEX) {
2688 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2689 name.c_str(), err);
2690 }
2691 while (!params.empty()) {
2692 C2Param *param = params.back().release();
2693 params.pop_back();
2694 if (!param) {
2695 continue;
2696 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002697 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
2698 mInputStreamFormat.reset(
2699 C2StreamBufferTypeSetting::input::From(param));
2700 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002701 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002702 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002703 }
2704 }
2705 mInitStatus = OK;
2706 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002707 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002708
2709 status_t initCheck() const { return mInitStatus; }
2710
2711 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2712 CHECK_EQ(1u, mFields.size());
2713 return mFields[0];
2714 }
2715
2716 const C2ApiFeaturesSetting &getApiFeatures() const {
2717 return mApiFeatures;
2718 }
2719
Taehwan Kim900b49c2021-12-13 11:16:22 +09002720 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
2721 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
2722 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
2723 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
2724 param->invalidate();
2725 return param;
2726 }();
2727 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
2728 }
2729
Wonsik Kimffb889a2020-05-28 11:32:25 -07002730 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2731 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2732 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2733 C2PortAllocatorsTuning::input::AllocUnique(0);
2734 param->invalidate();
2735 return param;
2736 }();
2737 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2738 }
2739
2740private:
2741 status_t mInitStatus{NO_INIT};
2742
2743 std::vector<C2FieldSupportedValuesQuery> mFields;
2744 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09002745 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002746 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2747};
2748
2749static const IntfCache &GetIntfCache(const std::string &name) {
2750 static IntfCache sNullIntfCache;
2751 static std::mutex sMutex;
2752 static std::map<std::string, IntfCache> sCache;
2753 std::unique_lock<std::mutex> lock{sMutex};
2754 auto it = sCache.find(name);
2755 if (it == sCache.end()) {
2756 lock.unlock();
2757 IntfCache intfCache;
2758 status_t err = intfCache.init(name);
2759 if (err != OK) {
2760 return sNullIntfCache;
2761 }
2762 lock.lock();
2763 it = sCache.insert({name, std::move(intfCache)}).first;
2764 }
2765 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002766}
2767
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002768static status_t GetCommonAllocatorIds(
2769 const std::vector<std::string> &names,
2770 C2Allocator::type_t type,
2771 std::set<C2Allocator::id_t> *ids) {
2772 int poolMask = GetCodec2PoolMask();
2773 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2774 C2Allocator::id_t defaultAllocatorId =
2775 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2776
2777 ids->clear();
2778 if (names.empty()) {
2779 return OK;
2780 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002781 bool firstIteration = true;
2782 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002783 const IntfCache &intfCache = GetIntfCache(name);
2784 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002785 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002786 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002787 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
2788 if (streamFormat) {
2789 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
2790 if (streamFormat.value == C2BufferData::GRAPHIC
2791 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
2792 allocatorType = C2Allocator::GRAPHIC;
2793 }
2794
2795 if (type != allocatorType) {
2796 // requested type is not supported at input allocators
2797 ids->clear();
2798 ids->insert(defaultAllocatorId);
2799 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
2800 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
2801 break;
2802 }
2803 }
2804
Wonsik Kimffb889a2020-05-28 11:32:25 -07002805 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002806 if (firstIteration) {
2807 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002808 if (allocators && allocators.flexCount() > 0) {
2809 ids->insert(allocators.m.values,
2810 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002811 }
2812 if (ids->empty()) {
2813 // The component does not advertise allocators. Use default.
2814 ids->insert(defaultAllocatorId);
2815 }
2816 continue;
2817 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002818 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002819 if (allocators && allocators.flexCount() > 0) {
2820 filtered = true;
2821 for (auto it = ids->begin(); it != ids->end(); ) {
2822 bool found = false;
2823 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2824 if (allocators.m.values[j] == *it) {
2825 found = true;
2826 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002827 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002828 }
2829 if (found) {
2830 ++it;
2831 } else {
2832 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002833 }
2834 }
2835 }
2836 if (!filtered) {
2837 // The component does not advertise supported allocators. Use default.
2838 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2839 if (ids->size() != (containsDefault ? 1 : 0)) {
2840 ids->clear();
2841 if (containsDefault) {
2842 ids->insert(defaultAllocatorId);
2843 }
2844 }
2845 }
2846 }
2847 // Finally, filter with pool masks
2848 for (auto it = ids->begin(); it != ids->end(); ) {
2849 if ((poolMask >> *it) & 1) {
2850 ++it;
2851 } else {
2852 it = ids->erase(it);
2853 }
2854 }
2855 return OK;
2856}
2857
2858static status_t CalculateMinMaxUsage(
2859 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2860 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2861 *minUsage = 0;
2862 *maxUsage = ~0ull;
2863 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002864 const IntfCache &intfCache = GetIntfCache(name);
2865 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002866 continue;
2867 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002868 const C2FieldSupportedValuesQuery &usageSupportedValues =
2869 intfCache.getUsageSupportedValues();
2870 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002871 continue;
2872 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002873 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002874 if (supported.type != C2FieldSupportedValues::FLAGS) {
2875 continue;
2876 }
2877 if (supported.values.empty()) {
2878 *maxUsage = 0;
2879 continue;
2880 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08002881 if (supported.values.size() > 1) {
2882 *minUsage |= supported.values[1].u64;
2883 } else {
2884 *minUsage |= supported.values[0].u64;
2885 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002886 int64_t currentMaxUsage = 0;
2887 for (const C2Value::Primitive &flags : supported.values) {
2888 currentMaxUsage |= flags.u64;
2889 }
2890 *maxUsage &= currentMaxUsage;
2891 }
2892 return OK;
2893}
2894
2895// static
2896status_t CCodec::CanFetchLinearBlock(
2897 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002898 for (const std::string &name : names) {
2899 const IntfCache &intfCache = GetIntfCache(name);
2900 if (intfCache.initCheck() != OK) {
2901 continue;
2902 }
2903 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2904 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2905 *isCompatible = false;
2906 return OK;
2907 }
2908 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002909 std::set<C2Allocator::id_t> allocators;
2910 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2911 if (allocators.empty()) {
2912 *isCompatible = false;
2913 return OK;
2914 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002915
2916 uint64_t minUsage = 0;
2917 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002918 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002919 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002920 *isCompatible = ((maxUsage & minUsage) == minUsage);
2921 return OK;
2922}
2923
2924static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2925 static std::mutex sMutex{};
2926 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2927 std::unique_lock<std::mutex> lock{sMutex};
2928 std::shared_ptr<C2BlockPool> pool;
2929 auto it = sPools.find(allocId);
2930 if (it == sPools.end()) {
2931 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2932 if (err == OK) {
2933 sPools.emplace(allocId, pool);
2934 } else {
2935 pool.reset();
2936 }
2937 } else {
2938 pool = it->second;
2939 }
2940 return pool;
2941}
2942
2943// static
2944std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2945 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002946 std::set<C2Allocator::id_t> allocators;
2947 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2948 if (allocators.empty()) {
2949 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2950 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002951
2952 uint64_t minUsage = 0;
2953 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002954 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002955 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002956 if ((maxUsage & minUsage) != minUsage) {
2957 allocators.clear();
2958 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2959 }
2960 std::shared_ptr<C2LinearBlock> block;
2961 for (C2Allocator::id_t allocId : allocators) {
2962 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2963 if (!pool) {
2964 continue;
2965 }
2966 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2967 if (err != C2_OK || !block) {
2968 block.reset();
2969 continue;
2970 }
2971 break;
2972 }
2973 return block;
2974}
2975
2976// static
2977status_t CCodec::CanFetchGraphicBlock(
2978 const std::vector<std::string> &names, bool *isCompatible) {
2979 uint64_t minUsage = 0;
2980 uint64_t maxUsage = ~0ull;
2981 std::set<C2Allocator::id_t> allocators;
2982 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2983 if (allocators.empty()) {
2984 *isCompatible = false;
2985 return OK;
2986 }
2987 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2988 *isCompatible = ((maxUsage & minUsage) == minUsage);
2989 return OK;
2990}
2991
2992// static
2993std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2994 int32_t width,
2995 int32_t height,
2996 int32_t format,
2997 uint64_t usage,
2998 const std::vector<std::string> &names) {
2999 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
3000 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
3001 ALOGD("Unrecognized pixel format: %d", format);
3002 return nullptr;
3003 }
3004 uint64_t minUsage = 0;
3005 uint64_t maxUsage = ~0ull;
3006 std::set<C2Allocator::id_t> allocators;
3007 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
3008 if (allocators.empty()) {
3009 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3010 }
3011 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
3012 minUsage |= usage;
3013 if ((maxUsage & minUsage) != minUsage) {
3014 allocators.clear();
3015 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
3016 }
3017 std::shared_ptr<C2GraphicBlock> block;
3018 for (C2Allocator::id_t allocId : allocators) {
3019 std::shared_ptr<C2BlockPool> pool;
3020 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
3021 if (err != C2_OK || !pool) {
3022 continue;
3023 }
3024 err = pool->fetchGraphicBlock(
3025 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
3026 if (err != C2_OK || !block) {
3027 block.reset();
3028 continue;
3029 }
3030 break;
3031 }
3032 return block;
3033}
3034
Wonsik Kim155d5cb2019-10-09 12:49:49 -07003035} // namespace android