blob: 729ba141395b2880c10860919bc085d20a82c7ad [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
555 // Note: for now we do not propagate the error code to MediaCodec as we would need
556 // to translate to a MediaCodec error.
557 sp<CCodec> codec(mCodec.promote());
558 if (!codec || !codec->mCallback) {
559 return;
560 }
561 codec->mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800562 }
563
564 virtual void onDeath(
565 const std::weak_ptr<Codec2Client::Component>& component) override {
566 { // Log the death of the component.
567 std::shared_ptr<Codec2Client::Component> comp = component.lock();
568 if (!comp) {
569 ALOGE("Codec2 component died.");
570 } else {
571 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
572 }
573 }
574
575 // Report to MediaCodec.
576 sp<CCodec> codec(mCodec.promote());
577 if (!codec || !codec->mCallback) {
578 return;
579 }
580 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
581 }
582
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800583 virtual void onFrameRendered(uint64_t bufferQueueId,
584 int32_t slotId,
585 int64_t timestampNs) override {
586 // TODO: implement
587 (void)bufferQueueId;
588 (void)slotId;
589 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800590 }
591
592 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800593 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800594 sp<CCodec> codec(mCodec.promote());
595 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800596 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800597 }
598 }
599
600private:
601 wp<CCodec> mCodec;
602};
603
604// CCodecCallbackImpl
605
606class CCodecCallbackImpl : public CCodecCallback {
607public:
608 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
609 ~CCodecCallbackImpl() override = default;
610
611 void onError(status_t err, enum ActionCode actionCode) override {
612 mCodec->mCallback->onError(err, actionCode);
613 }
614
615 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
616 mCodec->mCallback->onOutputFramesRendered(
617 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
618 }
619
Pawin Vongmasa36653902018-11-15 00:10:25 -0800620 void onOutputBuffersChanged() override {
621 mCodec->mCallback->onOutputBuffersChanged();
622 }
623
624private:
625 CCodec *mCodec;
626};
627
628// CCodec
629
630CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700631 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
632 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800633}
634
635CCodec::~CCodec() {
636}
637
638std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
639 return mChannel;
640}
641
642status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
643 status_t err = job();
644 if (err != C2_OK) {
645 mCallback->onError(err, ACTION_CODE_FATAL);
646 }
647 return err;
648}
649
650void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
651 auto setAllocating = [this] {
652 Mutexed<State>::Locked state(mState);
653 if (state->get() != RELEASED) {
654 return INVALID_OPERATION;
655 }
656 state->set(ALLOCATING);
657 return OK;
658 };
659 if (tryAndReportOnError(setAllocating) != OK) {
660 return;
661 }
662
663 sp<RefBase> codecInfo;
664 CHECK(msg->findObject("codecInfo", &codecInfo));
665 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
666
667 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
668 allocMsg->setObject("codecInfo", codecInfo);
669 allocMsg->post();
670}
671
672void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
673 if (codecInfo == nullptr) {
674 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
675 return;
676 }
677 ALOGD("allocate(%s)", codecInfo->getCodecName());
678 mClientListener.reset(new ClientListener(this));
679
680 AString componentName = codecInfo->getCodecName();
681 std::shared_ptr<Codec2Client> client;
682
683 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700684 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800685 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800686 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800687 SetPreferredCodec2ComponentStore(
688 std::make_shared<Codec2ClientInterfaceWrapper>(client));
689 }
690
691 std::shared_ptr<Codec2Client::Component> comp =
692 Codec2Client::CreateComponentByName(
693 componentName.c_str(),
694 mClientListener,
695 &client);
696 if (!comp) {
697 ALOGE("Failed Create component: %s", componentName.c_str());
698 Mutexed<State>::Locked state(mState);
699 state->set(RELEASED);
700 state.unlock();
701 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
702 state.lock();
703 return;
704 }
705 ALOGI("Created component [%s]", componentName.c_str());
706 mChannel->setComponent(comp);
707 auto setAllocated = [this, comp, client] {
708 Mutexed<State>::Locked state(mState);
709 if (state->get() != ALLOCATING) {
710 state->set(RELEASED);
711 return UNKNOWN_ERROR;
712 }
713 state->set(ALLOCATED);
714 state->comp = comp;
715 mClient = client;
716 return OK;
717 };
718 if (tryAndReportOnError(setAllocated) != OK) {
719 return;
720 }
721
722 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700723 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
724 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800725 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800726 if (err != OK) {
727 ALOGW("Failed to initialize configuration support");
728 // TODO: report error once we complete implementation.
729 }
730 config->queryConfiguration(comp);
731
732 mCallback->onComponentAllocated(componentName.c_str());
733}
734
735void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
736 auto checkAllocated = [this] {
737 Mutexed<State>::Locked state(mState);
738 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
739 };
740 if (tryAndReportOnError(checkAllocated) != OK) {
741 return;
742 }
743
744 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
745 msg->setMessage("format", format);
746 msg->post();
747}
748
749void CCodec::configure(const sp<AMessage> &msg) {
750 std::shared_ptr<Codec2Client::Component> comp;
751 auto checkAllocated = [this, &comp] {
752 Mutexed<State>::Locked state(mState);
753 if (state->get() != ALLOCATED) {
754 state->set(RELEASED);
755 return UNKNOWN_ERROR;
756 }
757 comp = state->comp;
758 return OK;
759 };
760 if (tryAndReportOnError(checkAllocated) != OK) {
761 return;
762 }
763
764 auto doConfig = [msg, comp, this]() -> status_t {
765 AString mime;
766 if (!msg->findString("mime", &mime)) {
767 return BAD_VALUE;
768 }
769
770 int32_t encoder;
771 if (!msg->findInt32("encoder", &encoder)) {
772 encoder = false;
773 }
774
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800775 int32_t flags;
776 if (!msg->findInt32("flags", &flags)) {
777 return BAD_VALUE;
778 }
779
Pawin Vongmasa36653902018-11-15 00:10:25 -0800780 // TODO: read from intf()
781 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
782 return UNKNOWN_ERROR;
783 }
784
785 int32_t storeMeta;
786 if (encoder
787 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
788 && storeMeta != kMetadataBufferTypeInvalid) {
789 if (storeMeta != kMetadataBufferTypeANWBuffer) {
790 ALOGD("Only ANW buffers are supported for legacy metadata mode");
791 return BAD_VALUE;
792 }
793 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
794 }
795
796 sp<RefBase> obj;
797 sp<Surface> surface;
798 if (msg->findObject("native-window", &obj)) {
799 surface = static_cast<Surface *>(obj.get());
800 setSurface(surface);
801 }
802
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700803 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
804 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800805 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800806 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
807 ALOGD("[%s] buffers are %sbound to CCodec for this session",
808 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800809
Wonsik Kim1114eea2019-02-25 14:35:24 -0800810 // Enforce required parameters
811 int32_t i32;
812 float flt;
813 if (config->mDomain & Config::IS_AUDIO) {
814 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
815 ALOGD("sample rate is missing, which is required for audio components.");
816 return BAD_VALUE;
817 }
818 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
819 ALOGD("channel count is missing, which is required for audio components.");
820 return BAD_VALUE;
821 }
822 if ((config->mDomain & Config::IS_ENCODER)
823 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
824 && !msg->findInt32(KEY_BIT_RATE, &i32)
825 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
826 ALOGD("bitrate is missing, which is required for audio encoders.");
827 return BAD_VALUE;
828 }
829 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800830 int32_t width = 0;
831 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800832 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800833 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800834 ALOGD("width is missing, which is required for image/video components.");
835 return BAD_VALUE;
836 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800837 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800838 ALOGD("height is missing, which is required for image/video components.");
839 return BAD_VALUE;
840 }
841 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700842 int32_t mode = BITRATE_MODE_VBR;
843 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700844 if (!msg->findInt32(KEY_QUALITY, &i32)) {
845 ALOGD("quality is missing, which is required for video encoders in CQ.");
846 return BAD_VALUE;
847 }
848 } else {
849 if (!msg->findInt32(KEY_BIT_RATE, &i32)
850 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
851 ALOGD("bitrate is missing, which is required for video encoders.");
852 return BAD_VALUE;
853 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800854 }
855 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
856 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
857 ALOGD("I frame interval is missing, which is required for video encoders.");
858 return BAD_VALUE;
859 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700860 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
861 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
862 ALOGD("frame rate is missing, which is required for video encoders.");
863 return BAD_VALUE;
864 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800865 }
866 }
867
Pawin Vongmasa36653902018-11-15 00:10:25 -0800868 /*
869 * Handle input surface configuration
870 */
871 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
872 && (config->mDomain & Config::IS_ENCODER)) {
873 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
874 {
875 config->mISConfig->mMinFps = 0;
876 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800877 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800878 config->mISConfig->mMinFps = 1e6 / value;
879 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700880 if (!msg->findFloat(
881 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
882 config->mISConfig->mMaxFps = -1;
883 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800884 config->mISConfig->mMinAdjustedFps = 0;
885 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800886 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800887 if (value < 0 && value >= INT32_MIN) {
888 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700889 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800890 } else if (value > 0 && value <= INT32_MAX) {
891 config->mISConfig->mMinAdjustedFps = 1e6 / value;
892 }
893 }
894 }
895
896 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700897 bool captureFpsFound = false;
898 double timeLapseFps;
899 float captureRate;
900 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
901 config->mISConfig->mCaptureFps = timeLapseFps;
902 captureFpsFound = true;
903 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
904 config->mISConfig->mCaptureFps = captureRate;
905 captureFpsFound = true;
906 }
907 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800908 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
909 }
910 }
911
912 {
913 config->mISConfig->mSuspended = false;
914 config->mISConfig->mSuspendAtUs = -1;
915 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800916 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800917 config->mISConfig->mSuspended = true;
918 }
919 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700920 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800921 }
922
923 /*
924 * Handle desired color format.
925 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700926 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800927 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700928 int32_t format = 0;
929 // Query vendor format for Flexible YUV
930 std::vector<std::unique_ptr<C2Param>> heapParams;
931 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
932 if (mClient->query(
933 {},
934 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
935 C2_MAY_BLOCK,
936 &heapParams) == C2_OK
937 && heapParams.size() == 1u) {
938 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
939 heapParams[0].get());
940 } else {
941 pixelFormatInfo = nullptr;
942 }
943 std::optional<uint32_t> flexPixelFormat{};
944 std::optional<uint32_t> flexPlanarPixelFormat{};
945 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
946 if (pixelFormatInfo && *pixelFormatInfo) {
947 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
948 const C2FlexiblePixelFormatDescriptorStruct &desc =
949 pixelFormatInfo->m.values[i];
950 if (desc.bitDepth != 8
951 || desc.subsampling != C2Color::YUV_420
952 // TODO(b/180076105): some device report wrong layout
953 // || desc.layout == C2Color::INTERLEAVED_PACKED
954 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
955 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
956 continue;
957 }
958 if (!flexPixelFormat) {
959 flexPixelFormat = desc.pixelFormat;
960 }
961 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
962 flexPlanarPixelFormat = desc.pixelFormat;
963 }
964 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
965 flexSemiPlanarPixelFormat = desc.pixelFormat;
966 }
967 }
968 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800969 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700970 // Also handle default color format (encoders require color format, so this is only
971 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -0800972 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700973 if (surface == nullptr) {
974 format = flexPixelFormat.value_or(COLOR_FormatYUV420Flexible);
975 } else {
976 format = COLOR_FormatSurface;
977 }
978 defaultColorFormat = format;
979 }
980 } else {
981 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
982 switch (format) {
983 case COLOR_FormatYUV420Flexible:
984 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
985 break;
986 case COLOR_FormatYUV420Planar:
987 case COLOR_FormatYUV420PackedPlanar:
988 format = flexPlanarPixelFormat.value_or(
989 flexPixelFormat.value_or(format));
990 break;
991 case COLOR_FormatYUV420SemiPlanar:
992 case COLOR_FormatYUV420PackedSemiPlanar:
993 format = flexSemiPlanarPixelFormat.value_or(
994 flexPixelFormat.value_or(format));
995 break;
996 default:
997 // No-op
998 break;
999 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001000 }
1001 }
1002
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001003 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001004 msg->setInt32("android._color-format", format);
1005 }
1006 }
1007
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001008 int32_t subscribeToAllVendorParams;
1009 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1010 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1011 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1012 }
1013 }
1014
Pawin Vongmasa36653902018-11-15 00:10:25 -08001015 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001016 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1017 // the behavior here.
1018 sp<AMessage> sdkParams = msg;
1019 int32_t videoBitrate;
1020 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1021 sdkParams = msg->dup();
1022 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1023 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001024 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001025 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001026 if (err != OK) {
1027 ALOGW("failed to convert configuration to c2 params");
1028 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001029
1030 int32_t maxBframes = 0;
1031 if ((config->mDomain & Config::IS_ENCODER)
1032 && (config->mDomain & Config::IS_VIDEO)
1033 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1034 && maxBframes > 0) {
1035 std::unique_ptr<C2StreamGopTuning::output> gop =
1036 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1037 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1038 gop->m.values[1] = {
1039 C2Config::picture_type_t(P_FRAME | B_FRAME),
1040 uint32_t(maxBframes)
1041 };
1042 configUpdate.push_back(std::move(gop));
1043 }
1044
Pawin Vongmasa36653902018-11-15 00:10:25 -08001045 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1046 if (err != OK) {
1047 ALOGW("failed to configure c2 params");
1048 return err;
1049 }
1050
1051 std::vector<std::unique_ptr<C2Param>> params;
1052 C2StreamUsageTuning::input usage(0u, 0u);
1053 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001054 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001055
Wonsik Kim58d83332021-02-07 22:19:56 -08001056 C2Param::Index colorAspectsRequestIndex =
1057 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001058 std::initializer_list<C2Param::Index> indices {
Wonsik Kim58d83332021-02-07 22:19:56 -08001059 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001060 };
1061 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001062 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001063 indices,
1064 C2_DONT_BLOCK,
1065 &params);
1066 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1067 ALOGE("Failed to query component interface: %d", c2err);
1068 return UNKNOWN_ERROR;
1069 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001070 if (usage) {
1071 if (usage.value & C2MemoryUsage::CPU_READ) {
1072 config->mInputFormat->setInt32("using-sw-read-often", true);
1073 }
1074 if (config->mISConfig) {
1075 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1076 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1077 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001078 }
1079
1080 // NOTE: we don't blindly use client specified input size if specified as clients
1081 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1082 // client specified size is only used to ask for bigger buffers than component suggested
1083 // size.
1084 int32_t clientInputSize = 0;
1085 bool clientSpecifiedInputSize =
1086 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1087 // TEMP: enforce minimum buffer size of 1MB for video decoders
1088 // and 16K / 4K for audio encoders/decoders
1089 if (maxInputSize.value == 0) {
1090 if (config->mDomain & Config::IS_AUDIO) {
1091 maxInputSize.value = encoder ? 16384 : 4096;
1092 } else if (!encoder) {
1093 maxInputSize.value = 1048576u;
1094 }
1095 }
1096
1097 // verify that CSD fits into this size (if defined)
1098 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1099 sp<ABuffer> csd;
1100 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1101 if (csd && csd->size() > maxInputSize.value) {
1102 maxInputSize.value = csd->size();
1103 }
1104 }
1105 }
1106
1107 // TODO: do this based on component requiring linear allocator for input
1108 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1109 if (clientSpecifiedInputSize) {
1110 // Warn that we're overriding client's max input size if necessary.
1111 if ((uint32_t)clientInputSize < maxInputSize.value) {
1112 ALOGD("client requested max input size %d, which is smaller than "
1113 "what component recommended (%u); overriding with component "
1114 "recommendation.", clientInputSize, maxInputSize.value);
1115 ALOGW("This behavior is subject to change. It is recommended that "
1116 "app developers double check whether the requested "
1117 "max input size is in reasonable range.");
1118 } else {
1119 maxInputSize.value = clientInputSize;
1120 }
1121 }
1122 // Pass max input size on input format to the buffer channel (if supplied by the
1123 // component or by a default)
1124 if (maxInputSize.value) {
1125 config->mInputFormat->setInt32(
1126 KEY_MAX_INPUT_SIZE,
1127 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1128 }
1129 }
1130
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001131 int32_t clientPrepend;
1132 if ((config->mDomain & Config::IS_VIDEO)
1133 && (config->mDomain & Config::IS_ENCODER)
1134 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1135 && clientPrepend
1136 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1137 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1138 return BAD_VALUE;
1139 }
1140
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001141 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001142 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1143 // propagate HDR static info to output format for both encoders and decoders
1144 // if component supports this info, we will update from component, but only the raw port,
1145 // so don't propagate if component already filled it in.
1146 sp<ABuffer> hdrInfo;
1147 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1148 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1149 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1150 }
1151
1152 // Set desired color format from configuration parameter
1153 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001154 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1155 format = defaultColorFormat;
1156 }
1157 if (config->mDomain & Config::IS_ENCODER) {
1158 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001159 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1160 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001161 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001162 } else {
1163 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001164 }
1165 }
1166
1167 // propagate encoder delay and padding to output format
1168 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1169 int delay = 0;
1170 if (msg->findInt32("encoder-delay", &delay)) {
1171 config->mOutputFormat->setInt32("encoder-delay", delay);
1172 }
1173 int padding = 0;
1174 if (msg->findInt32("encoder-padding", &padding)) {
1175 config->mOutputFormat->setInt32("encoder-padding", padding);
1176 }
1177 }
1178
1179 // set channel-mask
1180 if (config->mDomain & Config::IS_AUDIO) {
1181 int32_t mask;
1182 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1183 if (config->mDomain & Config::IS_ENCODER) {
1184 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1185 } else {
1186 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1187 }
1188 }
1189 }
1190
Wonsik Kim58d83332021-02-07 22:19:56 -08001191 std::unique_ptr<C2Param> colorTransferRequestParam;
1192 for (std::unique_ptr<C2Param> &param : params) {
1193 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1194 ALOGI("found color transfer request param");
1195 colorTransferRequestParam = std::move(param);
1196 }
1197 }
1198 int32_t colorTransferRequest = 0;
1199 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1200 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1201 colorTransferRequest = 0;
1202 }
1203
1204 if (colorTransferRequest != 0) {
1205 if (colorTransferRequestParam && *colorTransferRequestParam) {
1206 C2StreamColorAspectsInfo::output *info =
1207 static_cast<C2StreamColorAspectsInfo::output *>(
1208 colorTransferRequestParam.get());
1209 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1210 colorTransferRequest = 0;
1211 }
1212 } else {
1213 colorTransferRequest = 0;
1214 }
1215 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1216 }
1217
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001218 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1219 // Need to get stride/vstride
1220 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1221 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1222 // TODO: retrieve these values without allocating a buffer.
1223 // Currently allocating a buffer is necessary to retrieve the layout.
1224 int64_t blockUsage =
1225 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1226 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1227 width, height, pixelFormat, blockUsage, {comp->getName()});
1228 sp<GraphicBlockBuffer> buffer;
1229 if (block) {
1230 buffer = GraphicBlockBuffer::Allocate(
1231 config->mInputFormat,
1232 block,
1233 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1234 } else {
1235 ALOGD("Failed to allocate a graphic block "
1236 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1237 width, height, pixelFormat, (long long)blockUsage);
1238 // This means that byte buffer mode is not supported in this configuration
1239 // anyway. Skip setting stride/vstride to input format.
1240 }
1241 if (buffer) {
1242 sp<ABuffer> imageData = buffer->getImageData();
1243 MediaImage2 *img = nullptr;
1244 if (imageData && imageData->data()
1245 && imageData->size() >= sizeof(MediaImage2)) {
1246 img = (MediaImage2*)imageData->data();
1247 }
1248 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1249 int32_t stride = img->mPlane[0].mRowInc;
1250 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1251 if (img->mNumPlanes > 1 && stride > 0) {
1252 int64_t offsetDelta =
1253 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1254 if (offsetDelta % stride == 0) {
1255 int32_t vstride = int32_t(offsetDelta / stride);
1256 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1257 } else {
1258 ALOGD("Cannot report accurate slice height: "
1259 "offsetDelta = %lld stride = %d",
1260 (long long)offsetDelta, stride);
1261 }
1262 }
1263 }
1264 }
1265 }
1266 }
1267
1268 ALOGD("setup formats input: %s",
1269 config->mInputFormat->debugString().c_str());
1270 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001271 config->mOutputFormat->debugString().c_str());
1272 return OK;
1273 };
1274 if (tryAndReportOnError(doConfig) != OK) {
1275 return;
1276 }
1277
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001278 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1279 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001280
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001281 config->queryConfiguration(comp);
1282
Pawin Vongmasa36653902018-11-15 00:10:25 -08001283 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1284}
1285
1286void CCodec::initiateCreateInputSurface() {
1287 status_t err = [this] {
1288 Mutexed<State>::Locked state(mState);
1289 if (state->get() != ALLOCATED) {
1290 return UNKNOWN_ERROR;
1291 }
1292 // TODO: read it from intf() properly.
1293 if (state->comp->getName().find("encoder") == std::string::npos) {
1294 return INVALID_OPERATION;
1295 }
1296 return OK;
1297 }();
1298 if (err != OK) {
1299 mCallback->onInputSurfaceCreationFailed(err);
1300 return;
1301 }
1302
1303 (new AMessage(kWhatCreateInputSurface, this))->post();
1304}
1305
Lajos Molnar47118272019-01-31 16:28:04 -08001306sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1307 using namespace android::hardware::media::omx::V1_0;
1308 using namespace android::hardware::media::omx::V1_0::utils;
1309 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1310 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1311 android::sp<IOmx> omx = IOmx::getService();
1312 typedef android::hardware::graphics::bufferqueue::V1_0::
1313 IGraphicBufferProducer HGraphicBufferProducer;
1314 typedef android::hardware::media::omx::V1_0::
1315 IGraphicBufferSource HGraphicBufferSource;
1316 OmxStatus s;
1317 android::sp<HGraphicBufferProducer> gbp;
1318 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001319
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001320 using ::android::hardware::Return;
1321 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001322 [&s, &gbp, &gbs](
1323 OmxStatus status,
1324 const android::sp<HGraphicBufferProducer>& producer,
1325 const android::sp<HGraphicBufferSource>& source) {
1326 s = status;
1327 gbp = producer;
1328 gbs = source;
1329 });
1330 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001331 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001332 }
1333
1334 return nullptr;
1335}
1336
1337sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1338 sp<PersistentSurface> surface(CreateInputSurface());
1339
1340 if (surface == nullptr) {
1341 surface = CreateOmxInputSurface();
1342 }
1343
1344 return surface;
1345}
1346
Pawin Vongmasa36653902018-11-15 00:10:25 -08001347void CCodec::createInputSurface() {
1348 status_t err;
1349 sp<IGraphicBufferProducer> bufferProducer;
1350
1351 sp<AMessage> inputFormat;
1352 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001353 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001354 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001355 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1356 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001357 inputFormat = config->mInputFormat;
1358 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001359 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001360 }
1361
Lajos Molnar47118272019-01-31 16:28:04 -08001362 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001363 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1364 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1365 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001366
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001367 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001368 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1369 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001370 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001371 inputSurface));
1372 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001373 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001374 int32_t width = 0;
1375 (void)outputFormat->findInt32("width", &width);
1376 int32_t height = 0;
1377 (void)outputFormat->findInt32("height", &height);
1378 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001379 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001380 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001381 } else {
1382 ALOGE("Corrupted input surface");
1383 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1384 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001385 }
1386
1387 if (err != OK) {
1388 ALOGE("Failed to set up input surface: %d", err);
1389 mCallback->onInputSurfaceCreationFailed(err);
1390 return;
1391 }
1392
1393 mCallback->onInputSurfaceCreated(
1394 inputFormat,
1395 outputFormat,
1396 new BufferProducerWrapper(bufferProducer));
1397}
1398
1399status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001400 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1401 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001402 config->mUsingSurface = true;
1403
1404 // we are now using surface - apply default color aspects to input format - as well as
1405 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001406 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001407 ALOGD("input format %s to %s",
1408 inputFormatChanged ? "changed" : "unchanged",
1409 config->mInputFormat->debugString().c_str());
1410
1411 // configure dataspace
1412 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1413 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1414 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1415 surface->setDataSpace(dataSpace);
1416
1417 status_t err = mChannel->setInputSurface(surface);
1418 if (err != OK) {
1419 // undo input format update
1420 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001421 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001422 return err;
1423 }
1424 config->mInputSurface = surface;
1425
1426 if (config->mISConfig) {
1427 surface->configure(*config->mISConfig);
1428 } else {
1429 ALOGD("ISConfig: no configuration");
1430 }
1431
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001432 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001433}
1434
1435void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1436 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1437 msg->setObject("surface", surface);
1438 msg->post();
1439}
1440
1441void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1442 sp<AMessage> inputFormat;
1443 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001444 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001445 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001446 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1447 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001448 inputFormat = config->mInputFormat;
1449 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001450 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001451 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001452 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1453 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1454 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1455 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001456 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1457 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1458 if (err != OK) {
1459 ALOGE("Failed to set up input surface: %d", err);
1460 mCallback->onInputSurfaceDeclined(err);
1461 return;
1462 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001463 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001464 int32_t width = 0;
1465 (void)outputFormat->findInt32("width", &width);
1466 int32_t height = 0;
1467 (void)outputFormat->findInt32("height", &height);
1468 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001469 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001470 if (err != OK) {
1471 ALOGE("Failed to set up input surface: %d", err);
1472 mCallback->onInputSurfaceDeclined(err);
1473 return;
1474 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001475 } else {
1476 ALOGE("Failed to set input surface: Corrupted surface.");
1477 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1478 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001479 }
1480 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1481}
1482
1483void CCodec::initiateStart() {
1484 auto setStarting = [this] {
1485 Mutexed<State>::Locked state(mState);
1486 if (state->get() != ALLOCATED) {
1487 return UNKNOWN_ERROR;
1488 }
1489 state->set(STARTING);
1490 return OK;
1491 };
1492 if (tryAndReportOnError(setStarting) != OK) {
1493 return;
1494 }
1495
1496 (new AMessage(kWhatStart, this))->post();
1497}
1498
1499void CCodec::start() {
1500 std::shared_ptr<Codec2Client::Component> comp;
1501 auto checkStarting = [this, &comp] {
1502 Mutexed<State>::Locked state(mState);
1503 if (state->get() != STARTING) {
1504 return UNKNOWN_ERROR;
1505 }
1506 comp = state->comp;
1507 return OK;
1508 };
1509 if (tryAndReportOnError(checkStarting) != OK) {
1510 return;
1511 }
1512
1513 c2_status_t err = comp->start();
1514 if (err != C2_OK) {
1515 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1516 ACTION_CODE_FATAL);
1517 return;
1518 }
1519 sp<AMessage> inputFormat;
1520 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001521 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001522 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001523 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001524 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1525 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001526 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001527 // start triggers format dup
1528 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001529 if (config->mInputSurface) {
1530 err2 = config->mInputSurface->start();
1531 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001532 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001533 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001534 if (err2 != OK) {
1535 mCallback->onError(err2, ACTION_CODE_FATAL);
1536 return;
1537 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001538 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001539 if (err2 != OK) {
1540 mCallback->onError(err2, ACTION_CODE_FATAL);
1541 return;
1542 }
1543
1544 auto setRunning = [this] {
1545 Mutexed<State>::Locked state(mState);
1546 if (state->get() != STARTING) {
1547 return UNKNOWN_ERROR;
1548 }
1549 state->set(RUNNING);
1550 return OK;
1551 };
1552 if (tryAndReportOnError(setRunning) != OK) {
1553 return;
1554 }
1555 mCallback->onStartCompleted();
1556
1557 (void)mChannel->requestInitialInputBuffers();
1558}
1559
1560void CCodec::initiateShutdown(bool keepComponentAllocated) {
1561 if (keepComponentAllocated) {
1562 initiateStop();
1563 } else {
1564 initiateRelease();
1565 }
1566}
1567
1568void CCodec::initiateStop() {
1569 {
1570 Mutexed<State>::Locked state(mState);
1571 if (state->get() == ALLOCATED
1572 || state->get() == RELEASED
1573 || state->get() == STOPPING
1574 || state->get() == RELEASING) {
1575 // We're already stopped, released, or doing it right now.
1576 state.unlock();
1577 mCallback->onStopCompleted();
1578 state.lock();
1579 return;
1580 }
1581 state->set(STOPPING);
1582 }
1583
Wonsik Kim936a89c2020-05-08 16:07:50 -07001584 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001585 (new AMessage(kWhatStop, this))->post();
1586}
1587
1588void CCodec::stop() {
1589 std::shared_ptr<Codec2Client::Component> comp;
1590 {
1591 Mutexed<State>::Locked state(mState);
1592 if (state->get() == RELEASING) {
1593 state.unlock();
1594 // We're already stopped or release is in progress.
1595 mCallback->onStopCompleted();
1596 state.lock();
1597 return;
1598 } else if (state->get() != STOPPING) {
1599 state.unlock();
1600 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1601 state.lock();
1602 return;
1603 }
1604 comp = state->comp;
1605 }
1606 status_t err = comp->stop();
1607 if (err != C2_OK) {
1608 // TODO: convert err into status_t
1609 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1610 }
1611
1612 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001613 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1614 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001615 if (config->mInputSurface) {
1616 config->mInputSurface->disconnect();
1617 config->mInputSurface = nullptr;
1618 }
1619 }
1620 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001621 Mutexed<State>::Locked state(mState);
1622 if (state->get() == STOPPING) {
1623 state->set(ALLOCATED);
1624 }
1625 }
1626 mCallback->onStopCompleted();
1627}
1628
1629void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001630 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001631 {
1632 Mutexed<State>::Locked state(mState);
1633 if (state->get() == RELEASED || state->get() == RELEASING) {
1634 // We're already released or doing it right now.
1635 if (sendCallback) {
1636 state.unlock();
1637 mCallback->onReleaseCompleted();
1638 state.lock();
1639 }
1640 return;
1641 }
1642 if (state->get() == ALLOCATING) {
1643 state->set(RELEASING);
1644 // With the altered state allocate() would fail and clean up.
1645 if (sendCallback) {
1646 state.unlock();
1647 mCallback->onReleaseCompleted();
1648 state.lock();
1649 }
1650 return;
1651 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001652 if (state->get() == STARTING
1653 || state->get() == RUNNING
1654 || state->get() == STOPPING) {
1655 // Input surface may have been started, so clean up is needed.
1656 clearInputSurfaceIfNeeded = true;
1657 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001658 state->set(RELEASING);
1659 }
1660
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001661 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001662 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1663 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001664 if (config->mInputSurface) {
1665 config->mInputSurface->disconnect();
1666 config->mInputSurface = nullptr;
1667 }
1668 }
1669
Wonsik Kim936a89c2020-05-08 16:07:50 -07001670 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001671 // thiz holds strong ref to this while the thread is running.
1672 sp<CCodec> thiz(this);
1673 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1674}
1675
1676void CCodec::release(bool sendCallback) {
1677 std::shared_ptr<Codec2Client::Component> comp;
1678 {
1679 Mutexed<State>::Locked state(mState);
1680 if (state->get() == RELEASED) {
1681 if (sendCallback) {
1682 state.unlock();
1683 mCallback->onReleaseCompleted();
1684 state.lock();
1685 }
1686 return;
1687 }
1688 comp = state->comp;
1689 }
1690 comp->release();
1691
1692 {
1693 Mutexed<State>::Locked state(mState);
1694 state->set(RELEASED);
1695 state->comp.reset();
1696 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001697 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001698 if (sendCallback) {
1699 mCallback->onReleaseCompleted();
1700 }
1701}
1702
1703status_t CCodec::setSurface(const sp<Surface> &surface) {
1704 return mChannel->setSurface(surface);
1705}
1706
1707void CCodec::signalFlush() {
1708 status_t err = [this] {
1709 Mutexed<State>::Locked state(mState);
1710 if (state->get() == FLUSHED) {
1711 return ALREADY_EXISTS;
1712 }
1713 if (state->get() != RUNNING) {
1714 return UNKNOWN_ERROR;
1715 }
1716 state->set(FLUSHING);
1717 return OK;
1718 }();
1719 switch (err) {
1720 case ALREADY_EXISTS:
1721 mCallback->onFlushCompleted();
1722 return;
1723 case OK:
1724 break;
1725 default:
1726 mCallback->onError(err, ACTION_CODE_FATAL);
1727 return;
1728 }
1729
1730 mChannel->stop();
1731 (new AMessage(kWhatFlush, this))->post();
1732}
1733
1734void CCodec::flush() {
1735 std::shared_ptr<Codec2Client::Component> comp;
1736 auto checkFlushing = [this, &comp] {
1737 Mutexed<State>::Locked state(mState);
1738 if (state->get() != FLUSHING) {
1739 return UNKNOWN_ERROR;
1740 }
1741 comp = state->comp;
1742 return OK;
1743 };
1744 if (tryAndReportOnError(checkFlushing) != OK) {
1745 return;
1746 }
1747
1748 std::list<std::unique_ptr<C2Work>> flushedWork;
1749 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1750 {
1751 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1752 flushedWork.splice(flushedWork.end(), *queue);
1753 }
1754 if (err != C2_OK) {
1755 // TODO: convert err into status_t
1756 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1757 }
1758
1759 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001760
1761 {
1762 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001763 if (state->get() == FLUSHING) {
1764 state->set(FLUSHED);
1765 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001766 }
1767 mCallback->onFlushCompleted();
1768}
1769
1770void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001771 std::shared_ptr<Codec2Client::Component> comp;
1772 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001773 Mutexed<State>::Locked state(mState);
1774 if (state->get() != FLUSHED) {
1775 return UNKNOWN_ERROR;
1776 }
1777 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001778 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001779 return OK;
1780 };
1781 if (tryAndReportOnError(setResuming) != OK) {
1782 return;
1783 }
1784
Wonsik Kime75a5da2020-02-14 17:29:03 -08001785 {
1786 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1787 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001788 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001789 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001790 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001791 }
1792
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001793 (void)mChannel->start(nullptr, nullptr, [&]{
1794 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1795 const std::unique_ptr<Config> &config = *configLocked;
1796 return config->mBuffersBoundToCodec;
1797 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001798
1799 {
1800 Mutexed<State>::Locked state(mState);
1801 if (state->get() != RESUMING) {
1802 state.unlock();
1803 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1804 state.lock();
1805 return;
1806 }
1807 state->set(RUNNING);
1808 }
1809
1810 (void)mChannel->requestInitialInputBuffers();
1811}
1812
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001813void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001814 std::shared_ptr<Codec2Client::Component> comp;
1815 auto checkState = [this, &comp] {
1816 Mutexed<State>::Locked state(mState);
1817 if (state->get() == RELEASED) {
1818 return INVALID_OPERATION;
1819 }
1820 comp = state->comp;
1821 return OK;
1822 };
1823 if (tryAndReportOnError(checkState) != OK) {
1824 return;
1825 }
1826
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001827 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1828 // the behavior here.
1829 sp<AMessage> params = msg;
1830 int32_t bitrate;
1831 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1832 params = msg->dup();
1833 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1834 }
1835
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001836 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1837 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001838
1839 /**
1840 * Handle input surface parameters
1841 */
1842 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001843 && (config->mDomain & Config::IS_ENCODER)
1844 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001845 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001846
1847 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1848 config->mISConfig->mStopped = false;
1849 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1850 config->mISConfig->mStopped = true;
1851 }
1852
1853 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001854 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001855 config->mISConfig->mSuspended = value;
1856 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001857 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001858 }
1859
1860 (void)config->mInputSurface->configure(*config->mISConfig);
1861 if (config->mISConfig->mStopped) {
1862 config->mInputFormat->setInt64(
1863 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1864 }
1865 }
1866
1867 std::vector<std::unique_ptr<C2Param>> configUpdate;
1868 (void)config->getConfigUpdateFromSdkParams(
1869 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1870 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1871 // Parameter synchronization is not defined when using input surface. For now, route
1872 // these directly to the component.
1873 if (config->mInputSurface == nullptr
1874 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1875 || comp->getName().find("c2.android.") == 0)) {
1876 mChannel->setParameters(configUpdate);
1877 } else {
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001878 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001879 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001880 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001881 }
1882}
1883
1884void CCodec::signalEndOfInputStream() {
1885 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1886}
1887
1888void CCodec::signalRequestIDRFrame() {
1889 std::shared_ptr<Codec2Client::Component> comp;
1890 {
1891 Mutexed<State>::Locked state(mState);
1892 if (state->get() == RELEASED) {
1893 ALOGD("no IDR request sent since component is released");
1894 return;
1895 }
1896 comp = state->comp;
1897 }
1898 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001899 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1900 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001901 std::vector<std::unique_ptr<C2Param>> params;
1902 params.push_back(
1903 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1904 config->setParameters(comp, params, C2_MAY_BLOCK);
1905}
1906
Wonsik Kimab34ed62019-01-31 15:28:46 -08001907void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001908 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001909 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1910 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001911 }
1912 (new AMessage(kWhatWorkDone, this))->post();
1913}
1914
Wonsik Kimab34ed62019-01-31 15:28:46 -08001915void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1916 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001917 if (arrayIndex == 0) {
1918 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001919 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1920 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001921 if (config->mInputSurface) {
1922 config->mInputSurface->onInputBufferDone(frameIndex);
1923 }
1924 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001925}
1926
1927void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1928 TimePoint now = std::chrono::steady_clock::now();
1929 CCodecWatchdog::getInstance()->watch(this);
1930 switch (msg->what()) {
1931 case kWhatAllocate: {
1932 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001933 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001934 sp<RefBase> obj;
1935 CHECK(msg->findObject("codecInfo", &obj));
1936 allocate((MediaCodecInfo *)obj.get());
1937 break;
1938 }
1939 case kWhatConfigure: {
1940 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001941 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001942 sp<AMessage> format;
1943 CHECK(msg->findMessage("format", &format));
1944 configure(format);
1945 break;
1946 }
1947 case kWhatStart: {
1948 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001949 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001950 start();
1951 break;
1952 }
1953 case kWhatStop: {
1954 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001955 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001956 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001957 break;
1958 }
1959 case kWhatFlush: {
1960 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001961 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001962 flush();
1963 break;
1964 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001965 case kWhatRelease: {
1966 mChannel->release();
1967 mClient.reset();
1968 mClientListener.reset();
1969 break;
1970 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001971 case kWhatCreateInputSurface: {
1972 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001973 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001974 createInputSurface();
1975 break;
1976 }
1977 case kWhatSetInputSurface: {
1978 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001979 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001980 sp<RefBase> obj;
1981 CHECK(msg->findObject("surface", &obj));
1982 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1983 setInputSurface(surface);
1984 break;
1985 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001986 case kWhatWorkDone: {
1987 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001988 bool shouldPost = false;
1989 {
1990 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1991 if (queue->empty()) {
1992 break;
1993 }
1994 work.swap(queue->front());
1995 queue->pop_front();
1996 shouldPost = !queue->empty();
1997 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001998 if (shouldPost) {
1999 (new AMessage(kWhatWorkDone, this))->post();
2000 }
2001
Pawin Vongmasa36653902018-11-15 00:10:25 -08002002 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002003 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2004 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002005 Config::Watcher<C2StreamInitDataInfo::output> initData =
2006 config->watch<C2StreamInitDataInfo::output>();
2007 if (!work->worklets.empty()
2008 && (work->worklets.front()->output.flags
2009 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
2010
2011 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002012 std::vector<std::unique_ptr<C2Param>> updates;
2013 for (const std::unique_ptr<C2Param> &param
2014 : work->worklets.front()->output.configUpdate) {
2015 updates.push_back(C2Param::Copy(*param));
2016 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002017 unsigned stream = 0;
2018 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2019 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2020 // move all info into output-stream #0 domain
2021 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
2022 }
George Burgess IVc813a592020-02-22 22:54:44 -08002023
2024 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2025 // for now only do the first block
2026 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002027 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2028 // block.crop().left, block.crop().top,
2029 // block.crop().width, block.crop().height,
2030 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08002031 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08002032 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
2033 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07002034 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002035 }
2036 ++stream;
2037 }
2038
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002039 sp<AMessage> outputFormat = config->mOutputFormat;
2040 config->updateConfiguration(updates, config->mOutputDomain);
2041 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002042
2043 // copy standard infos to graphic buffers if not already present (otherwise, we
2044 // may overwrite the actual intermediate value with a final value)
2045 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07002046 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002047 C2StreamRotationInfo::output::PARAM_TYPE,
2048 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2049 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2050 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08002051 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08002052 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2053 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2054 };
2055 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2056 if (buf->data().graphicBlocks().size()) {
2057 for (C2Param::Index ix : stdGfxInfos) {
2058 if (!buf->hasInfo(ix)) {
2059 const C2Param *param =
2060 config->getConfigParameterValue(ix.withStream(stream));
2061 if (param) {
2062 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2063 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2064 }
2065 }
2066 }
2067 }
2068 ++stream;
2069 }
2070 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002071 if (config->mInputSurface) {
2072 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2073 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002074 mChannel->onWorkDone(
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002075 std::move(work), config->mOutputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002076 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002077 break;
2078 }
2079 case kWhatWatch: {
2080 // watch message already posted; no-op.
2081 break;
2082 }
2083 default: {
2084 ALOGE("unrecognized message");
2085 break;
2086 }
2087 }
2088 setDeadline(TimePoint::max(), 0ms, "none");
2089}
2090
2091void CCodec::setDeadline(
2092 const TimePoint &now,
2093 const std::chrono::milliseconds &timeout,
2094 const char *name) {
2095 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2096 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2097 deadline->set(now + (timeout * mult), name);
2098}
2099
2100void CCodec::initiateReleaseIfStuck() {
2101 std::string name;
2102 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002103 {
2104 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002105 if (deadline->get() < std::chrono::steady_clock::now()) {
2106 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002107 }
2108 if (deadline->get() != TimePoint::max()) {
2109 pendingDeadline = true;
2110 }
2111 }
2112 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002113 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2114 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2115 if (elapsed >= kWorkDurationThreshold) {
2116 name = "queue";
2117 }
2118 if (elapsed > 0s) {
2119 pendingDeadline = true;
2120 }
2121 }
2122 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002123 // We're not stuck.
2124 if (pendingDeadline) {
2125 // If we are not stuck yet but still has deadline coming up,
2126 // post watch message to check back later.
2127 (new AMessage(kWhatWatch, this))->post();
2128 }
2129 return;
2130 }
2131
2132 ALOGW("previous call to %s exceeded timeout", name.c_str());
2133 initiateRelease(false);
2134 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2135}
2136
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002137// static
2138PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002139 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002140 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002141 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002142 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2143 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002144 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002145 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2146 sp<IGraphicBufferProducer> gbp;
2147 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2148 status_t err = gbs->initCheck();
2149 if (err != OK) {
2150 ALOGE("Failed to create persistent input surface: error %d", err);
2151 return nullptr;
2152 }
2153 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002154 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002155 } else {
2156 return nullptr;
2157 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002158 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002159 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002160 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002161 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002162 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002163}
2164
Wonsik Kimffb889a2020-05-28 11:32:25 -07002165class IntfCache {
2166public:
2167 IntfCache() = default;
2168
2169 status_t init(const std::string &name) {
2170 std::shared_ptr<Codec2Client::Interface> intf{
2171 Codec2Client::CreateInterfaceByName(name.c_str())};
2172 if (!intf) {
2173 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2174 mInitStatus = NO_INIT;
2175 return NO_INIT;
2176 }
2177 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2178 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2179 C2ParamField{&sUsage, &sUsage.value}));
2180 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2181 if (err != C2_OK) {
2182 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2183 name.c_str(), err);
2184 mFields[0].status = err;
2185 }
2186 std::vector<std::unique_ptr<C2Param>> params;
2187 err = intf->query(
2188 {&mApiFeatures},
2189 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2190 C2_MAY_BLOCK,
2191 &params);
2192 if (err != C2_OK && err != C2_BAD_INDEX) {
2193 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2194 name.c_str(), err);
2195 }
2196 while (!params.empty()) {
2197 C2Param *param = params.back().release();
2198 params.pop_back();
2199 if (!param) {
2200 continue;
2201 }
2202 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2203 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002204 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002205 }
2206 }
2207 mInitStatus = OK;
2208 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002209 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002210
2211 status_t initCheck() const { return mInitStatus; }
2212
2213 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2214 CHECK_EQ(1u, mFields.size());
2215 return mFields[0];
2216 }
2217
2218 const C2ApiFeaturesSetting &getApiFeatures() const {
2219 return mApiFeatures;
2220 }
2221
2222 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2223 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2224 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2225 C2PortAllocatorsTuning::input::AllocUnique(0);
2226 param->invalidate();
2227 return param;
2228 }();
2229 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2230 }
2231
2232private:
2233 status_t mInitStatus{NO_INIT};
2234
2235 std::vector<C2FieldSupportedValuesQuery> mFields;
2236 C2ApiFeaturesSetting mApiFeatures;
2237 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2238};
2239
2240static const IntfCache &GetIntfCache(const std::string &name) {
2241 static IntfCache sNullIntfCache;
2242 static std::mutex sMutex;
2243 static std::map<std::string, IntfCache> sCache;
2244 std::unique_lock<std::mutex> lock{sMutex};
2245 auto it = sCache.find(name);
2246 if (it == sCache.end()) {
2247 lock.unlock();
2248 IntfCache intfCache;
2249 status_t err = intfCache.init(name);
2250 if (err != OK) {
2251 return sNullIntfCache;
2252 }
2253 lock.lock();
2254 it = sCache.insert({name, std::move(intfCache)}).first;
2255 }
2256 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002257}
2258
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002259static status_t GetCommonAllocatorIds(
2260 const std::vector<std::string> &names,
2261 C2Allocator::type_t type,
2262 std::set<C2Allocator::id_t> *ids) {
2263 int poolMask = GetCodec2PoolMask();
2264 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2265 C2Allocator::id_t defaultAllocatorId =
2266 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2267
2268 ids->clear();
2269 if (names.empty()) {
2270 return OK;
2271 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002272 bool firstIteration = true;
2273 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002274 const IntfCache &intfCache = GetIntfCache(name);
2275 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002276 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002277 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002278 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002279 if (firstIteration) {
2280 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002281 if (allocators && allocators.flexCount() > 0) {
2282 ids->insert(allocators.m.values,
2283 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002284 }
2285 if (ids->empty()) {
2286 // The component does not advertise allocators. Use default.
2287 ids->insert(defaultAllocatorId);
2288 }
2289 continue;
2290 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002291 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002292 if (allocators && allocators.flexCount() > 0) {
2293 filtered = true;
2294 for (auto it = ids->begin(); it != ids->end(); ) {
2295 bool found = false;
2296 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2297 if (allocators.m.values[j] == *it) {
2298 found = true;
2299 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002300 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002301 }
2302 if (found) {
2303 ++it;
2304 } else {
2305 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002306 }
2307 }
2308 }
2309 if (!filtered) {
2310 // The component does not advertise supported allocators. Use default.
2311 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2312 if (ids->size() != (containsDefault ? 1 : 0)) {
2313 ids->clear();
2314 if (containsDefault) {
2315 ids->insert(defaultAllocatorId);
2316 }
2317 }
2318 }
2319 }
2320 // Finally, filter with pool masks
2321 for (auto it = ids->begin(); it != ids->end(); ) {
2322 if ((poolMask >> *it) & 1) {
2323 ++it;
2324 } else {
2325 it = ids->erase(it);
2326 }
2327 }
2328 return OK;
2329}
2330
2331static status_t CalculateMinMaxUsage(
2332 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2333 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2334 *minUsage = 0;
2335 *maxUsage = ~0ull;
2336 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002337 const IntfCache &intfCache = GetIntfCache(name);
2338 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002339 continue;
2340 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002341 const C2FieldSupportedValuesQuery &usageSupportedValues =
2342 intfCache.getUsageSupportedValues();
2343 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002344 continue;
2345 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002346 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002347 if (supported.type != C2FieldSupportedValues::FLAGS) {
2348 continue;
2349 }
2350 if (supported.values.empty()) {
2351 *maxUsage = 0;
2352 continue;
2353 }
2354 *minUsage |= supported.values[0].u64;
2355 int64_t currentMaxUsage = 0;
2356 for (const C2Value::Primitive &flags : supported.values) {
2357 currentMaxUsage |= flags.u64;
2358 }
2359 *maxUsage &= currentMaxUsage;
2360 }
2361 return OK;
2362}
2363
2364// static
2365status_t CCodec::CanFetchLinearBlock(
2366 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002367 for (const std::string &name : names) {
2368 const IntfCache &intfCache = GetIntfCache(name);
2369 if (intfCache.initCheck() != OK) {
2370 continue;
2371 }
2372 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2373 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2374 *isCompatible = false;
2375 return OK;
2376 }
2377 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002378 uint64_t minUsage = usage.expected;
2379 uint64_t maxUsage = ~0ull;
2380 std::set<C2Allocator::id_t> allocators;
2381 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2382 if (allocators.empty()) {
2383 *isCompatible = false;
2384 return OK;
2385 }
2386 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2387 *isCompatible = ((maxUsage & minUsage) == minUsage);
2388 return OK;
2389}
2390
2391static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2392 static std::mutex sMutex{};
2393 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2394 std::unique_lock<std::mutex> lock{sMutex};
2395 std::shared_ptr<C2BlockPool> pool;
2396 auto it = sPools.find(allocId);
2397 if (it == sPools.end()) {
2398 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2399 if (err == OK) {
2400 sPools.emplace(allocId, pool);
2401 } else {
2402 pool.reset();
2403 }
2404 } else {
2405 pool = it->second;
2406 }
2407 return pool;
2408}
2409
2410// static
2411std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2412 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
2413 uint64_t minUsage = usage.expected;
2414 uint64_t maxUsage = ~0ull;
2415 std::set<C2Allocator::id_t> allocators;
2416 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2417 if (allocators.empty()) {
2418 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2419 }
2420 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2421 if ((maxUsage & minUsage) != minUsage) {
2422 allocators.clear();
2423 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2424 }
2425 std::shared_ptr<C2LinearBlock> block;
2426 for (C2Allocator::id_t allocId : allocators) {
2427 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2428 if (!pool) {
2429 continue;
2430 }
2431 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2432 if (err != C2_OK || !block) {
2433 block.reset();
2434 continue;
2435 }
2436 break;
2437 }
2438 return block;
2439}
2440
2441// static
2442status_t CCodec::CanFetchGraphicBlock(
2443 const std::vector<std::string> &names, bool *isCompatible) {
2444 uint64_t minUsage = 0;
2445 uint64_t maxUsage = ~0ull;
2446 std::set<C2Allocator::id_t> allocators;
2447 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2448 if (allocators.empty()) {
2449 *isCompatible = false;
2450 return OK;
2451 }
2452 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2453 *isCompatible = ((maxUsage & minUsage) == minUsage);
2454 return OK;
2455}
2456
2457// static
2458std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2459 int32_t width,
2460 int32_t height,
2461 int32_t format,
2462 uint64_t usage,
2463 const std::vector<std::string> &names) {
2464 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2465 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2466 ALOGD("Unrecognized pixel format: %d", format);
2467 return nullptr;
2468 }
2469 uint64_t minUsage = 0;
2470 uint64_t maxUsage = ~0ull;
2471 std::set<C2Allocator::id_t> allocators;
2472 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2473 if (allocators.empty()) {
2474 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2475 }
2476 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2477 minUsage |= usage;
2478 if ((maxUsage & minUsage) != minUsage) {
2479 allocators.clear();
2480 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2481 }
2482 std::shared_ptr<C2GraphicBlock> block;
2483 for (C2Allocator::id_t allocId : allocators) {
2484 std::shared_ptr<C2BlockPool> pool;
2485 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2486 if (err != C2_OK || !pool) {
2487 continue;
2488 }
2489 err = pool->fetchGraphicBlock(
2490 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2491 if (err != C2_OK || !block) {
2492 block.reset();
2493 continue;
2494 }
2495 break;
2496 }
2497 return block;
2498}
2499
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002500} // namespace android
2501