blob: f034a6fd2120820d168cf1c7c7da76617d06028b [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;
251 // WORKAROUND: having more slots improve performance while consuming
252 // more memory. This is a temporary workaround to reduce memory for
253 // larger-than-4K scenario.
254 if (mWidth * mHeight > 4096 * 2340) {
255 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900256
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800257 OMX_PARAM_PORTDEFINITIONTYPE param;
258 param.nPortIndex = kPortIndexInput;
259 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
260 &param, sizeof(param));
261 if (err == OK) {
262 numSlots = param.nBufferCountActual;
263 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900264 }
265
266 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800267 source->onInputBufferAdded(i);
268 }
269
270 source->onOmxExecuting();
271 return OK;
272 }
273
274 status_t signalEndOfInputStream() override {
275 return GetStatus(mSource->signalEndOfInputStream());
276 }
277
278 status_t configure(Config &config) {
279 std::stringstream status;
280 status_t err = OK;
281
282 // handle each configuration granually, in case we need to handle part of the configuration
283 // elsewhere
284
285 // TRICKY: we do not unset frame delay repeating
286 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
287 int64_t us = 1e6 / config.mMinFps + 0.5;
288 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
289 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
290 if (res != OK) {
291 status << " (=> " << asString(res) << ")";
292 err = res;
293 }
294 mConfig.mMinFps = config.mMinFps;
295 }
296
297 // pts gap
298 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
299 if (mNode != nullptr) {
300 OMX_PARAM_U32TYPE ptrGapParam = {};
301 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700302 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800303 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
304 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700305 // float -> uint32_t is undefined if the value is negative.
306 // First convert to int32_t to ensure the expected behavior.
307 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800308 (void)mNode->setParameter(
309 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
310 &ptrGapParam, sizeof(ptrGapParam));
311 }
312 }
313
314 // max fps
315 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700316 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800317 && config.mMaxFps != mConfig.mMaxFps) {
318 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
319 status << " maxFps=" << config.mMaxFps;
320 if (res != OK) {
321 status << " (=> " << asString(res) << ")";
322 err = res;
323 }
324 mConfig.mMaxFps = config.mMaxFps;
325 }
326
327 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
328 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
329 status << " timeOffset " << config.mTimeOffsetUs << "us";
330 if (res != OK) {
331 status << " (=> " << asString(res) << ")";
332 err = res;
333 }
334 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
335 }
336
337 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
338 status_t res =
339 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
340 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
341 if (res != OK) {
342 status << " (=> " << asString(res) << ")";
343 err = res;
344 }
345 mConfig.mCaptureFps = config.mCaptureFps;
346 mConfig.mCodedFps = config.mCodedFps;
347 }
348
349 if (config.mStartAtUs != mConfig.mStartAtUs
350 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
351 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
352 status << " start at " << config.mStartAtUs << "us";
353 if (res != OK) {
354 status << " (=> " << asString(res) << ")";
355 err = res;
356 }
357 mConfig.mStartAtUs = config.mStartAtUs;
358 mConfig.mStopped = config.mStopped;
359 }
360
361 // suspend-resume
362 if (config.mSuspended != mConfig.mSuspended) {
363 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
364 status << " " << (config.mSuspended ? "suspend" : "resume")
365 << " at " << config.mSuspendAtUs << "us";
366 if (res != OK) {
367 status << " (=> " << asString(res) << ")";
368 err = res;
369 }
370 mConfig.mSuspended = config.mSuspended;
371 mConfig.mSuspendAtUs = config.mSuspendAtUs;
372 }
373
374 if (config.mStopped != mConfig.mStopped && config.mStopped) {
375 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
376 status << " stop at " << config.mStopAtUs << "us";
377 if (res != OK) {
378 status << " (=> " << asString(res) << ")";
379 err = res;
380 } else {
381 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700382 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
383 [&res, &delayUs = config.mInputDelayUs](
384 auto status, auto stopTimeOffsetUs) {
385 res = static_cast<status_t>(status);
386 delayUs = stopTimeOffsetUs;
387 });
388 if (!trans.isOk()) {
389 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
390 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800391 if (res != OK) {
392 status << " (=> " << asString(res) << ")";
393 } else {
394 status << "=" << config.mInputDelayUs << "us";
395 }
396 mConfig.mInputDelayUs = config.mInputDelayUs;
397 }
398 mConfig.mStopAtUs = config.mStopAtUs;
399 mConfig.mStopped = config.mStopped;
400 }
401
402 // color aspects (android._color-aspects)
403
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700404 // consumer usage is queried earlier.
405
Wonsik Kimbd557932019-07-02 15:51:20 -0700406 if (status.str().empty()) {
407 ALOGD("ISConfig not changed");
408 } else {
409 ALOGD("ISConfig%s", status.str().c_str());
410 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800411 return err;
412 }
413
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700414 void onInputBufferDone(c2_cntr64_t index) override {
415 mNode->onInputBufferDone(index);
416 }
417
Pawin Vongmasa36653902018-11-15 00:10:25 -0800418private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700419 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800420 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700421 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800422 uint32_t mWidth;
423 uint32_t mHeight;
424 Config mConfig;
425};
426
427class Codec2ClientInterfaceWrapper : public C2ComponentStore {
428 std::shared_ptr<Codec2Client> mClient;
429
430public:
431 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
432 : mClient(client) { }
433
434 virtual ~Codec2ClientInterfaceWrapper() = default;
435
436 virtual c2_status_t config_sm(
437 const std::vector<C2Param *> &params,
438 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
439 return mClient->config(params, C2_MAY_BLOCK, failures);
440 };
441
442 virtual c2_status_t copyBuffer(
443 std::shared_ptr<C2GraphicBuffer>,
444 std::shared_ptr<C2GraphicBuffer>) {
445 return C2_OMITTED;
446 }
447
448 virtual c2_status_t createComponent(
449 C2String, std::shared_ptr<C2Component> *const component) {
450 component->reset();
451 return C2_OMITTED;
452 }
453
454 virtual c2_status_t createInterface(
455 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
456 interface->reset();
457 return C2_OMITTED;
458 }
459
460 virtual c2_status_t query_sm(
461 const std::vector<C2Param *> &stackParams,
462 const std::vector<C2Param::Index> &heapParamIndices,
463 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
464 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
465 }
466
467 virtual c2_status_t querySupportedParams_nb(
468 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
469 return mClient->querySupportedParams(params);
470 }
471
472 virtual c2_status_t querySupportedValues_sm(
473 std::vector<C2FieldSupportedValuesQuery> &fields) const {
474 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
475 }
476
477 virtual C2String getName() const {
478 return mClient->getName();
479 }
480
481 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
482 return mClient->getParamReflector();
483 }
484
485 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
486 return std::vector<std::shared_ptr<const C2Component::Traits>>();
487 }
488};
489
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800490void RevertOutputFormatIfNeeded(
491 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
492 // We used to not report changes to these keys to the client.
493 const static std::set<std::string> sIgnoredKeys({
494 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800495 KEY_FRAME_RATE,
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800496 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800497 KEY_MAX_WIDTH,
498 KEY_MAX_HEIGHT,
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800499 "csd-0",
500 "csd-1",
501 "csd-2",
502 });
503 if (currentFormat == oldFormat) {
504 return;
505 }
506 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
507 AMessage::Type type;
508 for (size_t i = diff->countEntries(); i > 0; --i) {
509 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
510 diff->removeEntryAt(i - 1);
511 }
512 }
513 if (diff->countEntries() == 0) {
514 currentFormat = oldFormat;
515 }
516}
517
Pawin Vongmasa36653902018-11-15 00:10:25 -0800518} // namespace
519
520// CCodec::ClientListener
521
522struct CCodec::ClientListener : public Codec2Client::Listener {
523
524 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
525
526 virtual void onWorkDone(
527 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800528 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800529 (void)component;
530 sp<CCodec> codec(mCodec.promote());
531 if (!codec) {
532 return;
533 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800534 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800535 }
536
537 virtual void onTripped(
538 const std::weak_ptr<Codec2Client::Component>& component,
539 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
540 ) override {
541 // TODO
542 (void)component;
543 (void)settingResult;
544 }
545
546 virtual void onError(
547 const std::weak_ptr<Codec2Client::Component>& component,
548 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800549 {
550 // Component is only used for reporting as we use a separate listener for each instance
551 std::shared_ptr<Codec2Client::Component> comp = component.lock();
552 if (!comp) {
553 ALOGD("Component died with error: 0x%x", errorCode);
554 } else {
555 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
556 }
557 }
558
559 // Report to MediaCodec
560 // Note: for now we do not propagate the error code to MediaCodec as we would need
561 // to translate to a MediaCodec error.
562 sp<CCodec> codec(mCodec.promote());
563 if (!codec || !codec->mCallback) {
564 return;
565 }
566 codec->mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800567 }
568
569 virtual void onDeath(
570 const std::weak_ptr<Codec2Client::Component>& component) override {
571 { // Log the death of the component.
572 std::shared_ptr<Codec2Client::Component> comp = component.lock();
573 if (!comp) {
574 ALOGE("Codec2 component died.");
575 } else {
576 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
577 }
578 }
579
580 // Report to MediaCodec.
581 sp<CCodec> codec(mCodec.promote());
582 if (!codec || !codec->mCallback) {
583 return;
584 }
585 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
586 }
587
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800588 virtual void onFrameRendered(uint64_t bufferQueueId,
589 int32_t slotId,
590 int64_t timestampNs) override {
591 // TODO: implement
592 (void)bufferQueueId;
593 (void)slotId;
594 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800595 }
596
597 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800598 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800599 sp<CCodec> codec(mCodec.promote());
600 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800601 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800602 }
603 }
604
605private:
606 wp<CCodec> mCodec;
607};
608
609// CCodecCallbackImpl
610
611class CCodecCallbackImpl : public CCodecCallback {
612public:
613 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
614 ~CCodecCallbackImpl() override = default;
615
616 void onError(status_t err, enum ActionCode actionCode) override {
617 mCodec->mCallback->onError(err, actionCode);
618 }
619
620 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
621 mCodec->mCallback->onOutputFramesRendered(
622 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
623 }
624
Pawin Vongmasa36653902018-11-15 00:10:25 -0800625 void onOutputBuffersChanged() override {
626 mCodec->mCallback->onOutputBuffersChanged();
627 }
628
629private:
630 CCodec *mCodec;
631};
632
633// CCodec
634
635CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700636 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
637 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800638}
639
640CCodec::~CCodec() {
641}
642
643std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
644 return mChannel;
645}
646
647status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
648 status_t err = job();
649 if (err != C2_OK) {
650 mCallback->onError(err, ACTION_CODE_FATAL);
651 }
652 return err;
653}
654
655void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
656 auto setAllocating = [this] {
657 Mutexed<State>::Locked state(mState);
658 if (state->get() != RELEASED) {
659 return INVALID_OPERATION;
660 }
661 state->set(ALLOCATING);
662 return OK;
663 };
664 if (tryAndReportOnError(setAllocating) != OK) {
665 return;
666 }
667
668 sp<RefBase> codecInfo;
669 CHECK(msg->findObject("codecInfo", &codecInfo));
670 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
671
672 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
673 allocMsg->setObject("codecInfo", codecInfo);
674 allocMsg->post();
675}
676
677void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
678 if (codecInfo == nullptr) {
679 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
680 return;
681 }
682 ALOGD("allocate(%s)", codecInfo->getCodecName());
683 mClientListener.reset(new ClientListener(this));
684
685 AString componentName = codecInfo->getCodecName();
686 std::shared_ptr<Codec2Client> client;
687
688 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700689 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800690 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800691 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800692 SetPreferredCodec2ComponentStore(
693 std::make_shared<Codec2ClientInterfaceWrapper>(client));
694 }
695
696 std::shared_ptr<Codec2Client::Component> comp =
697 Codec2Client::CreateComponentByName(
698 componentName.c_str(),
699 mClientListener,
700 &client);
701 if (!comp) {
702 ALOGE("Failed Create component: %s", componentName.c_str());
703 Mutexed<State>::Locked state(mState);
704 state->set(RELEASED);
705 state.unlock();
706 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
707 state.lock();
708 return;
709 }
710 ALOGI("Created component [%s]", componentName.c_str());
711 mChannel->setComponent(comp);
712 auto setAllocated = [this, comp, client] {
713 Mutexed<State>::Locked state(mState);
714 if (state->get() != ALLOCATING) {
715 state->set(RELEASED);
716 return UNKNOWN_ERROR;
717 }
718 state->set(ALLOCATED);
719 state->comp = comp;
720 mClient = client;
721 return OK;
722 };
723 if (tryAndReportOnError(setAllocated) != OK) {
724 return;
725 }
726
727 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700728 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
729 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800730 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800731 if (err != OK) {
732 ALOGW("Failed to initialize configuration support");
733 // TODO: report error once we complete implementation.
734 }
735 config->queryConfiguration(comp);
736
737 mCallback->onComponentAllocated(componentName.c_str());
738}
739
740void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
741 auto checkAllocated = [this] {
742 Mutexed<State>::Locked state(mState);
743 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
744 };
745 if (tryAndReportOnError(checkAllocated) != OK) {
746 return;
747 }
748
749 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
750 msg->setMessage("format", format);
751 msg->post();
752}
753
754void CCodec::configure(const sp<AMessage> &msg) {
755 std::shared_ptr<Codec2Client::Component> comp;
756 auto checkAllocated = [this, &comp] {
757 Mutexed<State>::Locked state(mState);
758 if (state->get() != ALLOCATED) {
759 state->set(RELEASED);
760 return UNKNOWN_ERROR;
761 }
762 comp = state->comp;
763 return OK;
764 };
765 if (tryAndReportOnError(checkAllocated) != OK) {
766 return;
767 }
768
769 auto doConfig = [msg, comp, this]() -> status_t {
770 AString mime;
771 if (!msg->findString("mime", &mime)) {
772 return BAD_VALUE;
773 }
774
775 int32_t encoder;
776 if (!msg->findInt32("encoder", &encoder)) {
777 encoder = false;
778 }
779
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800780 int32_t flags;
781 if (!msg->findInt32("flags", &flags)) {
782 return BAD_VALUE;
783 }
784
Pawin Vongmasa36653902018-11-15 00:10:25 -0800785 // TODO: read from intf()
786 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
787 return UNKNOWN_ERROR;
788 }
789
790 int32_t storeMeta;
791 if (encoder
792 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
793 && storeMeta != kMetadataBufferTypeInvalid) {
794 if (storeMeta != kMetadataBufferTypeANWBuffer) {
795 ALOGD("Only ANW buffers are supported for legacy metadata mode");
796 return BAD_VALUE;
797 }
798 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
799 }
800
801 sp<RefBase> obj;
802 sp<Surface> surface;
803 if (msg->findObject("native-window", &obj)) {
804 surface = static_cast<Surface *>(obj.get());
805 setSurface(surface);
806 }
807
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700808 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
809 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800810 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800811 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
812 ALOGD("[%s] buffers are %sbound to CCodec for this session",
813 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800814
Wonsik Kim1114eea2019-02-25 14:35:24 -0800815 // Enforce required parameters
816 int32_t i32;
817 float flt;
818 if (config->mDomain & Config::IS_AUDIO) {
819 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
820 ALOGD("sample rate is missing, which is required for audio components.");
821 return BAD_VALUE;
822 }
823 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
824 ALOGD("channel count is missing, which is required for audio components.");
825 return BAD_VALUE;
826 }
827 if ((config->mDomain & Config::IS_ENCODER)
828 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
829 && !msg->findInt32(KEY_BIT_RATE, &i32)
830 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
831 ALOGD("bitrate is missing, which is required for audio encoders.");
832 return BAD_VALUE;
833 }
834 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800835 int32_t width = 0;
836 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800837 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800838 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800839 ALOGD("width is missing, which is required for image/video components.");
840 return BAD_VALUE;
841 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800842 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800843 ALOGD("height is missing, which is required for image/video components.");
844 return BAD_VALUE;
845 }
846 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700847 int32_t mode = BITRATE_MODE_VBR;
848 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700849 if (!msg->findInt32(KEY_QUALITY, &i32)) {
850 ALOGD("quality is missing, which is required for video encoders in CQ.");
851 return BAD_VALUE;
852 }
853 } else {
854 if (!msg->findInt32(KEY_BIT_RATE, &i32)
855 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
856 ALOGD("bitrate is missing, which is required for video encoders.");
857 return BAD_VALUE;
858 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800859 }
860 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
861 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
862 ALOGD("I frame interval is missing, which is required for video encoders.");
863 return BAD_VALUE;
864 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700865 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
866 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
867 ALOGD("frame rate is missing, which is required for video encoders.");
868 return BAD_VALUE;
869 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800870 }
871 }
872
Pawin Vongmasa36653902018-11-15 00:10:25 -0800873 /*
874 * Handle input surface configuration
875 */
876 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
877 && (config->mDomain & Config::IS_ENCODER)) {
878 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
879 {
880 config->mISConfig->mMinFps = 0;
881 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800882 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800883 config->mISConfig->mMinFps = 1e6 / value;
884 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700885 if (!msg->findFloat(
886 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
887 config->mISConfig->mMaxFps = -1;
888 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800889 config->mISConfig->mMinAdjustedFps = 0;
890 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800891 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800892 if (value < 0 && value >= INT32_MIN) {
893 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700894 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800895 } else if (value > 0 && value <= INT32_MAX) {
896 config->mISConfig->mMinAdjustedFps = 1e6 / value;
897 }
898 }
899 }
900
901 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700902 bool captureFpsFound = false;
903 double timeLapseFps;
904 float captureRate;
905 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
906 config->mISConfig->mCaptureFps = timeLapseFps;
907 captureFpsFound = true;
908 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
909 config->mISConfig->mCaptureFps = captureRate;
910 captureFpsFound = true;
911 }
912 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800913 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
914 }
915 }
916
917 {
918 config->mISConfig->mSuspended = false;
919 config->mISConfig->mSuspendAtUs = -1;
920 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800921 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800922 config->mISConfig->mSuspended = true;
923 }
924 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700925 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800926 }
927
928 /*
929 * Handle desired color format.
930 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700931 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800932 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700933 int32_t format = 0;
934 // Query vendor format for Flexible YUV
935 std::vector<std::unique_ptr<C2Param>> heapParams;
936 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
937 if (mClient->query(
938 {},
939 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
940 C2_MAY_BLOCK,
941 &heapParams) == C2_OK
942 && heapParams.size() == 1u) {
943 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
944 heapParams[0].get());
945 } else {
946 pixelFormatInfo = nullptr;
947 }
948 std::optional<uint32_t> flexPixelFormat{};
949 std::optional<uint32_t> flexPlanarPixelFormat{};
950 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
951 if (pixelFormatInfo && *pixelFormatInfo) {
952 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
953 const C2FlexiblePixelFormatDescriptorStruct &desc =
954 pixelFormatInfo->m.values[i];
955 if (desc.bitDepth != 8
956 || desc.subsampling != C2Color::YUV_420
957 // TODO(b/180076105): some device report wrong layout
958 // || desc.layout == C2Color::INTERLEAVED_PACKED
959 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
960 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
961 continue;
962 }
963 if (!flexPixelFormat) {
964 flexPixelFormat = desc.pixelFormat;
965 }
966 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
967 flexPlanarPixelFormat = desc.pixelFormat;
968 }
969 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
970 flexSemiPlanarPixelFormat = desc.pixelFormat;
971 }
972 }
973 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800974 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700975 // Also handle default color format (encoders require color format, so this is only
976 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -0800977 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700978 if (surface == nullptr) {
979 format = flexPixelFormat.value_or(COLOR_FormatYUV420Flexible);
980 } else {
981 format = COLOR_FormatSurface;
982 }
983 defaultColorFormat = format;
984 }
985 } else {
986 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
987 switch (format) {
988 case COLOR_FormatYUV420Flexible:
989 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
990 break;
991 case COLOR_FormatYUV420Planar:
992 case COLOR_FormatYUV420PackedPlanar:
993 format = flexPlanarPixelFormat.value_or(
994 flexPixelFormat.value_or(format));
995 break;
996 case COLOR_FormatYUV420SemiPlanar:
997 case COLOR_FormatYUV420PackedSemiPlanar:
998 format = flexSemiPlanarPixelFormat.value_or(
999 flexPixelFormat.value_or(format));
1000 break;
1001 default:
1002 // No-op
1003 break;
1004 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001005 }
1006 }
1007
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001008 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001009 msg->setInt32("android._color-format", format);
1010 }
1011 }
1012
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001013 int32_t subscribeToAllVendorParams;
1014 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1015 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1016 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1017 }
1018 }
1019
Pawin Vongmasa36653902018-11-15 00:10:25 -08001020 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001021 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1022 // the behavior here.
1023 sp<AMessage> sdkParams = msg;
1024 int32_t videoBitrate;
1025 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1026 sdkParams = msg->dup();
1027 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1028 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001029 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001030 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001031 if (err != OK) {
1032 ALOGW("failed to convert configuration to c2 params");
1033 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001034
1035 int32_t maxBframes = 0;
1036 if ((config->mDomain & Config::IS_ENCODER)
1037 && (config->mDomain & Config::IS_VIDEO)
1038 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1039 && maxBframes > 0) {
1040 std::unique_ptr<C2StreamGopTuning::output> gop =
1041 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1042 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1043 gop->m.values[1] = {
1044 C2Config::picture_type_t(P_FRAME | B_FRAME),
1045 uint32_t(maxBframes)
1046 };
1047 configUpdate.push_back(std::move(gop));
1048 }
1049
Pawin Vongmasa36653902018-11-15 00:10:25 -08001050 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1051 if (err != OK) {
1052 ALOGW("failed to configure c2 params");
1053 return err;
1054 }
1055
1056 std::vector<std::unique_ptr<C2Param>> params;
1057 C2StreamUsageTuning::input usage(0u, 0u);
1058 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001059 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001060
Wonsik Kim58d83332021-02-07 22:19:56 -08001061 C2Param::Index colorAspectsRequestIndex =
1062 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001063 std::initializer_list<C2Param::Index> indices {
Wonsik Kim58d83332021-02-07 22:19:56 -08001064 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001065 };
1066 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001067 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001068 indices,
1069 C2_DONT_BLOCK,
1070 &params);
1071 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1072 ALOGE("Failed to query component interface: %d", c2err);
1073 return UNKNOWN_ERROR;
1074 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001075 if (usage) {
1076 if (usage.value & C2MemoryUsage::CPU_READ) {
1077 config->mInputFormat->setInt32("using-sw-read-often", true);
1078 }
1079 if (config->mISConfig) {
1080 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1081 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1082 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001083 }
1084
1085 // NOTE: we don't blindly use client specified input size if specified as clients
1086 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1087 // client specified size is only used to ask for bigger buffers than component suggested
1088 // size.
1089 int32_t clientInputSize = 0;
1090 bool clientSpecifiedInputSize =
1091 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1092 // TEMP: enforce minimum buffer size of 1MB for video decoders
1093 // and 16K / 4K for audio encoders/decoders
1094 if (maxInputSize.value == 0) {
1095 if (config->mDomain & Config::IS_AUDIO) {
1096 maxInputSize.value = encoder ? 16384 : 4096;
1097 } else if (!encoder) {
1098 maxInputSize.value = 1048576u;
1099 }
1100 }
1101
1102 // verify that CSD fits into this size (if defined)
1103 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1104 sp<ABuffer> csd;
1105 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1106 if (csd && csd->size() > maxInputSize.value) {
1107 maxInputSize.value = csd->size();
1108 }
1109 }
1110 }
1111
1112 // TODO: do this based on component requiring linear allocator for input
1113 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1114 if (clientSpecifiedInputSize) {
1115 // Warn that we're overriding client's max input size if necessary.
1116 if ((uint32_t)clientInputSize < maxInputSize.value) {
1117 ALOGD("client requested max input size %d, which is smaller than "
1118 "what component recommended (%u); overriding with component "
1119 "recommendation.", clientInputSize, maxInputSize.value);
1120 ALOGW("This behavior is subject to change. It is recommended that "
1121 "app developers double check whether the requested "
1122 "max input size is in reasonable range.");
1123 } else {
1124 maxInputSize.value = clientInputSize;
1125 }
1126 }
1127 // Pass max input size on input format to the buffer channel (if supplied by the
1128 // component or by a default)
1129 if (maxInputSize.value) {
1130 config->mInputFormat->setInt32(
1131 KEY_MAX_INPUT_SIZE,
1132 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1133 }
1134 }
1135
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001136 int32_t clientPrepend;
1137 if ((config->mDomain & Config::IS_VIDEO)
1138 && (config->mDomain & Config::IS_ENCODER)
1139 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1140 && clientPrepend
1141 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1142 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1143 return BAD_VALUE;
1144 }
1145
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001146 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001147 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1148 // propagate HDR static info to output format for both encoders and decoders
1149 // if component supports this info, we will update from component, but only the raw port,
1150 // so don't propagate if component already filled it in.
1151 sp<ABuffer> hdrInfo;
1152 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1153 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1154 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1155 }
1156
1157 // Set desired color format from configuration parameter
1158 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001159 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1160 format = defaultColorFormat;
1161 }
1162 if (config->mDomain & Config::IS_ENCODER) {
1163 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001164 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1165 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001166 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001167 } else {
1168 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001169 }
1170 }
1171
1172 // propagate encoder delay and padding to output format
1173 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1174 int delay = 0;
1175 if (msg->findInt32("encoder-delay", &delay)) {
1176 config->mOutputFormat->setInt32("encoder-delay", delay);
1177 }
1178 int padding = 0;
1179 if (msg->findInt32("encoder-padding", &padding)) {
1180 config->mOutputFormat->setInt32("encoder-padding", padding);
1181 }
1182 }
1183
1184 // set channel-mask
1185 if (config->mDomain & Config::IS_AUDIO) {
1186 int32_t mask;
1187 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1188 if (config->mDomain & Config::IS_ENCODER) {
1189 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1190 } else {
1191 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1192 }
1193 }
1194 }
1195
Wonsik Kim58d83332021-02-07 22:19:56 -08001196 std::unique_ptr<C2Param> colorTransferRequestParam;
1197 for (std::unique_ptr<C2Param> &param : params) {
1198 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1199 ALOGI("found color transfer request param");
1200 colorTransferRequestParam = std::move(param);
1201 }
1202 }
1203 int32_t colorTransferRequest = 0;
1204 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1205 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1206 colorTransferRequest = 0;
1207 }
1208
1209 if (colorTransferRequest != 0) {
1210 if (colorTransferRequestParam && *colorTransferRequestParam) {
1211 C2StreamColorAspectsInfo::output *info =
1212 static_cast<C2StreamColorAspectsInfo::output *>(
1213 colorTransferRequestParam.get());
1214 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1215 colorTransferRequest = 0;
1216 }
1217 } else {
1218 colorTransferRequest = 0;
1219 }
1220 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1221 }
1222
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001223 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1224 // Need to get stride/vstride
1225 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1226 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1227 // TODO: retrieve these values without allocating a buffer.
1228 // Currently allocating a buffer is necessary to retrieve the layout.
1229 int64_t blockUsage =
1230 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1231 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1232 width, height, pixelFormat, blockUsage, {comp->getName()});
1233 sp<GraphicBlockBuffer> buffer;
1234 if (block) {
1235 buffer = GraphicBlockBuffer::Allocate(
1236 config->mInputFormat,
1237 block,
1238 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1239 } else {
1240 ALOGD("Failed to allocate a graphic block "
1241 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1242 width, height, pixelFormat, (long long)blockUsage);
1243 // This means that byte buffer mode is not supported in this configuration
1244 // anyway. Skip setting stride/vstride to input format.
1245 }
1246 if (buffer) {
1247 sp<ABuffer> imageData = buffer->getImageData();
1248 MediaImage2 *img = nullptr;
1249 if (imageData && imageData->data()
1250 && imageData->size() >= sizeof(MediaImage2)) {
1251 img = (MediaImage2*)imageData->data();
1252 }
1253 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1254 int32_t stride = img->mPlane[0].mRowInc;
1255 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1256 if (img->mNumPlanes > 1 && stride > 0) {
1257 int64_t offsetDelta =
1258 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1259 if (offsetDelta % stride == 0) {
1260 int32_t vstride = int32_t(offsetDelta / stride);
1261 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1262 } else {
1263 ALOGD("Cannot report accurate slice height: "
1264 "offsetDelta = %lld stride = %d",
1265 (long long)offsetDelta, stride);
1266 }
1267 }
1268 }
1269 }
1270 }
1271 }
1272
1273 ALOGD("setup formats input: %s",
1274 config->mInputFormat->debugString().c_str());
1275 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001276 config->mOutputFormat->debugString().c_str());
1277 return OK;
1278 };
1279 if (tryAndReportOnError(doConfig) != OK) {
1280 return;
1281 }
1282
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001283 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1284 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001285
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001286 config->queryConfiguration(comp);
1287
Pawin Vongmasa36653902018-11-15 00:10:25 -08001288 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1289}
1290
1291void CCodec::initiateCreateInputSurface() {
1292 status_t err = [this] {
1293 Mutexed<State>::Locked state(mState);
1294 if (state->get() != ALLOCATED) {
1295 return UNKNOWN_ERROR;
1296 }
1297 // TODO: read it from intf() properly.
1298 if (state->comp->getName().find("encoder") == std::string::npos) {
1299 return INVALID_OPERATION;
1300 }
1301 return OK;
1302 }();
1303 if (err != OK) {
1304 mCallback->onInputSurfaceCreationFailed(err);
1305 return;
1306 }
1307
1308 (new AMessage(kWhatCreateInputSurface, this))->post();
1309}
1310
Lajos Molnar47118272019-01-31 16:28:04 -08001311sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1312 using namespace android::hardware::media::omx::V1_0;
1313 using namespace android::hardware::media::omx::V1_0::utils;
1314 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1315 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1316 android::sp<IOmx> omx = IOmx::getService();
1317 typedef android::hardware::graphics::bufferqueue::V1_0::
1318 IGraphicBufferProducer HGraphicBufferProducer;
1319 typedef android::hardware::media::omx::V1_0::
1320 IGraphicBufferSource HGraphicBufferSource;
1321 OmxStatus s;
1322 android::sp<HGraphicBufferProducer> gbp;
1323 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001324
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001325 using ::android::hardware::Return;
1326 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001327 [&s, &gbp, &gbs](
1328 OmxStatus status,
1329 const android::sp<HGraphicBufferProducer>& producer,
1330 const android::sp<HGraphicBufferSource>& source) {
1331 s = status;
1332 gbp = producer;
1333 gbs = source;
1334 });
1335 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001336 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001337 }
1338
1339 return nullptr;
1340}
1341
1342sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1343 sp<PersistentSurface> surface(CreateInputSurface());
1344
1345 if (surface == nullptr) {
1346 surface = CreateOmxInputSurface();
1347 }
1348
1349 return surface;
1350}
1351
Pawin Vongmasa36653902018-11-15 00:10:25 -08001352void CCodec::createInputSurface() {
1353 status_t err;
1354 sp<IGraphicBufferProducer> bufferProducer;
1355
1356 sp<AMessage> inputFormat;
1357 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001358 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001359 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001360 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1361 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001362 inputFormat = config->mInputFormat;
1363 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001364 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001365 }
1366
Lajos Molnar47118272019-01-31 16:28:04 -08001367 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001368 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1369 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1370 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001371
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001372 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001373 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1374 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001375 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001376 inputSurface));
1377 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001378 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001379 int32_t width = 0;
1380 (void)outputFormat->findInt32("width", &width);
1381 int32_t height = 0;
1382 (void)outputFormat->findInt32("height", &height);
1383 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001384 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001385 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001386 } else {
1387 ALOGE("Corrupted input surface");
1388 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1389 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001390 }
1391
1392 if (err != OK) {
1393 ALOGE("Failed to set up input surface: %d", err);
1394 mCallback->onInputSurfaceCreationFailed(err);
1395 return;
1396 }
1397
1398 mCallback->onInputSurfaceCreated(
1399 inputFormat,
1400 outputFormat,
1401 new BufferProducerWrapper(bufferProducer));
1402}
1403
1404status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001405 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1406 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001407 config->mUsingSurface = true;
1408
1409 // we are now using surface - apply default color aspects to input format - as well as
1410 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001411 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001412 ALOGD("input format %s to %s",
1413 inputFormatChanged ? "changed" : "unchanged",
1414 config->mInputFormat->debugString().c_str());
1415
1416 // configure dataspace
1417 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1418 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1419 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1420 surface->setDataSpace(dataSpace);
1421
1422 status_t err = mChannel->setInputSurface(surface);
1423 if (err != OK) {
1424 // undo input format update
1425 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001426 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001427 return err;
1428 }
1429 config->mInputSurface = surface;
1430
1431 if (config->mISConfig) {
1432 surface->configure(*config->mISConfig);
1433 } else {
1434 ALOGD("ISConfig: no configuration");
1435 }
1436
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001437 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001438}
1439
1440void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1441 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1442 msg->setObject("surface", surface);
1443 msg->post();
1444}
1445
1446void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1447 sp<AMessage> inputFormat;
1448 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001449 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001450 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001451 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1452 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001453 inputFormat = config->mInputFormat;
1454 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001455 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001456 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001457 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1458 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1459 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1460 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001461 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1462 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1463 if (err != OK) {
1464 ALOGE("Failed to set up input surface: %d", err);
1465 mCallback->onInputSurfaceDeclined(err);
1466 return;
1467 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001468 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001469 int32_t width = 0;
1470 (void)outputFormat->findInt32("width", &width);
1471 int32_t height = 0;
1472 (void)outputFormat->findInt32("height", &height);
1473 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001474 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001475 if (err != OK) {
1476 ALOGE("Failed to set up input surface: %d", err);
1477 mCallback->onInputSurfaceDeclined(err);
1478 return;
1479 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001480 } else {
1481 ALOGE("Failed to set input surface: Corrupted surface.");
1482 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1483 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001484 }
1485 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1486}
1487
1488void CCodec::initiateStart() {
1489 auto setStarting = [this] {
1490 Mutexed<State>::Locked state(mState);
1491 if (state->get() != ALLOCATED) {
1492 return UNKNOWN_ERROR;
1493 }
1494 state->set(STARTING);
1495 return OK;
1496 };
1497 if (tryAndReportOnError(setStarting) != OK) {
1498 return;
1499 }
1500
1501 (new AMessage(kWhatStart, this))->post();
1502}
1503
1504void CCodec::start() {
1505 std::shared_ptr<Codec2Client::Component> comp;
1506 auto checkStarting = [this, &comp] {
1507 Mutexed<State>::Locked state(mState);
1508 if (state->get() != STARTING) {
1509 return UNKNOWN_ERROR;
1510 }
1511 comp = state->comp;
1512 return OK;
1513 };
1514 if (tryAndReportOnError(checkStarting) != OK) {
1515 return;
1516 }
1517
1518 c2_status_t err = comp->start();
1519 if (err != C2_OK) {
1520 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1521 ACTION_CODE_FATAL);
1522 return;
1523 }
1524 sp<AMessage> inputFormat;
1525 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001526 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001527 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001528 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001529 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1530 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001531 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001532 // start triggers format dup
1533 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001534 if (config->mInputSurface) {
1535 err2 = config->mInputSurface->start();
1536 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001537 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001538 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001539 if (err2 != OK) {
1540 mCallback->onError(err2, ACTION_CODE_FATAL);
1541 return;
1542 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001543 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001544 if (err2 != OK) {
1545 mCallback->onError(err2, ACTION_CODE_FATAL);
1546 return;
1547 }
1548
1549 auto setRunning = [this] {
1550 Mutexed<State>::Locked state(mState);
1551 if (state->get() != STARTING) {
1552 return UNKNOWN_ERROR;
1553 }
1554 state->set(RUNNING);
1555 return OK;
1556 };
1557 if (tryAndReportOnError(setRunning) != OK) {
1558 return;
1559 }
1560 mCallback->onStartCompleted();
1561
1562 (void)mChannel->requestInitialInputBuffers();
1563}
1564
1565void CCodec::initiateShutdown(bool keepComponentAllocated) {
1566 if (keepComponentAllocated) {
1567 initiateStop();
1568 } else {
1569 initiateRelease();
1570 }
1571}
1572
1573void CCodec::initiateStop() {
1574 {
1575 Mutexed<State>::Locked state(mState);
1576 if (state->get() == ALLOCATED
1577 || state->get() == RELEASED
1578 || state->get() == STOPPING
1579 || state->get() == RELEASING) {
1580 // We're already stopped, released, or doing it right now.
1581 state.unlock();
1582 mCallback->onStopCompleted();
1583 state.lock();
1584 return;
1585 }
1586 state->set(STOPPING);
1587 }
1588
Wonsik Kim936a89c2020-05-08 16:07:50 -07001589 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001590 (new AMessage(kWhatStop, this))->post();
1591}
1592
1593void CCodec::stop() {
1594 std::shared_ptr<Codec2Client::Component> comp;
1595 {
1596 Mutexed<State>::Locked state(mState);
1597 if (state->get() == RELEASING) {
1598 state.unlock();
1599 // We're already stopped or release is in progress.
1600 mCallback->onStopCompleted();
1601 state.lock();
1602 return;
1603 } else if (state->get() != STOPPING) {
1604 state.unlock();
1605 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1606 state.lock();
1607 return;
1608 }
1609 comp = state->comp;
1610 }
1611 status_t err = comp->stop();
1612 if (err != C2_OK) {
1613 // TODO: convert err into status_t
1614 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1615 }
1616
1617 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001618 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1619 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001620 if (config->mInputSurface) {
1621 config->mInputSurface->disconnect();
1622 config->mInputSurface = nullptr;
1623 }
1624 }
1625 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001626 Mutexed<State>::Locked state(mState);
1627 if (state->get() == STOPPING) {
1628 state->set(ALLOCATED);
1629 }
1630 }
1631 mCallback->onStopCompleted();
1632}
1633
1634void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001635 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001636 {
1637 Mutexed<State>::Locked state(mState);
1638 if (state->get() == RELEASED || state->get() == RELEASING) {
1639 // We're already released or doing it right now.
1640 if (sendCallback) {
1641 state.unlock();
1642 mCallback->onReleaseCompleted();
1643 state.lock();
1644 }
1645 return;
1646 }
1647 if (state->get() == ALLOCATING) {
1648 state->set(RELEASING);
1649 // With the altered state allocate() would fail and clean up.
1650 if (sendCallback) {
1651 state.unlock();
1652 mCallback->onReleaseCompleted();
1653 state.lock();
1654 }
1655 return;
1656 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001657 if (state->get() == STARTING
1658 || state->get() == RUNNING
1659 || state->get() == STOPPING) {
1660 // Input surface may have been started, so clean up is needed.
1661 clearInputSurfaceIfNeeded = true;
1662 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001663 state->set(RELEASING);
1664 }
1665
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001666 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001667 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1668 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001669 if (config->mInputSurface) {
1670 config->mInputSurface->disconnect();
1671 config->mInputSurface = nullptr;
1672 }
1673 }
1674
Wonsik Kim936a89c2020-05-08 16:07:50 -07001675 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001676 // thiz holds strong ref to this while the thread is running.
1677 sp<CCodec> thiz(this);
1678 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1679}
1680
1681void CCodec::release(bool sendCallback) {
1682 std::shared_ptr<Codec2Client::Component> comp;
1683 {
1684 Mutexed<State>::Locked state(mState);
1685 if (state->get() == RELEASED) {
1686 if (sendCallback) {
1687 state.unlock();
1688 mCallback->onReleaseCompleted();
1689 state.lock();
1690 }
1691 return;
1692 }
1693 comp = state->comp;
1694 }
1695 comp->release();
1696
1697 {
1698 Mutexed<State>::Locked state(mState);
1699 state->set(RELEASED);
1700 state->comp.reset();
1701 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001702 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001703 if (sendCallback) {
1704 mCallback->onReleaseCompleted();
1705 }
1706}
1707
1708status_t CCodec::setSurface(const sp<Surface> &surface) {
1709 return mChannel->setSurface(surface);
1710}
1711
1712void CCodec::signalFlush() {
1713 status_t err = [this] {
1714 Mutexed<State>::Locked state(mState);
1715 if (state->get() == FLUSHED) {
1716 return ALREADY_EXISTS;
1717 }
1718 if (state->get() != RUNNING) {
1719 return UNKNOWN_ERROR;
1720 }
1721 state->set(FLUSHING);
1722 return OK;
1723 }();
1724 switch (err) {
1725 case ALREADY_EXISTS:
1726 mCallback->onFlushCompleted();
1727 return;
1728 case OK:
1729 break;
1730 default:
1731 mCallback->onError(err, ACTION_CODE_FATAL);
1732 return;
1733 }
1734
1735 mChannel->stop();
1736 (new AMessage(kWhatFlush, this))->post();
1737}
1738
1739void CCodec::flush() {
1740 std::shared_ptr<Codec2Client::Component> comp;
1741 auto checkFlushing = [this, &comp] {
1742 Mutexed<State>::Locked state(mState);
1743 if (state->get() != FLUSHING) {
1744 return UNKNOWN_ERROR;
1745 }
1746 comp = state->comp;
1747 return OK;
1748 };
1749 if (tryAndReportOnError(checkFlushing) != OK) {
1750 return;
1751 }
1752
1753 std::list<std::unique_ptr<C2Work>> flushedWork;
1754 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1755 {
1756 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1757 flushedWork.splice(flushedWork.end(), *queue);
1758 }
1759 if (err != C2_OK) {
1760 // TODO: convert err into status_t
1761 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1762 }
1763
1764 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001765
1766 {
1767 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001768 if (state->get() == FLUSHING) {
1769 state->set(FLUSHED);
1770 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001771 }
1772 mCallback->onFlushCompleted();
1773}
1774
1775void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001776 std::shared_ptr<Codec2Client::Component> comp;
1777 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001778 Mutexed<State>::Locked state(mState);
1779 if (state->get() != FLUSHED) {
1780 return UNKNOWN_ERROR;
1781 }
1782 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001783 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001784 return OK;
1785 };
1786 if (tryAndReportOnError(setResuming) != OK) {
1787 return;
1788 }
1789
Wonsik Kime75a5da2020-02-14 17:29:03 -08001790 {
1791 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1792 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001793 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001794 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001795 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001796 }
1797
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001798 (void)mChannel->start(nullptr, nullptr, [&]{
1799 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1800 const std::unique_ptr<Config> &config = *configLocked;
1801 return config->mBuffersBoundToCodec;
1802 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001803
1804 {
1805 Mutexed<State>::Locked state(mState);
1806 if (state->get() != RESUMING) {
1807 state.unlock();
1808 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1809 state.lock();
1810 return;
1811 }
1812 state->set(RUNNING);
1813 }
1814
1815 (void)mChannel->requestInitialInputBuffers();
1816}
1817
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001818void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001819 std::shared_ptr<Codec2Client::Component> comp;
1820 auto checkState = [this, &comp] {
1821 Mutexed<State>::Locked state(mState);
1822 if (state->get() == RELEASED) {
1823 return INVALID_OPERATION;
1824 }
1825 comp = state->comp;
1826 return OK;
1827 };
1828 if (tryAndReportOnError(checkState) != OK) {
1829 return;
1830 }
1831
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001832 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1833 // the behavior here.
1834 sp<AMessage> params = msg;
1835 int32_t bitrate;
1836 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1837 params = msg->dup();
1838 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1839 }
1840
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001841 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1842 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001843
1844 /**
1845 * Handle input surface parameters
1846 */
1847 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001848 && (config->mDomain & Config::IS_ENCODER)
1849 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001850 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001851
1852 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1853 config->mISConfig->mStopped = false;
1854 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1855 config->mISConfig->mStopped = true;
1856 }
1857
1858 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001859 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001860 config->mISConfig->mSuspended = value;
1861 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001862 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001863 }
1864
1865 (void)config->mInputSurface->configure(*config->mISConfig);
1866 if (config->mISConfig->mStopped) {
1867 config->mInputFormat->setInt64(
1868 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1869 }
1870 }
1871
1872 std::vector<std::unique_ptr<C2Param>> configUpdate;
1873 (void)config->getConfigUpdateFromSdkParams(
1874 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1875 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1876 // Parameter synchronization is not defined when using input surface. For now, route
1877 // these directly to the component.
1878 if (config->mInputSurface == nullptr
1879 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1880 || comp->getName().find("c2.android.") == 0)) {
1881 mChannel->setParameters(configUpdate);
1882 } else {
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001883 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001884 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001885 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001886 }
1887}
1888
1889void CCodec::signalEndOfInputStream() {
1890 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1891}
1892
1893void CCodec::signalRequestIDRFrame() {
1894 std::shared_ptr<Codec2Client::Component> comp;
1895 {
1896 Mutexed<State>::Locked state(mState);
1897 if (state->get() == RELEASED) {
1898 ALOGD("no IDR request sent since component is released");
1899 return;
1900 }
1901 comp = state->comp;
1902 }
1903 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001904 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1905 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001906 std::vector<std::unique_ptr<C2Param>> params;
1907 params.push_back(
1908 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1909 config->setParameters(comp, params, C2_MAY_BLOCK);
1910}
1911
Wonsik Kimab34ed62019-01-31 15:28:46 -08001912void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001913 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001914 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1915 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001916 }
1917 (new AMessage(kWhatWorkDone, this))->post();
1918}
1919
Wonsik Kimab34ed62019-01-31 15:28:46 -08001920void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1921 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001922 if (arrayIndex == 0) {
1923 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001924 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1925 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001926 if (config->mInputSurface) {
1927 config->mInputSurface->onInputBufferDone(frameIndex);
1928 }
1929 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001930}
1931
1932void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1933 TimePoint now = std::chrono::steady_clock::now();
1934 CCodecWatchdog::getInstance()->watch(this);
1935 switch (msg->what()) {
1936 case kWhatAllocate: {
1937 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001938 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001939 sp<RefBase> obj;
1940 CHECK(msg->findObject("codecInfo", &obj));
1941 allocate((MediaCodecInfo *)obj.get());
1942 break;
1943 }
1944 case kWhatConfigure: {
1945 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001946 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001947 sp<AMessage> format;
1948 CHECK(msg->findMessage("format", &format));
1949 configure(format);
1950 break;
1951 }
1952 case kWhatStart: {
1953 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001954 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001955 start();
1956 break;
1957 }
1958 case kWhatStop: {
1959 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001960 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001961 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001962 break;
1963 }
1964 case kWhatFlush: {
1965 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001966 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001967 flush();
1968 break;
1969 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001970 case kWhatRelease: {
1971 mChannel->release();
1972 mClient.reset();
1973 mClientListener.reset();
1974 break;
1975 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001976 case kWhatCreateInputSurface: {
1977 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001978 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001979 createInputSurface();
1980 break;
1981 }
1982 case kWhatSetInputSurface: {
1983 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001984 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001985 sp<RefBase> obj;
1986 CHECK(msg->findObject("surface", &obj));
1987 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1988 setInputSurface(surface);
1989 break;
1990 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001991 case kWhatWorkDone: {
1992 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001993 bool shouldPost = false;
1994 {
1995 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1996 if (queue->empty()) {
1997 break;
1998 }
1999 work.swap(queue->front());
2000 queue->pop_front();
2001 shouldPost = !queue->empty();
2002 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002003 if (shouldPost) {
2004 (new AMessage(kWhatWorkDone, this))->post();
2005 }
2006
Pawin Vongmasa36653902018-11-15 00:10:25 -08002007 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002008 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2009 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002010 Config::Watcher<C2StreamInitDataInfo::output> initData =
2011 config->watch<C2StreamInitDataInfo::output>();
2012 if (!work->worklets.empty()
2013 && (work->worklets.front()->output.flags
2014 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
2015
2016 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002017 std::vector<std::unique_ptr<C2Param>> updates;
2018 for (const std::unique_ptr<C2Param> &param
2019 : work->worklets.front()->output.configUpdate) {
2020 updates.push_back(C2Param::Copy(*param));
2021 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002022 unsigned stream = 0;
2023 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2024 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2025 // move all info into output-stream #0 domain
2026 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
2027 }
George Burgess IVc813a592020-02-22 22:54:44 -08002028
2029 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2030 // for now only do the first block
2031 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002032 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2033 // block.crop().left, block.crop().top,
2034 // block.crop().width, block.crop().height,
2035 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08002036 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08002037 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
2038 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07002039 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002040 }
2041 ++stream;
2042 }
2043
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002044 sp<AMessage> outputFormat = config->mOutputFormat;
2045 config->updateConfiguration(updates, config->mOutputDomain);
2046 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002047
2048 // copy standard infos to graphic buffers if not already present (otherwise, we
2049 // may overwrite the actual intermediate value with a final value)
2050 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07002051 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002052 C2StreamRotationInfo::output::PARAM_TYPE,
2053 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2054 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2055 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08002056 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08002057 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2058 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2059 };
2060 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2061 if (buf->data().graphicBlocks().size()) {
2062 for (C2Param::Index ix : stdGfxInfos) {
2063 if (!buf->hasInfo(ix)) {
2064 const C2Param *param =
2065 config->getConfigParameterValue(ix.withStream(stream));
2066 if (param) {
2067 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2068 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2069 }
2070 }
2071 }
2072 }
2073 ++stream;
2074 }
2075 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002076 if (config->mInputSurface) {
2077 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2078 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002079 mChannel->onWorkDone(
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002080 std::move(work), config->mOutputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002081 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002082 break;
2083 }
2084 case kWhatWatch: {
2085 // watch message already posted; no-op.
2086 break;
2087 }
2088 default: {
2089 ALOGE("unrecognized message");
2090 break;
2091 }
2092 }
2093 setDeadline(TimePoint::max(), 0ms, "none");
2094}
2095
2096void CCodec::setDeadline(
2097 const TimePoint &now,
2098 const std::chrono::milliseconds &timeout,
2099 const char *name) {
2100 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2101 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2102 deadline->set(now + (timeout * mult), name);
2103}
2104
2105void CCodec::initiateReleaseIfStuck() {
2106 std::string name;
2107 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002108 {
2109 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002110 if (deadline->get() < std::chrono::steady_clock::now()) {
2111 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002112 }
2113 if (deadline->get() != TimePoint::max()) {
2114 pendingDeadline = true;
2115 }
2116 }
2117 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002118 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2119 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2120 if (elapsed >= kWorkDurationThreshold) {
2121 name = "queue";
2122 }
2123 if (elapsed > 0s) {
2124 pendingDeadline = true;
2125 }
2126 }
2127 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002128 // We're not stuck.
2129 if (pendingDeadline) {
2130 // If we are not stuck yet but still has deadline coming up,
2131 // post watch message to check back later.
2132 (new AMessage(kWhatWatch, this))->post();
2133 }
2134 return;
2135 }
2136
2137 ALOGW("previous call to %s exceeded timeout", name.c_str());
2138 initiateRelease(false);
2139 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2140}
2141
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002142// static
2143PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002144 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002145 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002146 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002147 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2148 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002149 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002150 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2151 sp<IGraphicBufferProducer> gbp;
2152 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2153 status_t err = gbs->initCheck();
2154 if (err != OK) {
2155 ALOGE("Failed to create persistent input surface: error %d", err);
2156 return nullptr;
2157 }
2158 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002159 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002160 } else {
2161 return nullptr;
2162 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002163 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002164 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002165 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002166 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002167 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002168}
2169
Wonsik Kimffb889a2020-05-28 11:32:25 -07002170class IntfCache {
2171public:
2172 IntfCache() = default;
2173
2174 status_t init(const std::string &name) {
2175 std::shared_ptr<Codec2Client::Interface> intf{
2176 Codec2Client::CreateInterfaceByName(name.c_str())};
2177 if (!intf) {
2178 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2179 mInitStatus = NO_INIT;
2180 return NO_INIT;
2181 }
2182 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2183 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2184 C2ParamField{&sUsage, &sUsage.value}));
2185 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2186 if (err != C2_OK) {
2187 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2188 name.c_str(), err);
2189 mFields[0].status = err;
2190 }
2191 std::vector<std::unique_ptr<C2Param>> params;
2192 err = intf->query(
2193 {&mApiFeatures},
2194 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2195 C2_MAY_BLOCK,
2196 &params);
2197 if (err != C2_OK && err != C2_BAD_INDEX) {
2198 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2199 name.c_str(), err);
2200 }
2201 while (!params.empty()) {
2202 C2Param *param = params.back().release();
2203 params.pop_back();
2204 if (!param) {
2205 continue;
2206 }
2207 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2208 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002209 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002210 }
2211 }
2212 mInitStatus = OK;
2213 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002214 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002215
2216 status_t initCheck() const { return mInitStatus; }
2217
2218 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2219 CHECK_EQ(1u, mFields.size());
2220 return mFields[0];
2221 }
2222
2223 const C2ApiFeaturesSetting &getApiFeatures() const {
2224 return mApiFeatures;
2225 }
2226
2227 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2228 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2229 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2230 C2PortAllocatorsTuning::input::AllocUnique(0);
2231 param->invalidate();
2232 return param;
2233 }();
2234 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2235 }
2236
2237private:
2238 status_t mInitStatus{NO_INIT};
2239
2240 std::vector<C2FieldSupportedValuesQuery> mFields;
2241 C2ApiFeaturesSetting mApiFeatures;
2242 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2243};
2244
2245static const IntfCache &GetIntfCache(const std::string &name) {
2246 static IntfCache sNullIntfCache;
2247 static std::mutex sMutex;
2248 static std::map<std::string, IntfCache> sCache;
2249 std::unique_lock<std::mutex> lock{sMutex};
2250 auto it = sCache.find(name);
2251 if (it == sCache.end()) {
2252 lock.unlock();
2253 IntfCache intfCache;
2254 status_t err = intfCache.init(name);
2255 if (err != OK) {
2256 return sNullIntfCache;
2257 }
2258 lock.lock();
2259 it = sCache.insert({name, std::move(intfCache)}).first;
2260 }
2261 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002262}
2263
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002264static status_t GetCommonAllocatorIds(
2265 const std::vector<std::string> &names,
2266 C2Allocator::type_t type,
2267 std::set<C2Allocator::id_t> *ids) {
2268 int poolMask = GetCodec2PoolMask();
2269 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2270 C2Allocator::id_t defaultAllocatorId =
2271 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2272
2273 ids->clear();
2274 if (names.empty()) {
2275 return OK;
2276 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002277 bool firstIteration = true;
2278 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002279 const IntfCache &intfCache = GetIntfCache(name);
2280 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002281 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002282 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002283 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002284 if (firstIteration) {
2285 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002286 if (allocators && allocators.flexCount() > 0) {
2287 ids->insert(allocators.m.values,
2288 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002289 }
2290 if (ids->empty()) {
2291 // The component does not advertise allocators. Use default.
2292 ids->insert(defaultAllocatorId);
2293 }
2294 continue;
2295 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002296 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002297 if (allocators && allocators.flexCount() > 0) {
2298 filtered = true;
2299 for (auto it = ids->begin(); it != ids->end(); ) {
2300 bool found = false;
2301 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2302 if (allocators.m.values[j] == *it) {
2303 found = true;
2304 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002305 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002306 }
2307 if (found) {
2308 ++it;
2309 } else {
2310 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002311 }
2312 }
2313 }
2314 if (!filtered) {
2315 // The component does not advertise supported allocators. Use default.
2316 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2317 if (ids->size() != (containsDefault ? 1 : 0)) {
2318 ids->clear();
2319 if (containsDefault) {
2320 ids->insert(defaultAllocatorId);
2321 }
2322 }
2323 }
2324 }
2325 // Finally, filter with pool masks
2326 for (auto it = ids->begin(); it != ids->end(); ) {
2327 if ((poolMask >> *it) & 1) {
2328 ++it;
2329 } else {
2330 it = ids->erase(it);
2331 }
2332 }
2333 return OK;
2334}
2335
2336static status_t CalculateMinMaxUsage(
2337 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2338 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2339 *minUsage = 0;
2340 *maxUsage = ~0ull;
2341 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002342 const IntfCache &intfCache = GetIntfCache(name);
2343 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002344 continue;
2345 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002346 const C2FieldSupportedValuesQuery &usageSupportedValues =
2347 intfCache.getUsageSupportedValues();
2348 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002349 continue;
2350 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002351 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002352 if (supported.type != C2FieldSupportedValues::FLAGS) {
2353 continue;
2354 }
2355 if (supported.values.empty()) {
2356 *maxUsage = 0;
2357 continue;
2358 }
2359 *minUsage |= supported.values[0].u64;
2360 int64_t currentMaxUsage = 0;
2361 for (const C2Value::Primitive &flags : supported.values) {
2362 currentMaxUsage |= flags.u64;
2363 }
2364 *maxUsage &= currentMaxUsage;
2365 }
2366 return OK;
2367}
2368
2369// static
2370status_t CCodec::CanFetchLinearBlock(
2371 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002372 for (const std::string &name : names) {
2373 const IntfCache &intfCache = GetIntfCache(name);
2374 if (intfCache.initCheck() != OK) {
2375 continue;
2376 }
2377 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2378 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2379 *isCompatible = false;
2380 return OK;
2381 }
2382 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002383 uint64_t minUsage = usage.expected;
2384 uint64_t maxUsage = ~0ull;
2385 std::set<C2Allocator::id_t> allocators;
2386 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2387 if (allocators.empty()) {
2388 *isCompatible = false;
2389 return OK;
2390 }
2391 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2392 *isCompatible = ((maxUsage & minUsage) == minUsage);
2393 return OK;
2394}
2395
2396static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2397 static std::mutex sMutex{};
2398 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2399 std::unique_lock<std::mutex> lock{sMutex};
2400 std::shared_ptr<C2BlockPool> pool;
2401 auto it = sPools.find(allocId);
2402 if (it == sPools.end()) {
2403 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2404 if (err == OK) {
2405 sPools.emplace(allocId, pool);
2406 } else {
2407 pool.reset();
2408 }
2409 } else {
2410 pool = it->second;
2411 }
2412 return pool;
2413}
2414
2415// static
2416std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2417 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
2418 uint64_t minUsage = usage.expected;
2419 uint64_t maxUsage = ~0ull;
2420 std::set<C2Allocator::id_t> allocators;
2421 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2422 if (allocators.empty()) {
2423 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2424 }
2425 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2426 if ((maxUsage & minUsage) != minUsage) {
2427 allocators.clear();
2428 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2429 }
2430 std::shared_ptr<C2LinearBlock> block;
2431 for (C2Allocator::id_t allocId : allocators) {
2432 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2433 if (!pool) {
2434 continue;
2435 }
2436 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2437 if (err != C2_OK || !block) {
2438 block.reset();
2439 continue;
2440 }
2441 break;
2442 }
2443 return block;
2444}
2445
2446// static
2447status_t CCodec::CanFetchGraphicBlock(
2448 const std::vector<std::string> &names, bool *isCompatible) {
2449 uint64_t minUsage = 0;
2450 uint64_t maxUsage = ~0ull;
2451 std::set<C2Allocator::id_t> allocators;
2452 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2453 if (allocators.empty()) {
2454 *isCompatible = false;
2455 return OK;
2456 }
2457 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2458 *isCompatible = ((maxUsage & minUsage) == minUsage);
2459 return OK;
2460}
2461
2462// static
2463std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2464 int32_t width,
2465 int32_t height,
2466 int32_t format,
2467 uint64_t usage,
2468 const std::vector<std::string> &names) {
2469 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2470 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2471 ALOGD("Unrecognized pixel format: %d", format);
2472 return nullptr;
2473 }
2474 uint64_t minUsage = 0;
2475 uint64_t maxUsage = ~0ull;
2476 std::set<C2Allocator::id_t> allocators;
2477 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2478 if (allocators.empty()) {
2479 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2480 }
2481 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2482 minUsage |= usage;
2483 if ((maxUsage & minUsage) != minUsage) {
2484 allocators.clear();
2485 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2486 }
2487 std::shared_ptr<C2GraphicBlock> block;
2488 for (C2Allocator::id_t allocId : allocators) {
2489 std::shared_ptr<C2BlockPool> pool;
2490 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2491 if (err != C2_OK || !pool) {
2492 continue;
2493 }
2494 err = pool->fetchGraphicBlock(
2495 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2496 if (err != C2_OK || !block) {
2497 block.reset();
2498 continue;
2499 }
2500 break;
2501 }
2502 return block;
2503}
2504
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002505} // namespace android
2506