blob: a23b9bda20388ff41a1e72a94f3df9f243941a12 [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>
33#include <android-base/stringprintf.h>
34#include <cutils/properties.h>
35#include <gui/IGraphicBufferProducer.h>
36#include <gui/Surface.h>
37#include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070038#include <media/omx/1.0/WOmxNode.h>
39#include <media/openmax/OMX_Core.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080040#include <media/openmax/OMX_IndexExt.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070041#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
42#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070043#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080044#include <media/stagefright/BufferProducerWrapper.h>
45#include <media/stagefright/MediaCodecConstants.h>
46#include <media/stagefright/PersistentSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080047
48#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080049#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070050#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080051#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080052#include "InputSurfaceWrapper.h"
53
54extern "C" android::PersistentSurface *CreateInputSurface();
55
56namespace android {
57
58using namespace std::chrono_literals;
59using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
60using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080061using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080062
Wonsik Kim9917d4a2019-10-24 12:56:38 -070063typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070064typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070065
Pawin Vongmasa36653902018-11-15 00:10:25 -080066namespace {
67
68class CCodecWatchdog : public AHandler {
69private:
70 enum {
71 kWhatWatch,
72 };
73 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
74
75public:
76 static sp<CCodecWatchdog> getInstance() {
77 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
78 static std::once_flag flag;
79 // Call Init() only once.
80 std::call_once(flag, Init, instance);
81 return instance;
82 }
83
84 ~CCodecWatchdog() = default;
85
86 void watch(sp<CCodec> codec) {
87 bool shouldPost = false;
88 {
89 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
90 // If a watch message is in flight, piggy-back this instance as well.
91 // Otherwise, post a new watch message.
92 shouldPost = codecs->empty();
93 codecs->emplace(codec);
94 }
95 if (shouldPost) {
96 ALOGV("posting watch message");
97 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
98 }
99 }
100
101protected:
102 void onMessageReceived(const sp<AMessage> &msg) {
103 switch (msg->what()) {
104 case kWhatWatch: {
105 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
106 ALOGV("watch for %zu codecs", codecs->size());
107 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
108 sp<CCodec> codec = it->promote();
109 if (codec == nullptr) {
110 continue;
111 }
112 codec->initiateReleaseIfStuck();
113 }
114 codecs->clear();
115 break;
116 }
117
118 default: {
119 TRESPASS("CCodecWatchdog: unrecognized message");
120 }
121 }
122 }
123
124private:
125 CCodecWatchdog() : mLooper(new ALooper) {}
126
127 static void Init(const sp<CCodecWatchdog> &thiz) {
128 ALOGV("Init");
129 thiz->mLooper->setName("CCodecWatchdog");
130 thiz->mLooper->registerHandler(thiz);
131 thiz->mLooper->start();
132 }
133
134 sp<ALooper> mLooper;
135
136 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
137};
138
139class C2InputSurfaceWrapper : public InputSurfaceWrapper {
140public:
141 explicit C2InputSurfaceWrapper(
142 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
143 mSurface(surface) {
144 }
145
146 ~C2InputSurfaceWrapper() override = default;
147
148 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
149 if (mConnection != nullptr) {
150 return ALREADY_EXISTS;
151 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800152 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800153 }
154
155 void disconnect() override {
156 if (mConnection != nullptr) {
157 mConnection->disconnect();
158 mConnection = nullptr;
159 }
160 }
161
162 status_t start() override {
163 // InputSurface does not distinguish started state
164 return OK;
165 }
166
167 status_t signalEndOfInputStream() override {
168 C2InputSurfaceEosTuning eos(true);
169 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800170 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800171 if (err != C2_OK) {
172 return UNKNOWN_ERROR;
173 }
174 return OK;
175 }
176
177 status_t configure(Config &config __unused) {
178 // TODO
179 return OK;
180 }
181
182private:
183 std::shared_ptr<Codec2Client::InputSurface> mSurface;
184 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
185};
186
187class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
188public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700189 typedef hardware::media::omx::V1_0::Status OmxStatus;
190
Pawin Vongmasa36653902018-11-15 00:10:25 -0800191 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700192 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800193 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700194 uint32_t height,
195 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800196 : mSource(source), mWidth(width), mHeight(height) {
197 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700198 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800199 }
200 ~GraphicBufferSourceWrapper() override = default;
201
202 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
203 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700204 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800205 mNode->setFrameSize(mWidth, mHeight);
206
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700207 // Usage is queried during configure(), so setting it beforehand.
208 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
209 (void)mNode->setParameter(
210 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
211 &usage, sizeof(usage));
212
Pawin Vongmasa36653902018-11-15 00:10:25 -0800213 // NOTE: we do not use/pass through color aspects from GraphicBufferSource as we
214 // communicate that directly to the component.
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700215 mSource->configure(
216 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800217 return OK;
218 }
219
220 void disconnect() override {
221 if (mNode == nullptr) {
222 return;
223 }
224 sp<IOMXBufferSource> source = mNode->getSource();
225 if (source == nullptr) {
226 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
227 return;
228 }
229 source->onOmxIdle();
230 source->onOmxLoaded();
231 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700232 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800233 }
234
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700235 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
236 if (status.isOk()) {
237 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
238 } else if (status.isDeadObject()) {
239 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800240 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700241 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800242 }
243
244 status_t start() override {
245 sp<IOMXBufferSource> source = mNode->getSource();
246 if (source == nullptr) {
247 return NO_INIT;
248 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900249
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800250 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800251 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900252
Wonsik Kim34d66012021-03-01 16:40:33 -0800253 OMX_PARAM_PORTDEFINITIONTYPE param;
254 param.nPortIndex = kPortIndexInput;
255 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
256 &param, sizeof(param));
257 if (err == OK) {
258 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900259 }
260
261 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800262 source->onInputBufferAdded(i);
263 }
264
265 source->onOmxExecuting();
266 return OK;
267 }
268
269 status_t signalEndOfInputStream() override {
270 return GetStatus(mSource->signalEndOfInputStream());
271 }
272
273 status_t configure(Config &config) {
274 std::stringstream status;
275 status_t err = OK;
276
277 // handle each configuration granually, in case we need to handle part of the configuration
278 // elsewhere
279
280 // TRICKY: we do not unset frame delay repeating
281 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
282 int64_t us = 1e6 / config.mMinFps + 0.5;
283 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
284 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
285 if (res != OK) {
286 status << " (=> " << asString(res) << ")";
287 err = res;
288 }
289 mConfig.mMinFps = config.mMinFps;
290 }
291
292 // pts gap
293 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
294 if (mNode != nullptr) {
295 OMX_PARAM_U32TYPE ptrGapParam = {};
296 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700297 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800298 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
299 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700300 // float -> uint32_t is undefined if the value is negative.
301 // First convert to int32_t to ensure the expected behavior.
302 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800303 (void)mNode->setParameter(
304 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
305 &ptrGapParam, sizeof(ptrGapParam));
306 }
307 }
308
309 // max fps
310 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700311 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800312 && config.mMaxFps != mConfig.mMaxFps) {
313 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
314 status << " maxFps=" << config.mMaxFps;
315 if (res != OK) {
316 status << " (=> " << asString(res) << ")";
317 err = res;
318 }
319 mConfig.mMaxFps = config.mMaxFps;
320 }
321
322 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
323 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
324 status << " timeOffset " << config.mTimeOffsetUs << "us";
325 if (res != OK) {
326 status << " (=> " << asString(res) << ")";
327 err = res;
328 }
329 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
330 }
331
332 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
333 status_t res =
334 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
335 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
336 if (res != OK) {
337 status << " (=> " << asString(res) << ")";
338 err = res;
339 }
340 mConfig.mCaptureFps = config.mCaptureFps;
341 mConfig.mCodedFps = config.mCodedFps;
342 }
343
344 if (config.mStartAtUs != mConfig.mStartAtUs
345 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
346 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
347 status << " start at " << config.mStartAtUs << "us";
348 if (res != OK) {
349 status << " (=> " << asString(res) << ")";
350 err = res;
351 }
352 mConfig.mStartAtUs = config.mStartAtUs;
353 mConfig.mStopped = config.mStopped;
354 }
355
356 // suspend-resume
357 if (config.mSuspended != mConfig.mSuspended) {
358 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
359 status << " " << (config.mSuspended ? "suspend" : "resume")
360 << " at " << config.mSuspendAtUs << "us";
361 if (res != OK) {
362 status << " (=> " << asString(res) << ")";
363 err = res;
364 }
365 mConfig.mSuspended = config.mSuspended;
366 mConfig.mSuspendAtUs = config.mSuspendAtUs;
367 }
368
369 if (config.mStopped != mConfig.mStopped && config.mStopped) {
370 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
371 status << " stop at " << config.mStopAtUs << "us";
372 if (res != OK) {
373 status << " (=> " << asString(res) << ")";
374 err = res;
375 } else {
376 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700377 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
378 [&res, &delayUs = config.mInputDelayUs](
379 auto status, auto stopTimeOffsetUs) {
380 res = static_cast<status_t>(status);
381 delayUs = stopTimeOffsetUs;
382 });
383 if (!trans.isOk()) {
384 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
385 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800386 if (res != OK) {
387 status << " (=> " << asString(res) << ")";
388 } else {
389 status << "=" << config.mInputDelayUs << "us";
390 }
391 mConfig.mInputDelayUs = config.mInputDelayUs;
392 }
393 mConfig.mStopAtUs = config.mStopAtUs;
394 mConfig.mStopped = config.mStopped;
395 }
396
397 // color aspects (android._color-aspects)
398
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700399 // consumer usage is queried earlier.
400
Wonsik Kimbd557932019-07-02 15:51:20 -0700401 if (status.str().empty()) {
402 ALOGD("ISConfig not changed");
403 } else {
404 ALOGD("ISConfig%s", status.str().c_str());
405 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800406 return err;
407 }
408
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700409 void onInputBufferDone(c2_cntr64_t index) override {
410 mNode->onInputBufferDone(index);
411 }
412
Pawin Vongmasa36653902018-11-15 00:10:25 -0800413private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700414 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800415 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700416 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800417 uint32_t mWidth;
418 uint32_t mHeight;
419 Config mConfig;
420};
421
422class Codec2ClientInterfaceWrapper : public C2ComponentStore {
423 std::shared_ptr<Codec2Client> mClient;
424
425public:
426 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
427 : mClient(client) { }
428
429 virtual ~Codec2ClientInterfaceWrapper() = default;
430
431 virtual c2_status_t config_sm(
432 const std::vector<C2Param *> &params,
433 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
434 return mClient->config(params, C2_MAY_BLOCK, failures);
435 };
436
437 virtual c2_status_t copyBuffer(
438 std::shared_ptr<C2GraphicBuffer>,
439 std::shared_ptr<C2GraphicBuffer>) {
440 return C2_OMITTED;
441 }
442
443 virtual c2_status_t createComponent(
444 C2String, std::shared_ptr<C2Component> *const component) {
445 component->reset();
446 return C2_OMITTED;
447 }
448
449 virtual c2_status_t createInterface(
450 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
451 interface->reset();
452 return C2_OMITTED;
453 }
454
455 virtual c2_status_t query_sm(
456 const std::vector<C2Param *> &stackParams,
457 const std::vector<C2Param::Index> &heapParamIndices,
458 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
459 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
460 }
461
462 virtual c2_status_t querySupportedParams_nb(
463 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
464 return mClient->querySupportedParams(params);
465 }
466
467 virtual c2_status_t querySupportedValues_sm(
468 std::vector<C2FieldSupportedValuesQuery> &fields) const {
469 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
470 }
471
472 virtual C2String getName() const {
473 return mClient->getName();
474 }
475
476 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
477 return mClient->getParamReflector();
478 }
479
480 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
481 return std::vector<std::shared_ptr<const C2Component::Traits>>();
482 }
483};
484
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800485void RevertOutputFormatIfNeeded(
486 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
487 // We used to not report changes to these keys to the client.
488 const static std::set<std::string> sIgnoredKeys({
489 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800490 KEY_FRAME_RATE,
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800491 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800492 KEY_MAX_WIDTH,
493 KEY_MAX_HEIGHT,
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800494 "csd-0",
495 "csd-1",
496 "csd-2",
497 });
498 if (currentFormat == oldFormat) {
499 return;
500 }
501 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
502 AMessage::Type type;
503 for (size_t i = diff->countEntries(); i > 0; --i) {
504 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
505 diff->removeEntryAt(i - 1);
506 }
507 }
508 if (diff->countEntries() == 0) {
509 currentFormat = oldFormat;
510 }
511}
512
Pawin Vongmasa36653902018-11-15 00:10:25 -0800513} // namespace
514
515// CCodec::ClientListener
516
517struct CCodec::ClientListener : public Codec2Client::Listener {
518
519 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
520
521 virtual void onWorkDone(
522 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800523 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800524 (void)component;
525 sp<CCodec> codec(mCodec.promote());
526 if (!codec) {
527 return;
528 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800529 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800530 }
531
532 virtual void onTripped(
533 const std::weak_ptr<Codec2Client::Component>& component,
534 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
535 ) override {
536 // TODO
537 (void)component;
538 (void)settingResult;
539 }
540
541 virtual void onError(
542 const std::weak_ptr<Codec2Client::Component>& component,
543 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800544 {
545 // Component is only used for reporting as we use a separate listener for each instance
546 std::shared_ptr<Codec2Client::Component> comp = component.lock();
547 if (!comp) {
548 ALOGD("Component died with error: 0x%x", errorCode);
549 } else {
550 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
551 }
552 }
553
554 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800555 // Note: for now we do not propagate the error code to MediaCodec
556 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800557 sp<CCodec> codec(mCodec.promote());
558 if (!codec || !codec->mCallback) {
559 return;
560 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800561 codec->mCallback->onError(
562 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
563 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800564 }
565
566 virtual void onDeath(
567 const std::weak_ptr<Codec2Client::Component>& component) override {
568 { // Log the death of the component.
569 std::shared_ptr<Codec2Client::Component> comp = component.lock();
570 if (!comp) {
571 ALOGE("Codec2 component died.");
572 } else {
573 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
574 }
575 }
576
577 // Report to MediaCodec.
578 sp<CCodec> codec(mCodec.promote());
579 if (!codec || !codec->mCallback) {
580 return;
581 }
582 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
583 }
584
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800585 virtual void onFrameRendered(uint64_t bufferQueueId,
586 int32_t slotId,
587 int64_t timestampNs) override {
588 // TODO: implement
589 (void)bufferQueueId;
590 (void)slotId;
591 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800592 }
593
594 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800595 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800596 sp<CCodec> codec(mCodec.promote());
597 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800598 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800599 }
600 }
601
602private:
603 wp<CCodec> mCodec;
604};
605
606// CCodecCallbackImpl
607
608class CCodecCallbackImpl : public CCodecCallback {
609public:
610 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
611 ~CCodecCallbackImpl() override = default;
612
613 void onError(status_t err, enum ActionCode actionCode) override {
614 mCodec->mCallback->onError(err, actionCode);
615 }
616
617 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
618 mCodec->mCallback->onOutputFramesRendered(
619 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
620 }
621
Pawin Vongmasa36653902018-11-15 00:10:25 -0800622 void onOutputBuffersChanged() override {
623 mCodec->mCallback->onOutputBuffersChanged();
624 }
625
626private:
627 CCodec *mCodec;
628};
629
630// CCodec
631
632CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700633 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
634 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800635}
636
637CCodec::~CCodec() {
638}
639
640std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
641 return mChannel;
642}
643
644status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
645 status_t err = job();
646 if (err != C2_OK) {
647 mCallback->onError(err, ACTION_CODE_FATAL);
648 }
649 return err;
650}
651
652void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
653 auto setAllocating = [this] {
654 Mutexed<State>::Locked state(mState);
655 if (state->get() != RELEASED) {
656 return INVALID_OPERATION;
657 }
658 state->set(ALLOCATING);
659 return OK;
660 };
661 if (tryAndReportOnError(setAllocating) != OK) {
662 return;
663 }
664
665 sp<RefBase> codecInfo;
666 CHECK(msg->findObject("codecInfo", &codecInfo));
667 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
668
669 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
670 allocMsg->setObject("codecInfo", codecInfo);
671 allocMsg->post();
672}
673
674void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
675 if (codecInfo == nullptr) {
676 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
677 return;
678 }
679 ALOGD("allocate(%s)", codecInfo->getCodecName());
680 mClientListener.reset(new ClientListener(this));
681
682 AString componentName = codecInfo->getCodecName();
683 std::shared_ptr<Codec2Client> client;
684
685 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700686 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800687 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800688 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800689 SetPreferredCodec2ComponentStore(
690 std::make_shared<Codec2ClientInterfaceWrapper>(client));
691 }
692
693 std::shared_ptr<Codec2Client::Component> comp =
694 Codec2Client::CreateComponentByName(
695 componentName.c_str(),
696 mClientListener,
697 &client);
698 if (!comp) {
699 ALOGE("Failed Create component: %s", componentName.c_str());
700 Mutexed<State>::Locked state(mState);
701 state->set(RELEASED);
702 state.unlock();
703 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
704 state.lock();
705 return;
706 }
707 ALOGI("Created component [%s]", componentName.c_str());
708 mChannel->setComponent(comp);
709 auto setAllocated = [this, comp, client] {
710 Mutexed<State>::Locked state(mState);
711 if (state->get() != ALLOCATING) {
712 state->set(RELEASED);
713 return UNKNOWN_ERROR;
714 }
715 state->set(ALLOCATED);
716 state->comp = comp;
717 mClient = client;
718 return OK;
719 };
720 if (tryAndReportOnError(setAllocated) != OK) {
721 return;
722 }
723
724 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700725 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
726 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800727 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800728 if (err != OK) {
729 ALOGW("Failed to initialize configuration support");
730 // TODO: report error once we complete implementation.
731 }
732 config->queryConfiguration(comp);
733
734 mCallback->onComponentAllocated(componentName.c_str());
735}
736
737void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
738 auto checkAllocated = [this] {
739 Mutexed<State>::Locked state(mState);
740 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
741 };
742 if (tryAndReportOnError(checkAllocated) != OK) {
743 return;
744 }
745
746 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
747 msg->setMessage("format", format);
748 msg->post();
749}
750
751void CCodec::configure(const sp<AMessage> &msg) {
752 std::shared_ptr<Codec2Client::Component> comp;
753 auto checkAllocated = [this, &comp] {
754 Mutexed<State>::Locked state(mState);
755 if (state->get() != ALLOCATED) {
756 state->set(RELEASED);
757 return UNKNOWN_ERROR;
758 }
759 comp = state->comp;
760 return OK;
761 };
762 if (tryAndReportOnError(checkAllocated) != OK) {
763 return;
764 }
765
766 auto doConfig = [msg, comp, this]() -> status_t {
767 AString mime;
768 if (!msg->findString("mime", &mime)) {
769 return BAD_VALUE;
770 }
771
772 int32_t encoder;
773 if (!msg->findInt32("encoder", &encoder)) {
774 encoder = false;
775 }
776
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800777 int32_t flags;
778 if (!msg->findInt32("flags", &flags)) {
779 return BAD_VALUE;
780 }
781
Pawin Vongmasa36653902018-11-15 00:10:25 -0800782 // TODO: read from intf()
783 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
784 return UNKNOWN_ERROR;
785 }
786
787 int32_t storeMeta;
788 if (encoder
789 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
790 && storeMeta != kMetadataBufferTypeInvalid) {
791 if (storeMeta != kMetadataBufferTypeANWBuffer) {
792 ALOGD("Only ANW buffers are supported for legacy metadata mode");
793 return BAD_VALUE;
794 }
795 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
796 }
797
798 sp<RefBase> obj;
799 sp<Surface> surface;
800 if (msg->findObject("native-window", &obj)) {
801 surface = static_cast<Surface *>(obj.get());
802 setSurface(surface);
803 }
804
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700805 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
806 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800807 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800808 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
809 ALOGD("[%s] buffers are %sbound to CCodec for this session",
810 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800811
Wonsik Kim1114eea2019-02-25 14:35:24 -0800812 // Enforce required parameters
813 int32_t i32;
814 float flt;
815 if (config->mDomain & Config::IS_AUDIO) {
816 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
817 ALOGD("sample rate is missing, which is required for audio components.");
818 return BAD_VALUE;
819 }
820 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
821 ALOGD("channel count is missing, which is required for audio components.");
822 return BAD_VALUE;
823 }
824 if ((config->mDomain & Config::IS_ENCODER)
825 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
826 && !msg->findInt32(KEY_BIT_RATE, &i32)
827 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
828 ALOGD("bitrate is missing, which is required for audio encoders.");
829 return BAD_VALUE;
830 }
831 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800832 int32_t width = 0;
833 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800834 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800835 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800836 ALOGD("width is missing, which is required for image/video components.");
837 return BAD_VALUE;
838 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800839 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800840 ALOGD("height is missing, which is required for image/video components.");
841 return BAD_VALUE;
842 }
843 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700844 int32_t mode = BITRATE_MODE_VBR;
845 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700846 if (!msg->findInt32(KEY_QUALITY, &i32)) {
847 ALOGD("quality is missing, which is required for video encoders in CQ.");
848 return BAD_VALUE;
849 }
850 } else {
851 if (!msg->findInt32(KEY_BIT_RATE, &i32)
852 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
853 ALOGD("bitrate is missing, which is required for video encoders.");
854 return BAD_VALUE;
855 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800856 }
857 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
858 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
859 ALOGD("I frame interval is missing, which is required for video encoders.");
860 return BAD_VALUE;
861 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700862 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
863 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
864 ALOGD("frame rate is missing, which is required for video encoders.");
865 return BAD_VALUE;
866 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800867 }
868 }
869
Pawin Vongmasa36653902018-11-15 00:10:25 -0800870 /*
871 * Handle input surface configuration
872 */
873 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
874 && (config->mDomain & Config::IS_ENCODER)) {
875 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
876 {
877 config->mISConfig->mMinFps = 0;
878 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800879 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800880 config->mISConfig->mMinFps = 1e6 / value;
881 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700882 if (!msg->findFloat(
883 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
884 config->mISConfig->mMaxFps = -1;
885 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800886 config->mISConfig->mMinAdjustedFps = 0;
887 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800888 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800889 if (value < 0 && value >= INT32_MIN) {
890 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700891 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800892 } else if (value > 0 && value <= INT32_MAX) {
893 config->mISConfig->mMinAdjustedFps = 1e6 / value;
894 }
895 }
896 }
897
898 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700899 bool captureFpsFound = false;
900 double timeLapseFps;
901 float captureRate;
902 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
903 config->mISConfig->mCaptureFps = timeLapseFps;
904 captureFpsFound = true;
905 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
906 config->mISConfig->mCaptureFps = captureRate;
907 captureFpsFound = true;
908 }
909 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800910 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
911 }
912 }
913
914 {
915 config->mISConfig->mSuspended = false;
916 config->mISConfig->mSuspendAtUs = -1;
917 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800918 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800919 config->mISConfig->mSuspended = true;
920 }
921 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700922 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800923 }
924
925 /*
926 * Handle desired color format.
927 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700928 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800929 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700930 int32_t format = 0;
931 // Query vendor format for Flexible YUV
932 std::vector<std::unique_ptr<C2Param>> heapParams;
933 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
934 if (mClient->query(
935 {},
936 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
937 C2_MAY_BLOCK,
938 &heapParams) == C2_OK
939 && heapParams.size() == 1u) {
940 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
941 heapParams[0].get());
942 } else {
943 pixelFormatInfo = nullptr;
944 }
945 std::optional<uint32_t> flexPixelFormat{};
946 std::optional<uint32_t> flexPlanarPixelFormat{};
947 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
948 if (pixelFormatInfo && *pixelFormatInfo) {
949 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
950 const C2FlexiblePixelFormatDescriptorStruct &desc =
951 pixelFormatInfo->m.values[i];
952 if (desc.bitDepth != 8
953 || desc.subsampling != C2Color::YUV_420
954 // TODO(b/180076105): some device report wrong layout
955 // || desc.layout == C2Color::INTERLEAVED_PACKED
956 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
957 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
958 continue;
959 }
960 if (!flexPixelFormat) {
961 flexPixelFormat = desc.pixelFormat;
962 }
963 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
964 flexPlanarPixelFormat = desc.pixelFormat;
965 }
966 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
967 flexSemiPlanarPixelFormat = desc.pixelFormat;
968 }
969 }
970 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800971 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700972 // Also handle default color format (encoders require color format, so this is only
973 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -0800974 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700975 if (surface == nullptr) {
976 format = flexPixelFormat.value_or(COLOR_FormatYUV420Flexible);
977 } else {
978 format = COLOR_FormatSurface;
979 }
980 defaultColorFormat = format;
981 }
982 } else {
983 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
984 switch (format) {
985 case COLOR_FormatYUV420Flexible:
986 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
987 break;
988 case COLOR_FormatYUV420Planar:
989 case COLOR_FormatYUV420PackedPlanar:
990 format = flexPlanarPixelFormat.value_or(
991 flexPixelFormat.value_or(format));
992 break;
993 case COLOR_FormatYUV420SemiPlanar:
994 case COLOR_FormatYUV420PackedSemiPlanar:
995 format = flexSemiPlanarPixelFormat.value_or(
996 flexPixelFormat.value_or(format));
997 break;
998 default:
999 // No-op
1000 break;
1001 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001002 }
1003 }
1004
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001005 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001006 msg->setInt32("android._color-format", format);
1007 }
1008 }
1009
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001010 int32_t subscribeToAllVendorParams;
1011 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1012 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1013 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1014 }
1015 }
1016
Pawin Vongmasa36653902018-11-15 00:10:25 -08001017 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001018 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1019 // the behavior here.
1020 sp<AMessage> sdkParams = msg;
1021 int32_t videoBitrate;
1022 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1023 sdkParams = msg->dup();
1024 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1025 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001026 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001027 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001028 if (err != OK) {
1029 ALOGW("failed to convert configuration to c2 params");
1030 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001031
1032 int32_t maxBframes = 0;
1033 if ((config->mDomain & Config::IS_ENCODER)
1034 && (config->mDomain & Config::IS_VIDEO)
1035 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1036 && maxBframes > 0) {
1037 std::unique_ptr<C2StreamGopTuning::output> gop =
1038 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1039 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1040 gop->m.values[1] = {
1041 C2Config::picture_type_t(P_FRAME | B_FRAME),
1042 uint32_t(maxBframes)
1043 };
1044 configUpdate.push_back(std::move(gop));
1045 }
1046
Pawin Vongmasa36653902018-11-15 00:10:25 -08001047 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1048 if (err != OK) {
1049 ALOGW("failed to configure c2 params");
1050 return err;
1051 }
1052
1053 std::vector<std::unique_ptr<C2Param>> params;
1054 C2StreamUsageTuning::input usage(0u, 0u);
1055 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001056 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001057
Wonsik Kim58d83332021-02-07 22:19:56 -08001058 C2Param::Index colorAspectsRequestIndex =
1059 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001060 std::initializer_list<C2Param::Index> indices {
Wonsik Kim58d83332021-02-07 22:19:56 -08001061 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001062 };
1063 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001064 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001065 indices,
1066 C2_DONT_BLOCK,
1067 &params);
1068 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1069 ALOGE("Failed to query component interface: %d", c2err);
1070 return UNKNOWN_ERROR;
1071 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001072 if (usage) {
1073 if (usage.value & C2MemoryUsage::CPU_READ) {
1074 config->mInputFormat->setInt32("using-sw-read-often", true);
1075 }
1076 if (config->mISConfig) {
1077 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1078 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1079 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001080 }
1081
1082 // NOTE: we don't blindly use client specified input size if specified as clients
1083 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1084 // client specified size is only used to ask for bigger buffers than component suggested
1085 // size.
1086 int32_t clientInputSize = 0;
1087 bool clientSpecifiedInputSize =
1088 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1089 // TEMP: enforce minimum buffer size of 1MB for video decoders
1090 // and 16K / 4K for audio encoders/decoders
1091 if (maxInputSize.value == 0) {
1092 if (config->mDomain & Config::IS_AUDIO) {
1093 maxInputSize.value = encoder ? 16384 : 4096;
1094 } else if (!encoder) {
1095 maxInputSize.value = 1048576u;
1096 }
1097 }
1098
1099 // verify that CSD fits into this size (if defined)
1100 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1101 sp<ABuffer> csd;
1102 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1103 if (csd && csd->size() > maxInputSize.value) {
1104 maxInputSize.value = csd->size();
1105 }
1106 }
1107 }
1108
1109 // TODO: do this based on component requiring linear allocator for input
1110 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1111 if (clientSpecifiedInputSize) {
1112 // Warn that we're overriding client's max input size if necessary.
1113 if ((uint32_t)clientInputSize < maxInputSize.value) {
1114 ALOGD("client requested max input size %d, which is smaller than "
1115 "what component recommended (%u); overriding with component "
1116 "recommendation.", clientInputSize, maxInputSize.value);
1117 ALOGW("This behavior is subject to change. It is recommended that "
1118 "app developers double check whether the requested "
1119 "max input size is in reasonable range.");
1120 } else {
1121 maxInputSize.value = clientInputSize;
1122 }
1123 }
1124 // Pass max input size on input format to the buffer channel (if supplied by the
1125 // component or by a default)
1126 if (maxInputSize.value) {
1127 config->mInputFormat->setInt32(
1128 KEY_MAX_INPUT_SIZE,
1129 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1130 }
1131 }
1132
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001133 int32_t clientPrepend;
1134 if ((config->mDomain & Config::IS_VIDEO)
1135 && (config->mDomain & Config::IS_ENCODER)
1136 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1137 && clientPrepend
1138 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1139 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1140 return BAD_VALUE;
1141 }
1142
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001143 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001144 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1145 // propagate HDR static info to output format for both encoders and decoders
1146 // if component supports this info, we will update from component, but only the raw port,
1147 // so don't propagate if component already filled it in.
1148 sp<ABuffer> hdrInfo;
1149 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1150 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1151 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1152 }
1153
1154 // Set desired color format from configuration parameter
1155 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001156 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1157 format = defaultColorFormat;
1158 }
1159 if (config->mDomain & Config::IS_ENCODER) {
1160 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001161 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1162 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001163 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001164 } else {
1165 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001166 }
1167 }
1168
1169 // propagate encoder delay and padding to output format
1170 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1171 int delay = 0;
1172 if (msg->findInt32("encoder-delay", &delay)) {
1173 config->mOutputFormat->setInt32("encoder-delay", delay);
1174 }
1175 int padding = 0;
1176 if (msg->findInt32("encoder-padding", &padding)) {
1177 config->mOutputFormat->setInt32("encoder-padding", padding);
1178 }
1179 }
1180
1181 // set channel-mask
1182 if (config->mDomain & Config::IS_AUDIO) {
1183 int32_t mask;
1184 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1185 if (config->mDomain & Config::IS_ENCODER) {
1186 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1187 } else {
1188 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1189 }
1190 }
1191 }
1192
Wonsik Kim58d83332021-02-07 22:19:56 -08001193 std::unique_ptr<C2Param> colorTransferRequestParam;
1194 for (std::unique_ptr<C2Param> &param : params) {
1195 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1196 ALOGI("found color transfer request param");
1197 colorTransferRequestParam = std::move(param);
1198 }
1199 }
1200 int32_t colorTransferRequest = 0;
1201 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1202 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1203 colorTransferRequest = 0;
1204 }
1205
1206 if (colorTransferRequest != 0) {
1207 if (colorTransferRequestParam && *colorTransferRequestParam) {
1208 C2StreamColorAspectsInfo::output *info =
1209 static_cast<C2StreamColorAspectsInfo::output *>(
1210 colorTransferRequestParam.get());
1211 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1212 colorTransferRequest = 0;
1213 }
1214 } else {
1215 colorTransferRequest = 0;
1216 }
1217 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1218 }
1219
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001220 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1221 // Need to get stride/vstride
1222 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1223 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1224 // TODO: retrieve these values without allocating a buffer.
1225 // Currently allocating a buffer is necessary to retrieve the layout.
1226 int64_t blockUsage =
1227 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1228 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1229 width, height, pixelFormat, blockUsage, {comp->getName()});
1230 sp<GraphicBlockBuffer> buffer;
1231 if (block) {
1232 buffer = GraphicBlockBuffer::Allocate(
1233 config->mInputFormat,
1234 block,
1235 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1236 } else {
1237 ALOGD("Failed to allocate a graphic block "
1238 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1239 width, height, pixelFormat, (long long)blockUsage);
1240 // This means that byte buffer mode is not supported in this configuration
1241 // anyway. Skip setting stride/vstride to input format.
1242 }
1243 if (buffer) {
1244 sp<ABuffer> imageData = buffer->getImageData();
1245 MediaImage2 *img = nullptr;
1246 if (imageData && imageData->data()
1247 && imageData->size() >= sizeof(MediaImage2)) {
1248 img = (MediaImage2*)imageData->data();
1249 }
1250 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1251 int32_t stride = img->mPlane[0].mRowInc;
1252 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1253 if (img->mNumPlanes > 1 && stride > 0) {
1254 int64_t offsetDelta =
1255 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1256 if (offsetDelta % stride == 0) {
1257 int32_t vstride = int32_t(offsetDelta / stride);
1258 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1259 } else {
1260 ALOGD("Cannot report accurate slice height: "
1261 "offsetDelta = %lld stride = %d",
1262 (long long)offsetDelta, stride);
1263 }
1264 }
1265 }
1266 }
1267 }
1268 }
1269
1270 ALOGD("setup formats input: %s",
1271 config->mInputFormat->debugString().c_str());
1272 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001273 config->mOutputFormat->debugString().c_str());
1274 return OK;
1275 };
1276 if (tryAndReportOnError(doConfig) != OK) {
1277 return;
1278 }
1279
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001280 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1281 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001282
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001283 config->queryConfiguration(comp);
1284
Pawin Vongmasa36653902018-11-15 00:10:25 -08001285 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1286}
1287
1288void CCodec::initiateCreateInputSurface() {
1289 status_t err = [this] {
1290 Mutexed<State>::Locked state(mState);
1291 if (state->get() != ALLOCATED) {
1292 return UNKNOWN_ERROR;
1293 }
1294 // TODO: read it from intf() properly.
1295 if (state->comp->getName().find("encoder") == std::string::npos) {
1296 return INVALID_OPERATION;
1297 }
1298 return OK;
1299 }();
1300 if (err != OK) {
1301 mCallback->onInputSurfaceCreationFailed(err);
1302 return;
1303 }
1304
1305 (new AMessage(kWhatCreateInputSurface, this))->post();
1306}
1307
Lajos Molnar47118272019-01-31 16:28:04 -08001308sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1309 using namespace android::hardware::media::omx::V1_0;
1310 using namespace android::hardware::media::omx::V1_0::utils;
1311 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1312 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1313 android::sp<IOmx> omx = IOmx::getService();
1314 typedef android::hardware::graphics::bufferqueue::V1_0::
1315 IGraphicBufferProducer HGraphicBufferProducer;
1316 typedef android::hardware::media::omx::V1_0::
1317 IGraphicBufferSource HGraphicBufferSource;
1318 OmxStatus s;
1319 android::sp<HGraphicBufferProducer> gbp;
1320 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001321
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001322 using ::android::hardware::Return;
1323 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001324 [&s, &gbp, &gbs](
1325 OmxStatus status,
1326 const android::sp<HGraphicBufferProducer>& producer,
1327 const android::sp<HGraphicBufferSource>& source) {
1328 s = status;
1329 gbp = producer;
1330 gbs = source;
1331 });
1332 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001333 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001334 }
1335
1336 return nullptr;
1337}
1338
1339sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1340 sp<PersistentSurface> surface(CreateInputSurface());
1341
1342 if (surface == nullptr) {
1343 surface = CreateOmxInputSurface();
1344 }
1345
1346 return surface;
1347}
1348
Pawin Vongmasa36653902018-11-15 00:10:25 -08001349void CCodec::createInputSurface() {
1350 status_t err;
1351 sp<IGraphicBufferProducer> bufferProducer;
1352
1353 sp<AMessage> inputFormat;
1354 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001355 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001356 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001357 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1358 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001359 inputFormat = config->mInputFormat;
1360 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001361 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001362 }
1363
Lajos Molnar47118272019-01-31 16:28:04 -08001364 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001365 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1366 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1367 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001368
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001369 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001370 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1371 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001372 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001373 inputSurface));
1374 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001375 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001376 int32_t width = 0;
1377 (void)outputFormat->findInt32("width", &width);
1378 int32_t height = 0;
1379 (void)outputFormat->findInt32("height", &height);
1380 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001381 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001382 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001383 } else {
1384 ALOGE("Corrupted input surface");
1385 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1386 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001387 }
1388
1389 if (err != OK) {
1390 ALOGE("Failed to set up input surface: %d", err);
1391 mCallback->onInputSurfaceCreationFailed(err);
1392 return;
1393 }
1394
1395 mCallback->onInputSurfaceCreated(
1396 inputFormat,
1397 outputFormat,
1398 new BufferProducerWrapper(bufferProducer));
1399}
1400
1401status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001402 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1403 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001404 config->mUsingSurface = true;
1405
1406 // we are now using surface - apply default color aspects to input format - as well as
1407 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001408 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001409 ALOGD("input format %s to %s",
1410 inputFormatChanged ? "changed" : "unchanged",
1411 config->mInputFormat->debugString().c_str());
1412
1413 // configure dataspace
1414 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1415 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1416 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1417 surface->setDataSpace(dataSpace);
1418
1419 status_t err = mChannel->setInputSurface(surface);
1420 if (err != OK) {
1421 // undo input format update
1422 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001423 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001424 return err;
1425 }
1426 config->mInputSurface = surface;
1427
1428 if (config->mISConfig) {
1429 surface->configure(*config->mISConfig);
1430 } else {
1431 ALOGD("ISConfig: no configuration");
1432 }
1433
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001434 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001435}
1436
1437void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1438 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1439 msg->setObject("surface", surface);
1440 msg->post();
1441}
1442
1443void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1444 sp<AMessage> inputFormat;
1445 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001446 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001447 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001448 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1449 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001450 inputFormat = config->mInputFormat;
1451 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001452 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001453 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001454 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1455 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1456 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1457 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001458 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1459 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1460 if (err != OK) {
1461 ALOGE("Failed to set up input surface: %d", err);
1462 mCallback->onInputSurfaceDeclined(err);
1463 return;
1464 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001465 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001466 int32_t width = 0;
1467 (void)outputFormat->findInt32("width", &width);
1468 int32_t height = 0;
1469 (void)outputFormat->findInt32("height", &height);
1470 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001471 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001472 if (err != OK) {
1473 ALOGE("Failed to set up input surface: %d", err);
1474 mCallback->onInputSurfaceDeclined(err);
1475 return;
1476 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001477 } else {
1478 ALOGE("Failed to set input surface: Corrupted surface.");
1479 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1480 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001481 }
1482 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1483}
1484
1485void CCodec::initiateStart() {
1486 auto setStarting = [this] {
1487 Mutexed<State>::Locked state(mState);
1488 if (state->get() != ALLOCATED) {
1489 return UNKNOWN_ERROR;
1490 }
1491 state->set(STARTING);
1492 return OK;
1493 };
1494 if (tryAndReportOnError(setStarting) != OK) {
1495 return;
1496 }
1497
1498 (new AMessage(kWhatStart, this))->post();
1499}
1500
1501void CCodec::start() {
1502 std::shared_ptr<Codec2Client::Component> comp;
1503 auto checkStarting = [this, &comp] {
1504 Mutexed<State>::Locked state(mState);
1505 if (state->get() != STARTING) {
1506 return UNKNOWN_ERROR;
1507 }
1508 comp = state->comp;
1509 return OK;
1510 };
1511 if (tryAndReportOnError(checkStarting) != OK) {
1512 return;
1513 }
1514
1515 c2_status_t err = comp->start();
1516 if (err != C2_OK) {
1517 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1518 ACTION_CODE_FATAL);
1519 return;
1520 }
1521 sp<AMessage> inputFormat;
1522 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001523 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001524 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001525 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001526 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1527 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001528 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001529 // start triggers format dup
1530 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001531 if (config->mInputSurface) {
1532 err2 = config->mInputSurface->start();
1533 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001534 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001535 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001536 if (err2 != OK) {
1537 mCallback->onError(err2, ACTION_CODE_FATAL);
1538 return;
1539 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001540 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001541 if (err2 != OK) {
1542 mCallback->onError(err2, ACTION_CODE_FATAL);
1543 return;
1544 }
1545
1546 auto setRunning = [this] {
1547 Mutexed<State>::Locked state(mState);
1548 if (state->get() != STARTING) {
1549 return UNKNOWN_ERROR;
1550 }
1551 state->set(RUNNING);
1552 return OK;
1553 };
1554 if (tryAndReportOnError(setRunning) != OK) {
1555 return;
1556 }
1557 mCallback->onStartCompleted();
1558
1559 (void)mChannel->requestInitialInputBuffers();
1560}
1561
1562void CCodec::initiateShutdown(bool keepComponentAllocated) {
1563 if (keepComponentAllocated) {
1564 initiateStop();
1565 } else {
1566 initiateRelease();
1567 }
1568}
1569
1570void CCodec::initiateStop() {
1571 {
1572 Mutexed<State>::Locked state(mState);
1573 if (state->get() == ALLOCATED
1574 || state->get() == RELEASED
1575 || state->get() == STOPPING
1576 || state->get() == RELEASING) {
1577 // We're already stopped, released, or doing it right now.
1578 state.unlock();
1579 mCallback->onStopCompleted();
1580 state.lock();
1581 return;
1582 }
1583 state->set(STOPPING);
1584 }
1585
Wonsik Kim936a89c2020-05-08 16:07:50 -07001586 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001587 (new AMessage(kWhatStop, this))->post();
1588}
1589
1590void CCodec::stop() {
1591 std::shared_ptr<Codec2Client::Component> comp;
1592 {
1593 Mutexed<State>::Locked state(mState);
1594 if (state->get() == RELEASING) {
1595 state.unlock();
1596 // We're already stopped or release is in progress.
1597 mCallback->onStopCompleted();
1598 state.lock();
1599 return;
1600 } else if (state->get() != STOPPING) {
1601 state.unlock();
1602 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1603 state.lock();
1604 return;
1605 }
1606 comp = state->comp;
1607 }
1608 status_t err = comp->stop();
1609 if (err != C2_OK) {
1610 // TODO: convert err into status_t
1611 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1612 }
1613
1614 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001615 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1616 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001617 if (config->mInputSurface) {
1618 config->mInputSurface->disconnect();
1619 config->mInputSurface = nullptr;
1620 }
1621 }
1622 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001623 Mutexed<State>::Locked state(mState);
1624 if (state->get() == STOPPING) {
1625 state->set(ALLOCATED);
1626 }
1627 }
1628 mCallback->onStopCompleted();
1629}
1630
1631void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001632 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001633 {
1634 Mutexed<State>::Locked state(mState);
1635 if (state->get() == RELEASED || state->get() == RELEASING) {
1636 // We're already released or doing it right now.
1637 if (sendCallback) {
1638 state.unlock();
1639 mCallback->onReleaseCompleted();
1640 state.lock();
1641 }
1642 return;
1643 }
1644 if (state->get() == ALLOCATING) {
1645 state->set(RELEASING);
1646 // With the altered state allocate() would fail and clean up.
1647 if (sendCallback) {
1648 state.unlock();
1649 mCallback->onReleaseCompleted();
1650 state.lock();
1651 }
1652 return;
1653 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001654 if (state->get() == STARTING
1655 || state->get() == RUNNING
1656 || state->get() == STOPPING) {
1657 // Input surface may have been started, so clean up is needed.
1658 clearInputSurfaceIfNeeded = true;
1659 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001660 state->set(RELEASING);
1661 }
1662
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001663 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001664 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1665 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001666 if (config->mInputSurface) {
1667 config->mInputSurface->disconnect();
1668 config->mInputSurface = nullptr;
1669 }
1670 }
1671
Wonsik Kim936a89c2020-05-08 16:07:50 -07001672 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001673 // thiz holds strong ref to this while the thread is running.
1674 sp<CCodec> thiz(this);
1675 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1676}
1677
1678void CCodec::release(bool sendCallback) {
1679 std::shared_ptr<Codec2Client::Component> comp;
1680 {
1681 Mutexed<State>::Locked state(mState);
1682 if (state->get() == RELEASED) {
1683 if (sendCallback) {
1684 state.unlock();
1685 mCallback->onReleaseCompleted();
1686 state.lock();
1687 }
1688 return;
1689 }
1690 comp = state->comp;
1691 }
1692 comp->release();
1693
1694 {
1695 Mutexed<State>::Locked state(mState);
1696 state->set(RELEASED);
1697 state->comp.reset();
1698 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001699 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001700 if (sendCallback) {
1701 mCallback->onReleaseCompleted();
1702 }
1703}
1704
1705status_t CCodec::setSurface(const sp<Surface> &surface) {
1706 return mChannel->setSurface(surface);
1707}
1708
1709void CCodec::signalFlush() {
1710 status_t err = [this] {
1711 Mutexed<State>::Locked state(mState);
1712 if (state->get() == FLUSHED) {
1713 return ALREADY_EXISTS;
1714 }
1715 if (state->get() != RUNNING) {
1716 return UNKNOWN_ERROR;
1717 }
1718 state->set(FLUSHING);
1719 return OK;
1720 }();
1721 switch (err) {
1722 case ALREADY_EXISTS:
1723 mCallback->onFlushCompleted();
1724 return;
1725 case OK:
1726 break;
1727 default:
1728 mCallback->onError(err, ACTION_CODE_FATAL);
1729 return;
1730 }
1731
1732 mChannel->stop();
1733 (new AMessage(kWhatFlush, this))->post();
1734}
1735
1736void CCodec::flush() {
1737 std::shared_ptr<Codec2Client::Component> comp;
1738 auto checkFlushing = [this, &comp] {
1739 Mutexed<State>::Locked state(mState);
1740 if (state->get() != FLUSHING) {
1741 return UNKNOWN_ERROR;
1742 }
1743 comp = state->comp;
1744 return OK;
1745 };
1746 if (tryAndReportOnError(checkFlushing) != OK) {
1747 return;
1748 }
1749
1750 std::list<std::unique_ptr<C2Work>> flushedWork;
1751 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1752 {
1753 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1754 flushedWork.splice(flushedWork.end(), *queue);
1755 }
1756 if (err != C2_OK) {
1757 // TODO: convert err into status_t
1758 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1759 }
1760
1761 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001762
1763 {
1764 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001765 if (state->get() == FLUSHING) {
1766 state->set(FLUSHED);
1767 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001768 }
1769 mCallback->onFlushCompleted();
1770}
1771
1772void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001773 std::shared_ptr<Codec2Client::Component> comp;
1774 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001775 Mutexed<State>::Locked state(mState);
1776 if (state->get() != FLUSHED) {
1777 return UNKNOWN_ERROR;
1778 }
1779 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001780 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001781 return OK;
1782 };
1783 if (tryAndReportOnError(setResuming) != OK) {
1784 return;
1785 }
1786
Wonsik Kime75a5da2020-02-14 17:29:03 -08001787 {
1788 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1789 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001790 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001791 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001792 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001793 }
1794
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001795 (void)mChannel->start(nullptr, nullptr, [&]{
1796 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1797 const std::unique_ptr<Config> &config = *configLocked;
1798 return config->mBuffersBoundToCodec;
1799 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001800
1801 {
1802 Mutexed<State>::Locked state(mState);
1803 if (state->get() != RESUMING) {
1804 state.unlock();
1805 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1806 state.lock();
1807 return;
1808 }
1809 state->set(RUNNING);
1810 }
1811
1812 (void)mChannel->requestInitialInputBuffers();
1813}
1814
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001815void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001816 std::shared_ptr<Codec2Client::Component> comp;
1817 auto checkState = [this, &comp] {
1818 Mutexed<State>::Locked state(mState);
1819 if (state->get() == RELEASED) {
1820 return INVALID_OPERATION;
1821 }
1822 comp = state->comp;
1823 return OK;
1824 };
1825 if (tryAndReportOnError(checkState) != OK) {
1826 return;
1827 }
1828
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001829 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1830 // the behavior here.
1831 sp<AMessage> params = msg;
1832 int32_t bitrate;
1833 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1834 params = msg->dup();
1835 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1836 }
1837
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001838 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1839 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001840
1841 /**
1842 * Handle input surface parameters
1843 */
1844 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001845 && (config->mDomain & Config::IS_ENCODER)
1846 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001847 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001848
1849 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1850 config->mISConfig->mStopped = false;
1851 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1852 config->mISConfig->mStopped = true;
1853 }
1854
1855 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001856 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001857 config->mISConfig->mSuspended = value;
1858 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001859 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001860 }
1861
1862 (void)config->mInputSurface->configure(*config->mISConfig);
1863 if (config->mISConfig->mStopped) {
1864 config->mInputFormat->setInt64(
1865 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1866 }
1867 }
1868
1869 std::vector<std::unique_ptr<C2Param>> configUpdate;
1870 (void)config->getConfigUpdateFromSdkParams(
1871 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1872 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1873 // Parameter synchronization is not defined when using input surface. For now, route
1874 // these directly to the component.
1875 if (config->mInputSurface == nullptr
1876 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1877 || comp->getName().find("c2.android.") == 0)) {
1878 mChannel->setParameters(configUpdate);
1879 } else {
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001880 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001881 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001882 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001883 }
1884}
1885
1886void CCodec::signalEndOfInputStream() {
1887 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1888}
1889
1890void CCodec::signalRequestIDRFrame() {
1891 std::shared_ptr<Codec2Client::Component> comp;
1892 {
1893 Mutexed<State>::Locked state(mState);
1894 if (state->get() == RELEASED) {
1895 ALOGD("no IDR request sent since component is released");
1896 return;
1897 }
1898 comp = state->comp;
1899 }
1900 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001901 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1902 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001903 std::vector<std::unique_ptr<C2Param>> params;
1904 params.push_back(
1905 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1906 config->setParameters(comp, params, C2_MAY_BLOCK);
1907}
1908
Wonsik Kimab34ed62019-01-31 15:28:46 -08001909void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001910 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001911 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1912 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001913 }
1914 (new AMessage(kWhatWorkDone, this))->post();
1915}
1916
Wonsik Kimab34ed62019-01-31 15:28:46 -08001917void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1918 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001919 if (arrayIndex == 0) {
1920 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001921 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1922 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001923 if (config->mInputSurface) {
1924 config->mInputSurface->onInputBufferDone(frameIndex);
1925 }
1926 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001927}
1928
1929void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1930 TimePoint now = std::chrono::steady_clock::now();
1931 CCodecWatchdog::getInstance()->watch(this);
1932 switch (msg->what()) {
1933 case kWhatAllocate: {
1934 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001935 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001936 sp<RefBase> obj;
1937 CHECK(msg->findObject("codecInfo", &obj));
1938 allocate((MediaCodecInfo *)obj.get());
1939 break;
1940 }
1941 case kWhatConfigure: {
1942 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001943 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001944 sp<AMessage> format;
1945 CHECK(msg->findMessage("format", &format));
1946 configure(format);
1947 break;
1948 }
1949 case kWhatStart: {
1950 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001951 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001952 start();
1953 break;
1954 }
1955 case kWhatStop: {
1956 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001957 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001958 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001959 break;
1960 }
1961 case kWhatFlush: {
1962 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001963 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001964 flush();
1965 break;
1966 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001967 case kWhatRelease: {
1968 mChannel->release();
1969 mClient.reset();
1970 mClientListener.reset();
1971 break;
1972 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001973 case kWhatCreateInputSurface: {
1974 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001975 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001976 createInputSurface();
1977 break;
1978 }
1979 case kWhatSetInputSurface: {
1980 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001981 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001982 sp<RefBase> obj;
1983 CHECK(msg->findObject("surface", &obj));
1984 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1985 setInputSurface(surface);
1986 break;
1987 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001988 case kWhatWorkDone: {
1989 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001990 bool shouldPost = false;
1991 {
1992 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1993 if (queue->empty()) {
1994 break;
1995 }
1996 work.swap(queue->front());
1997 queue->pop_front();
1998 shouldPost = !queue->empty();
1999 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002000 if (shouldPost) {
2001 (new AMessage(kWhatWorkDone, this))->post();
2002 }
2003
Pawin Vongmasa36653902018-11-15 00:10:25 -08002004 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002005 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2006 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002007 Config::Watcher<C2StreamInitDataInfo::output> initData =
2008 config->watch<C2StreamInitDataInfo::output>();
2009 if (!work->worklets.empty()
2010 && (work->worklets.front()->output.flags
2011 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
2012
2013 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002014 std::vector<std::unique_ptr<C2Param>> updates;
2015 for (const std::unique_ptr<C2Param> &param
2016 : work->worklets.front()->output.configUpdate) {
2017 updates.push_back(C2Param::Copy(*param));
2018 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002019 unsigned stream = 0;
2020 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2021 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2022 // move all info into output-stream #0 domain
2023 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
2024 }
George Burgess IVc813a592020-02-22 22:54:44 -08002025
2026 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2027 // for now only do the first block
2028 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002029 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2030 // block.crop().left, block.crop().top,
2031 // block.crop().width, block.crop().height,
2032 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08002033 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08002034 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
2035 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07002036 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002037 }
2038 ++stream;
2039 }
2040
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002041 sp<AMessage> outputFormat = config->mOutputFormat;
2042 config->updateConfiguration(updates, config->mOutputDomain);
2043 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002044
2045 // copy standard infos to graphic buffers if not already present (otherwise, we
2046 // may overwrite the actual intermediate value with a final value)
2047 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07002048 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002049 C2StreamRotationInfo::output::PARAM_TYPE,
2050 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2051 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2052 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08002053 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08002054 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2055 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2056 };
2057 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2058 if (buf->data().graphicBlocks().size()) {
2059 for (C2Param::Index ix : stdGfxInfos) {
2060 if (!buf->hasInfo(ix)) {
2061 const C2Param *param =
2062 config->getConfigParameterValue(ix.withStream(stream));
2063 if (param) {
2064 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2065 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2066 }
2067 }
2068 }
2069 }
2070 ++stream;
2071 }
2072 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002073 if (config->mInputSurface) {
2074 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2075 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002076 mChannel->onWorkDone(
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002077 std::move(work), config->mOutputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002078 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002079 break;
2080 }
2081 case kWhatWatch: {
2082 // watch message already posted; no-op.
2083 break;
2084 }
2085 default: {
2086 ALOGE("unrecognized message");
2087 break;
2088 }
2089 }
2090 setDeadline(TimePoint::max(), 0ms, "none");
2091}
2092
2093void CCodec::setDeadline(
2094 const TimePoint &now,
2095 const std::chrono::milliseconds &timeout,
2096 const char *name) {
2097 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2098 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2099 deadline->set(now + (timeout * mult), name);
2100}
2101
2102void CCodec::initiateReleaseIfStuck() {
2103 std::string name;
2104 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002105 {
2106 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002107 if (deadline->get() < std::chrono::steady_clock::now()) {
2108 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002109 }
2110 if (deadline->get() != TimePoint::max()) {
2111 pendingDeadline = true;
2112 }
2113 }
2114 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002115 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2116 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2117 if (elapsed >= kWorkDurationThreshold) {
2118 name = "queue";
2119 }
2120 if (elapsed > 0s) {
2121 pendingDeadline = true;
2122 }
2123 }
2124 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002125 // We're not stuck.
2126 if (pendingDeadline) {
2127 // If we are not stuck yet but still has deadline coming up,
2128 // post watch message to check back later.
2129 (new AMessage(kWhatWatch, this))->post();
2130 }
2131 return;
2132 }
2133
2134 ALOGW("previous call to %s exceeded timeout", name.c_str());
2135 initiateRelease(false);
2136 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2137}
2138
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002139// static
2140PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002141 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002142 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002143 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002144 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2145 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002146 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002147 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2148 sp<IGraphicBufferProducer> gbp;
2149 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2150 status_t err = gbs->initCheck();
2151 if (err != OK) {
2152 ALOGE("Failed to create persistent input surface: error %d", err);
2153 return nullptr;
2154 }
2155 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002156 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002157 } else {
2158 return nullptr;
2159 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002160 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002161 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002162 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002163 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002164 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002165}
2166
Wonsik Kimffb889a2020-05-28 11:32:25 -07002167class IntfCache {
2168public:
2169 IntfCache() = default;
2170
2171 status_t init(const std::string &name) {
2172 std::shared_ptr<Codec2Client::Interface> intf{
2173 Codec2Client::CreateInterfaceByName(name.c_str())};
2174 if (!intf) {
2175 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2176 mInitStatus = NO_INIT;
2177 return NO_INIT;
2178 }
2179 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2180 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2181 C2ParamField{&sUsage, &sUsage.value}));
2182 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2183 if (err != C2_OK) {
2184 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2185 name.c_str(), err);
2186 mFields[0].status = err;
2187 }
2188 std::vector<std::unique_ptr<C2Param>> params;
2189 err = intf->query(
2190 {&mApiFeatures},
2191 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2192 C2_MAY_BLOCK,
2193 &params);
2194 if (err != C2_OK && err != C2_BAD_INDEX) {
2195 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2196 name.c_str(), err);
2197 }
2198 while (!params.empty()) {
2199 C2Param *param = params.back().release();
2200 params.pop_back();
2201 if (!param) {
2202 continue;
2203 }
2204 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2205 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002206 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002207 }
2208 }
2209 mInitStatus = OK;
2210 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002211 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002212
2213 status_t initCheck() const { return mInitStatus; }
2214
2215 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2216 CHECK_EQ(1u, mFields.size());
2217 return mFields[0];
2218 }
2219
2220 const C2ApiFeaturesSetting &getApiFeatures() const {
2221 return mApiFeatures;
2222 }
2223
2224 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2225 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2226 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2227 C2PortAllocatorsTuning::input::AllocUnique(0);
2228 param->invalidate();
2229 return param;
2230 }();
2231 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2232 }
2233
2234private:
2235 status_t mInitStatus{NO_INIT};
2236
2237 std::vector<C2FieldSupportedValuesQuery> mFields;
2238 C2ApiFeaturesSetting mApiFeatures;
2239 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2240};
2241
2242static const IntfCache &GetIntfCache(const std::string &name) {
2243 static IntfCache sNullIntfCache;
2244 static std::mutex sMutex;
2245 static std::map<std::string, IntfCache> sCache;
2246 std::unique_lock<std::mutex> lock{sMutex};
2247 auto it = sCache.find(name);
2248 if (it == sCache.end()) {
2249 lock.unlock();
2250 IntfCache intfCache;
2251 status_t err = intfCache.init(name);
2252 if (err != OK) {
2253 return sNullIntfCache;
2254 }
2255 lock.lock();
2256 it = sCache.insert({name, std::move(intfCache)}).first;
2257 }
2258 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002259}
2260
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002261static status_t GetCommonAllocatorIds(
2262 const std::vector<std::string> &names,
2263 C2Allocator::type_t type,
2264 std::set<C2Allocator::id_t> *ids) {
2265 int poolMask = GetCodec2PoolMask();
2266 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2267 C2Allocator::id_t defaultAllocatorId =
2268 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2269
2270 ids->clear();
2271 if (names.empty()) {
2272 return OK;
2273 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002274 bool firstIteration = true;
2275 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002276 const IntfCache &intfCache = GetIntfCache(name);
2277 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002278 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002279 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002280 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002281 if (firstIteration) {
2282 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002283 if (allocators && allocators.flexCount() > 0) {
2284 ids->insert(allocators.m.values,
2285 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002286 }
2287 if (ids->empty()) {
2288 // The component does not advertise allocators. Use default.
2289 ids->insert(defaultAllocatorId);
2290 }
2291 continue;
2292 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002293 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002294 if (allocators && allocators.flexCount() > 0) {
2295 filtered = true;
2296 for (auto it = ids->begin(); it != ids->end(); ) {
2297 bool found = false;
2298 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2299 if (allocators.m.values[j] == *it) {
2300 found = true;
2301 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002302 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002303 }
2304 if (found) {
2305 ++it;
2306 } else {
2307 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002308 }
2309 }
2310 }
2311 if (!filtered) {
2312 // The component does not advertise supported allocators. Use default.
2313 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2314 if (ids->size() != (containsDefault ? 1 : 0)) {
2315 ids->clear();
2316 if (containsDefault) {
2317 ids->insert(defaultAllocatorId);
2318 }
2319 }
2320 }
2321 }
2322 // Finally, filter with pool masks
2323 for (auto it = ids->begin(); it != ids->end(); ) {
2324 if ((poolMask >> *it) & 1) {
2325 ++it;
2326 } else {
2327 it = ids->erase(it);
2328 }
2329 }
2330 return OK;
2331}
2332
2333static status_t CalculateMinMaxUsage(
2334 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2335 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2336 *minUsage = 0;
2337 *maxUsage = ~0ull;
2338 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002339 const IntfCache &intfCache = GetIntfCache(name);
2340 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002341 continue;
2342 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002343 const C2FieldSupportedValuesQuery &usageSupportedValues =
2344 intfCache.getUsageSupportedValues();
2345 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002346 continue;
2347 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002348 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002349 if (supported.type != C2FieldSupportedValues::FLAGS) {
2350 continue;
2351 }
2352 if (supported.values.empty()) {
2353 *maxUsage = 0;
2354 continue;
2355 }
2356 *minUsage |= supported.values[0].u64;
2357 int64_t currentMaxUsage = 0;
2358 for (const C2Value::Primitive &flags : supported.values) {
2359 currentMaxUsage |= flags.u64;
2360 }
2361 *maxUsage &= currentMaxUsage;
2362 }
2363 return OK;
2364}
2365
2366// static
2367status_t CCodec::CanFetchLinearBlock(
2368 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002369 for (const std::string &name : names) {
2370 const IntfCache &intfCache = GetIntfCache(name);
2371 if (intfCache.initCheck() != OK) {
2372 continue;
2373 }
2374 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2375 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2376 *isCompatible = false;
2377 return OK;
2378 }
2379 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002380 uint64_t minUsage = usage.expected;
2381 uint64_t maxUsage = ~0ull;
2382 std::set<C2Allocator::id_t> allocators;
2383 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2384 if (allocators.empty()) {
2385 *isCompatible = false;
2386 return OK;
2387 }
2388 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2389 *isCompatible = ((maxUsage & minUsage) == minUsage);
2390 return OK;
2391}
2392
2393static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2394 static std::mutex sMutex{};
2395 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2396 std::unique_lock<std::mutex> lock{sMutex};
2397 std::shared_ptr<C2BlockPool> pool;
2398 auto it = sPools.find(allocId);
2399 if (it == sPools.end()) {
2400 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2401 if (err == OK) {
2402 sPools.emplace(allocId, pool);
2403 } else {
2404 pool.reset();
2405 }
2406 } else {
2407 pool = it->second;
2408 }
2409 return pool;
2410}
2411
2412// static
2413std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2414 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
2415 uint64_t minUsage = usage.expected;
2416 uint64_t maxUsage = ~0ull;
2417 std::set<C2Allocator::id_t> allocators;
2418 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2419 if (allocators.empty()) {
2420 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2421 }
2422 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2423 if ((maxUsage & minUsage) != minUsage) {
2424 allocators.clear();
2425 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2426 }
2427 std::shared_ptr<C2LinearBlock> block;
2428 for (C2Allocator::id_t allocId : allocators) {
2429 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2430 if (!pool) {
2431 continue;
2432 }
2433 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2434 if (err != C2_OK || !block) {
2435 block.reset();
2436 continue;
2437 }
2438 break;
2439 }
2440 return block;
2441}
2442
2443// static
2444status_t CCodec::CanFetchGraphicBlock(
2445 const std::vector<std::string> &names, bool *isCompatible) {
2446 uint64_t minUsage = 0;
2447 uint64_t maxUsage = ~0ull;
2448 std::set<C2Allocator::id_t> allocators;
2449 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2450 if (allocators.empty()) {
2451 *isCompatible = false;
2452 return OK;
2453 }
2454 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2455 *isCompatible = ((maxUsage & minUsage) == minUsage);
2456 return OK;
2457}
2458
2459// static
2460std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2461 int32_t width,
2462 int32_t height,
2463 int32_t format,
2464 uint64_t usage,
2465 const std::vector<std::string> &names) {
2466 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2467 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2468 ALOGD("Unrecognized pixel format: %d", format);
2469 return nullptr;
2470 }
2471 uint64_t minUsage = 0;
2472 uint64_t maxUsage = ~0ull;
2473 std::set<C2Allocator::id_t> allocators;
2474 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2475 if (allocators.empty()) {
2476 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2477 }
2478 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2479 minUsage |= usage;
2480 if ((maxUsage & minUsage) != minUsage) {
2481 allocators.clear();
2482 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2483 }
2484 std::shared_ptr<C2GraphicBlock> block;
2485 for (C2Allocator::id_t allocId : allocators) {
2486 std::shared_ptr<C2BlockPool> pool;
2487 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2488 if (err != C2_OK || !pool) {
2489 continue;
2490 }
2491 err = pool->fetchGraphicBlock(
2492 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2493 if (err != C2_OK || !block) {
2494 block.reset();
2495 continue;
2496 }
2497 break;
2498 }
2499 return block;
2500}
2501
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002502} // namespace android
2503