blob: c8a19945dbe8f5462f4898014787463f4a97a67f [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodec"
19#include <utils/Log.h>
20
21#include <sstream>
22#include <thread>
23
24#include <C2Config.h>
25#include <C2Debug.h>
26#include <C2ParamInternal.h>
27#include <C2PlatformSupport.h>
28
Pawin Vongmasa36653902018-11-15 00:10:25 -080029#include <android/IOMXBufferSource.h>
Pawin Vongmasabf69de92019-10-29 06:21:27 -070030#include <android/hardware/media/c2/1.0/IInputSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080031#include <android/hardware/media/omx/1.0/IGraphicBufferSource.h>
32#include <android/hardware/media/omx/1.0/IOmx.h>
33#include <android-base/stringprintf.h>
34#include <cutils/properties.h>
35#include <gui/IGraphicBufferProducer.h>
36#include <gui/Surface.h>
37#include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070038#include <media/omx/1.0/WOmxNode.h>
39#include <media/openmax/OMX_Core.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080040#include <media/openmax/OMX_IndexExt.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070041#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
42#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070043#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080044#include <media/stagefright/BufferProducerWrapper.h>
45#include <media/stagefright/MediaCodecConstants.h>
46#include <media/stagefright/PersistentSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080047
48#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080049#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070050#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080051#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080052#include "InputSurfaceWrapper.h"
53
54extern "C" android::PersistentSurface *CreateInputSurface();
55
56namespace android {
57
58using namespace std::chrono_literals;
59using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
60using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080061using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080062
Wonsik Kim9917d4a2019-10-24 12:56:38 -070063typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070064typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070065
Pawin Vongmasa36653902018-11-15 00:10:25 -080066namespace {
67
68class CCodecWatchdog : public AHandler {
69private:
70 enum {
71 kWhatWatch,
72 };
73 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
74
75public:
76 static sp<CCodecWatchdog> getInstance() {
77 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
78 static std::once_flag flag;
79 // Call Init() only once.
80 std::call_once(flag, Init, instance);
81 return instance;
82 }
83
84 ~CCodecWatchdog() = default;
85
86 void watch(sp<CCodec> codec) {
87 bool shouldPost = false;
88 {
89 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
90 // If a watch message is in flight, piggy-back this instance as well.
91 // Otherwise, post a new watch message.
92 shouldPost = codecs->empty();
93 codecs->emplace(codec);
94 }
95 if (shouldPost) {
96 ALOGV("posting watch message");
97 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
98 }
99 }
100
101protected:
102 void onMessageReceived(const sp<AMessage> &msg) {
103 switch (msg->what()) {
104 case kWhatWatch: {
105 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
106 ALOGV("watch for %zu codecs", codecs->size());
107 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
108 sp<CCodec> codec = it->promote();
109 if (codec == nullptr) {
110 continue;
111 }
112 codec->initiateReleaseIfStuck();
113 }
114 codecs->clear();
115 break;
116 }
117
118 default: {
119 TRESPASS("CCodecWatchdog: unrecognized message");
120 }
121 }
122 }
123
124private:
125 CCodecWatchdog() : mLooper(new ALooper) {}
126
127 static void Init(const sp<CCodecWatchdog> &thiz) {
128 ALOGV("Init");
129 thiz->mLooper->setName("CCodecWatchdog");
130 thiz->mLooper->registerHandler(thiz);
131 thiz->mLooper->start();
132 }
133
134 sp<ALooper> mLooper;
135
136 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
137};
138
139class C2InputSurfaceWrapper : public InputSurfaceWrapper {
140public:
141 explicit C2InputSurfaceWrapper(
142 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
143 mSurface(surface) {
144 }
145
146 ~C2InputSurfaceWrapper() override = default;
147
148 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
149 if (mConnection != nullptr) {
150 return ALREADY_EXISTS;
151 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800152 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800153 }
154
155 void disconnect() override {
156 if (mConnection != nullptr) {
157 mConnection->disconnect();
158 mConnection = nullptr;
159 }
160 }
161
162 status_t start() override {
163 // InputSurface does not distinguish started state
164 return OK;
165 }
166
167 status_t signalEndOfInputStream() override {
168 C2InputSurfaceEosTuning eos(true);
169 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800170 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800171 if (err != C2_OK) {
172 return UNKNOWN_ERROR;
173 }
174 return OK;
175 }
176
177 status_t configure(Config &config __unused) {
178 // TODO
179 return OK;
180 }
181
182private:
183 std::shared_ptr<Codec2Client::InputSurface> mSurface;
184 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
185};
186
187class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
188public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700189 typedef hardware::media::omx::V1_0::Status OmxStatus;
190
Pawin Vongmasa36653902018-11-15 00:10:25 -0800191 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700192 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800193 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700194 uint32_t height,
195 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800196 : mSource(source), mWidth(width), mHeight(height) {
197 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700198 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800199 }
200 ~GraphicBufferSourceWrapper() override = default;
201
202 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
203 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700204 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800205 mNode->setFrameSize(mWidth, mHeight);
206
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700207 // Usage is queried during configure(), so setting it beforehand.
208 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
209 (void)mNode->setParameter(
210 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
211 &usage, sizeof(usage));
212
Pawin Vongmasa36653902018-11-15 00:10:25 -0800213 // NOTE: we do not use/pass through color aspects from GraphicBufferSource as we
214 // communicate that directly to the component.
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700215 mSource->configure(
216 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800217 return OK;
218 }
219
220 void disconnect() override {
221 if (mNode == nullptr) {
222 return;
223 }
224 sp<IOMXBufferSource> source = mNode->getSource();
225 if (source == nullptr) {
226 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
227 return;
228 }
229 source->onOmxIdle();
230 source->onOmxLoaded();
231 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700232 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800233 }
234
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700235 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
236 if (status.isOk()) {
237 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
238 } else if (status.isDeadObject()) {
239 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800240 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700241 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800242 }
243
244 status_t start() override {
245 sp<IOMXBufferSource> source = mNode->getSource();
246 if (source == nullptr) {
247 return NO_INIT;
248 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900249
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800250 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800251 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900252
Wonsik Kim34d66012021-03-01 16:40:33 -0800253 OMX_PARAM_PORTDEFINITIONTYPE param;
254 param.nPortIndex = kPortIndexInput;
255 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
256 &param, sizeof(param));
257 if (err == OK) {
258 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900259 }
260
261 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800262 source->onInputBufferAdded(i);
263 }
264
265 source->onOmxExecuting();
266 return OK;
267 }
268
269 status_t signalEndOfInputStream() override {
270 return GetStatus(mSource->signalEndOfInputStream());
271 }
272
273 status_t configure(Config &config) {
274 std::stringstream status;
275 status_t err = OK;
276
277 // handle each configuration granually, in case we need to handle part of the configuration
278 // elsewhere
279
280 // TRICKY: we do not unset frame delay repeating
281 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
282 int64_t us = 1e6 / config.mMinFps + 0.5;
283 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
284 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
285 if (res != OK) {
286 status << " (=> " << asString(res) << ")";
287 err = res;
288 }
289 mConfig.mMinFps = config.mMinFps;
290 }
291
292 // pts gap
293 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
294 if (mNode != nullptr) {
295 OMX_PARAM_U32TYPE ptrGapParam = {};
296 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700297 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800298 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
299 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700300 // float -> uint32_t is undefined if the value is negative.
301 // First convert to int32_t to ensure the expected behavior.
302 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800303 (void)mNode->setParameter(
304 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
305 &ptrGapParam, sizeof(ptrGapParam));
306 }
307 }
308
309 // max fps
310 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700311 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800312 && config.mMaxFps != mConfig.mMaxFps) {
313 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
314 status << " maxFps=" << config.mMaxFps;
315 if (res != OK) {
316 status << " (=> " << asString(res) << ")";
317 err = res;
318 }
319 mConfig.mMaxFps = config.mMaxFps;
320 }
321
322 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
323 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
324 status << " timeOffset " << config.mTimeOffsetUs << "us";
325 if (res != OK) {
326 status << " (=> " << asString(res) << ")";
327 err = res;
328 }
329 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
330 }
331
332 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
333 status_t res =
334 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
335 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
336 if (res != OK) {
337 status << " (=> " << asString(res) << ")";
338 err = res;
339 }
340 mConfig.mCaptureFps = config.mCaptureFps;
341 mConfig.mCodedFps = config.mCodedFps;
342 }
343
344 if (config.mStartAtUs != mConfig.mStartAtUs
345 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
346 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
347 status << " start at " << config.mStartAtUs << "us";
348 if (res != OK) {
349 status << " (=> " << asString(res) << ")";
350 err = res;
351 }
352 mConfig.mStartAtUs = config.mStartAtUs;
353 mConfig.mStopped = config.mStopped;
354 }
355
356 // suspend-resume
357 if (config.mSuspended != mConfig.mSuspended) {
358 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
359 status << " " << (config.mSuspended ? "suspend" : "resume")
360 << " at " << config.mSuspendAtUs << "us";
361 if (res != OK) {
362 status << " (=> " << asString(res) << ")";
363 err = res;
364 }
365 mConfig.mSuspended = config.mSuspended;
366 mConfig.mSuspendAtUs = config.mSuspendAtUs;
367 }
368
369 if (config.mStopped != mConfig.mStopped && config.mStopped) {
370 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
371 status << " stop at " << config.mStopAtUs << "us";
372 if (res != OK) {
373 status << " (=> " << asString(res) << ")";
374 err = res;
375 } else {
376 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700377 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
378 [&res, &delayUs = config.mInputDelayUs](
379 auto status, auto stopTimeOffsetUs) {
380 res = static_cast<status_t>(status);
381 delayUs = stopTimeOffsetUs;
382 });
383 if (!trans.isOk()) {
384 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
385 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800386 if (res != OK) {
387 status << " (=> " << asString(res) << ")";
388 } else {
389 status << "=" << config.mInputDelayUs << "us";
390 }
391 mConfig.mInputDelayUs = config.mInputDelayUs;
392 }
393 mConfig.mStopAtUs = config.mStopAtUs;
394 mConfig.mStopped = config.mStopped;
395 }
396
397 // color aspects (android._color-aspects)
398
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700399 // consumer usage is queried earlier.
400
Wonsik Kimbd557932019-07-02 15:51:20 -0700401 if (status.str().empty()) {
402 ALOGD("ISConfig not changed");
403 } else {
404 ALOGD("ISConfig%s", status.str().c_str());
405 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800406 return err;
407 }
408
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700409 void onInputBufferDone(c2_cntr64_t index) override {
410 mNode->onInputBufferDone(index);
411 }
412
Pawin Vongmasa36653902018-11-15 00:10:25 -0800413private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700414 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800415 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700416 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800417 uint32_t mWidth;
418 uint32_t mHeight;
419 Config mConfig;
420};
421
422class Codec2ClientInterfaceWrapper : public C2ComponentStore {
423 std::shared_ptr<Codec2Client> mClient;
424
425public:
426 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
427 : mClient(client) { }
428
429 virtual ~Codec2ClientInterfaceWrapper() = default;
430
431 virtual c2_status_t config_sm(
432 const std::vector<C2Param *> &params,
433 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
434 return mClient->config(params, C2_MAY_BLOCK, failures);
435 };
436
437 virtual c2_status_t copyBuffer(
438 std::shared_ptr<C2GraphicBuffer>,
439 std::shared_ptr<C2GraphicBuffer>) {
440 return C2_OMITTED;
441 }
442
443 virtual c2_status_t createComponent(
444 C2String, std::shared_ptr<C2Component> *const component) {
445 component->reset();
446 return C2_OMITTED;
447 }
448
449 virtual c2_status_t createInterface(
450 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
451 interface->reset();
452 return C2_OMITTED;
453 }
454
455 virtual c2_status_t query_sm(
456 const std::vector<C2Param *> &stackParams,
457 const std::vector<C2Param::Index> &heapParamIndices,
458 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
459 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
460 }
461
462 virtual c2_status_t querySupportedParams_nb(
463 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
464 return mClient->querySupportedParams(params);
465 }
466
467 virtual c2_status_t querySupportedValues_sm(
468 std::vector<C2FieldSupportedValuesQuery> &fields) const {
469 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
470 }
471
472 virtual C2String getName() const {
473 return mClient->getName();
474 }
475
476 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
477 return mClient->getParamReflector();
478 }
479
480 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
481 return std::vector<std::shared_ptr<const C2Component::Traits>>();
482 }
483};
484
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800485void RevertOutputFormatIfNeeded(
486 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
487 // We used to not report changes to these keys to the client.
488 const static std::set<std::string> sIgnoredKeys({
489 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800490 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800491 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800492 KEY_MAX_WIDTH,
493 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800494 "csd-0",
495 "csd-1",
496 "csd-2",
497 });
498 if (currentFormat == oldFormat) {
499 return;
500 }
501 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
502 AMessage::Type type;
503 for (size_t i = diff->countEntries(); i > 0; --i) {
504 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
505 diff->removeEntryAt(i - 1);
506 }
507 }
508 if (diff->countEntries() == 0) {
509 currentFormat = oldFormat;
510 }
511}
512
Pawin Vongmasa36653902018-11-15 00:10:25 -0800513} // namespace
514
515// CCodec::ClientListener
516
517struct CCodec::ClientListener : public Codec2Client::Listener {
518
519 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
520
521 virtual void onWorkDone(
522 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800523 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800524 (void)component;
525 sp<CCodec> codec(mCodec.promote());
526 if (!codec) {
527 return;
528 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800529 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800530 }
531
532 virtual void onTripped(
533 const std::weak_ptr<Codec2Client::Component>& component,
534 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
535 ) override {
536 // TODO
537 (void)component;
538 (void)settingResult;
539 }
540
541 virtual void onError(
542 const std::weak_ptr<Codec2Client::Component>& component,
543 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800544 {
545 // Component is only used for reporting as we use a separate listener for each instance
546 std::shared_ptr<Codec2Client::Component> comp = component.lock();
547 if (!comp) {
548 ALOGD("Component died with error: 0x%x", errorCode);
549 } else {
550 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
551 }
552 }
553
554 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800555 // Note: for now we do not propagate the error code to MediaCodec
556 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800557 sp<CCodec> codec(mCodec.promote());
558 if (!codec || !codec->mCallback) {
559 return;
560 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800561 codec->mCallback->onError(
562 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
563 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800564 }
565
566 virtual void onDeath(
567 const std::weak_ptr<Codec2Client::Component>& component) override {
568 { // Log the death of the component.
569 std::shared_ptr<Codec2Client::Component> comp = component.lock();
570 if (!comp) {
571 ALOGE("Codec2 component died.");
572 } else {
573 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
574 }
575 }
576
577 // Report to MediaCodec.
578 sp<CCodec> codec(mCodec.promote());
579 if (!codec || !codec->mCallback) {
580 return;
581 }
582 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
583 }
584
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800585 virtual void onFrameRendered(uint64_t bufferQueueId,
586 int32_t slotId,
587 int64_t timestampNs) override {
588 // TODO: implement
589 (void)bufferQueueId;
590 (void)slotId;
591 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800592 }
593
594 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800595 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800596 sp<CCodec> codec(mCodec.promote());
597 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800598 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800599 }
600 }
601
602private:
603 wp<CCodec> mCodec;
604};
605
606// CCodecCallbackImpl
607
608class CCodecCallbackImpl : public CCodecCallback {
609public:
610 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
611 ~CCodecCallbackImpl() override = default;
612
613 void onError(status_t err, enum ActionCode actionCode) override {
614 mCodec->mCallback->onError(err, actionCode);
615 }
616
617 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
618 mCodec->mCallback->onOutputFramesRendered(
619 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
620 }
621
Pawin Vongmasa36653902018-11-15 00:10:25 -0800622 void onOutputBuffersChanged() override {
623 mCodec->mCallback->onOutputBuffersChanged();
624 }
625
626private:
627 CCodec *mCodec;
628};
629
630// CCodec
631
632CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700633 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
634 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800635}
636
637CCodec::~CCodec() {
638}
639
640std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
641 return mChannel;
642}
643
644status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
645 status_t err = job();
646 if (err != C2_OK) {
647 mCallback->onError(err, ACTION_CODE_FATAL);
648 }
649 return err;
650}
651
652void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
653 auto setAllocating = [this] {
654 Mutexed<State>::Locked state(mState);
655 if (state->get() != RELEASED) {
656 return INVALID_OPERATION;
657 }
658 state->set(ALLOCATING);
659 return OK;
660 };
661 if (tryAndReportOnError(setAllocating) != OK) {
662 return;
663 }
664
665 sp<RefBase> codecInfo;
666 CHECK(msg->findObject("codecInfo", &codecInfo));
667 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
668
669 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
670 allocMsg->setObject("codecInfo", codecInfo);
671 allocMsg->post();
672}
673
674void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
675 if (codecInfo == nullptr) {
676 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
677 return;
678 }
679 ALOGD("allocate(%s)", codecInfo->getCodecName());
680 mClientListener.reset(new ClientListener(this));
681
682 AString componentName = codecInfo->getCodecName();
683 std::shared_ptr<Codec2Client> client;
684
685 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700686 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800687 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800688 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800689 SetPreferredCodec2ComponentStore(
690 std::make_shared<Codec2ClientInterfaceWrapper>(client));
691 }
692
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900693 std::shared_ptr<Codec2Client::Component> comp;
694 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800695 componentName.c_str(),
696 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900697 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800698 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900699 if (status != C2_OK) {
700 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800701 Mutexed<State>::Locked state(mState);
702 state->set(RELEASED);
703 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900704 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800705 state.lock();
706 return;
707 }
708 ALOGI("Created component [%s]", componentName.c_str());
709 mChannel->setComponent(comp);
710 auto setAllocated = [this, comp, client] {
711 Mutexed<State>::Locked state(mState);
712 if (state->get() != ALLOCATING) {
713 state->set(RELEASED);
714 return UNKNOWN_ERROR;
715 }
716 state->set(ALLOCATED);
717 state->comp = comp;
718 mClient = client;
719 return OK;
720 };
721 if (tryAndReportOnError(setAllocated) != OK) {
722 return;
723 }
724
725 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700726 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
727 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800728 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800729 if (err != OK) {
730 ALOGW("Failed to initialize configuration support");
731 // TODO: report error once we complete implementation.
732 }
733 config->queryConfiguration(comp);
734
735 mCallback->onComponentAllocated(componentName.c_str());
736}
737
738void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
739 auto checkAllocated = [this] {
740 Mutexed<State>::Locked state(mState);
741 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
742 };
743 if (tryAndReportOnError(checkAllocated) != OK) {
744 return;
745 }
746
747 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
748 msg->setMessage("format", format);
749 msg->post();
750}
751
752void CCodec::configure(const sp<AMessage> &msg) {
753 std::shared_ptr<Codec2Client::Component> comp;
754 auto checkAllocated = [this, &comp] {
755 Mutexed<State>::Locked state(mState);
756 if (state->get() != ALLOCATED) {
757 state->set(RELEASED);
758 return UNKNOWN_ERROR;
759 }
760 comp = state->comp;
761 return OK;
762 };
763 if (tryAndReportOnError(checkAllocated) != OK) {
764 return;
765 }
766
767 auto doConfig = [msg, comp, this]() -> status_t {
768 AString mime;
769 if (!msg->findString("mime", &mime)) {
770 return BAD_VALUE;
771 }
772
773 int32_t encoder;
774 if (!msg->findInt32("encoder", &encoder)) {
775 encoder = false;
776 }
777
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800778 int32_t flags;
779 if (!msg->findInt32("flags", &flags)) {
780 return BAD_VALUE;
781 }
782
Pawin Vongmasa36653902018-11-15 00:10:25 -0800783 // TODO: read from intf()
784 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
785 return UNKNOWN_ERROR;
786 }
787
788 int32_t storeMeta;
789 if (encoder
790 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
791 && storeMeta != kMetadataBufferTypeInvalid) {
792 if (storeMeta != kMetadataBufferTypeANWBuffer) {
793 ALOGD("Only ANW buffers are supported for legacy metadata mode");
794 return BAD_VALUE;
795 }
796 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
797 }
798
799 sp<RefBase> obj;
800 sp<Surface> surface;
801 if (msg->findObject("native-window", &obj)) {
802 surface = static_cast<Surface *>(obj.get());
803 setSurface(surface);
804 }
805
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700806 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
807 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800808 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800809 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
810 ALOGD("[%s] buffers are %sbound to CCodec for this session",
811 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800812
Wonsik Kim1114eea2019-02-25 14:35:24 -0800813 // Enforce required parameters
814 int32_t i32;
815 float flt;
816 if (config->mDomain & Config::IS_AUDIO) {
817 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
818 ALOGD("sample rate is missing, which is required for audio components.");
819 return BAD_VALUE;
820 }
821 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
822 ALOGD("channel count is missing, which is required for audio components.");
823 return BAD_VALUE;
824 }
825 if ((config->mDomain & Config::IS_ENCODER)
826 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
827 && !msg->findInt32(KEY_BIT_RATE, &i32)
828 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
829 ALOGD("bitrate is missing, which is required for audio encoders.");
830 return BAD_VALUE;
831 }
832 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800833 int32_t width = 0;
834 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800835 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800836 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800837 ALOGD("width is missing, which is required for image/video components.");
838 return BAD_VALUE;
839 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800840 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800841 ALOGD("height is missing, which is required for image/video components.");
842 return BAD_VALUE;
843 }
844 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700845 int32_t mode = BITRATE_MODE_VBR;
846 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700847 if (!msg->findInt32(KEY_QUALITY, &i32)) {
848 ALOGD("quality is missing, which is required for video encoders in CQ.");
849 return BAD_VALUE;
850 }
851 } else {
852 if (!msg->findInt32(KEY_BIT_RATE, &i32)
853 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
854 ALOGD("bitrate is missing, which is required for video encoders.");
855 return BAD_VALUE;
856 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800857 }
858 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
859 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
860 ALOGD("I frame interval is missing, which is required for video encoders.");
861 return BAD_VALUE;
862 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700863 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
864 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
865 ALOGD("frame rate is missing, which is required for video encoders.");
866 return BAD_VALUE;
867 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800868 }
869 }
870
Pawin Vongmasa36653902018-11-15 00:10:25 -0800871 /*
872 * Handle input surface configuration
873 */
874 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
875 && (config->mDomain & Config::IS_ENCODER)) {
876 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
877 {
878 config->mISConfig->mMinFps = 0;
879 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800880 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800881 config->mISConfig->mMinFps = 1e6 / value;
882 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700883 if (!msg->findFloat(
884 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
885 config->mISConfig->mMaxFps = -1;
886 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800887 config->mISConfig->mMinAdjustedFps = 0;
888 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800889 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800890 if (value < 0 && value >= INT32_MIN) {
891 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700892 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800893 } else if (value > 0 && value <= INT32_MAX) {
894 config->mISConfig->mMinAdjustedFps = 1e6 / value;
895 }
896 }
897 }
898
899 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700900 bool captureFpsFound = false;
901 double timeLapseFps;
902 float captureRate;
903 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
904 config->mISConfig->mCaptureFps = timeLapseFps;
905 captureFpsFound = true;
906 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
907 config->mISConfig->mCaptureFps = captureRate;
908 captureFpsFound = true;
909 }
910 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800911 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
912 }
913 }
914
915 {
916 config->mISConfig->mSuspended = false;
917 config->mISConfig->mSuspendAtUs = -1;
918 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800919 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800920 config->mISConfig->mSuspended = true;
921 }
922 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700923 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800924 }
925
926 /*
927 * Handle desired color format.
928 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700929 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800930 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700931 int32_t format = 0;
932 // Query vendor format for Flexible YUV
933 std::vector<std::unique_ptr<C2Param>> heapParams;
934 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
935 if (mClient->query(
936 {},
937 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
938 C2_MAY_BLOCK,
939 &heapParams) == C2_OK
940 && heapParams.size() == 1u) {
941 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
942 heapParams[0].get());
943 } else {
944 pixelFormatInfo = nullptr;
945 }
946 std::optional<uint32_t> flexPixelFormat{};
947 std::optional<uint32_t> flexPlanarPixelFormat{};
948 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
949 if (pixelFormatInfo && *pixelFormatInfo) {
950 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
951 const C2FlexiblePixelFormatDescriptorStruct &desc =
952 pixelFormatInfo->m.values[i];
953 if (desc.bitDepth != 8
954 || desc.subsampling != C2Color::YUV_420
955 // TODO(b/180076105): some device report wrong layout
956 // || desc.layout == C2Color::INTERLEAVED_PACKED
957 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
958 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
959 continue;
960 }
961 if (!flexPixelFormat) {
962 flexPixelFormat = desc.pixelFormat;
963 }
964 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
965 flexPlanarPixelFormat = desc.pixelFormat;
966 }
967 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
968 flexSemiPlanarPixelFormat = desc.pixelFormat;
969 }
970 }
971 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800972 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700973 // Also handle default color format (encoders require color format, so this is only
974 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -0800975 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700976 if (surface == nullptr) {
977 format = flexPixelFormat.value_or(COLOR_FormatYUV420Flexible);
978 } else {
979 format = COLOR_FormatSurface;
980 }
981 defaultColorFormat = format;
982 }
983 } else {
984 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
985 switch (format) {
986 case COLOR_FormatYUV420Flexible:
987 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
988 break;
989 case COLOR_FormatYUV420Planar:
990 case COLOR_FormatYUV420PackedPlanar:
991 format = flexPlanarPixelFormat.value_or(
992 flexPixelFormat.value_or(format));
993 break;
994 case COLOR_FormatYUV420SemiPlanar:
995 case COLOR_FormatYUV420PackedSemiPlanar:
996 format = flexSemiPlanarPixelFormat.value_or(
997 flexPixelFormat.value_or(format));
998 break;
999 default:
1000 // No-op
1001 break;
1002 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001003 }
1004 }
1005
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001006 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001007 msg->setInt32("android._color-format", format);
1008 }
1009 }
1010
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001011 int32_t subscribeToAllVendorParams;
1012 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1013 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1014 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1015 }
1016 }
1017
Pawin Vongmasa36653902018-11-15 00:10:25 -08001018 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001019 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1020 // the behavior here.
1021 sp<AMessage> sdkParams = msg;
1022 int32_t videoBitrate;
1023 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1024 sdkParams = msg->dup();
1025 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1026 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001027 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001028 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001029 if (err != OK) {
1030 ALOGW("failed to convert configuration to c2 params");
1031 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001032
1033 int32_t maxBframes = 0;
1034 if ((config->mDomain & Config::IS_ENCODER)
1035 && (config->mDomain & Config::IS_VIDEO)
1036 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1037 && maxBframes > 0) {
1038 std::unique_ptr<C2StreamGopTuning::output> gop =
1039 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1040 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1041 gop->m.values[1] = {
1042 C2Config::picture_type_t(P_FRAME | B_FRAME),
1043 uint32_t(maxBframes)
1044 };
1045 configUpdate.push_back(std::move(gop));
1046 }
1047
Pawin Vongmasa36653902018-11-15 00:10:25 -08001048 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1049 if (err != OK) {
1050 ALOGW("failed to configure c2 params");
1051 return err;
1052 }
1053
1054 std::vector<std::unique_ptr<C2Param>> params;
1055 C2StreamUsageTuning::input usage(0u, 0u);
1056 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001057 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001058
Wonsik Kim3baecda2021-02-07 22:19:56 -08001059 C2Param::Index colorAspectsRequestIndex =
1060 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001061 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001062 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001063 };
1064 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001065 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001066 indices,
1067 C2_DONT_BLOCK,
1068 &params);
1069 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1070 ALOGE("Failed to query component interface: %d", c2err);
1071 return UNKNOWN_ERROR;
1072 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001073 if (usage) {
1074 if (usage.value & C2MemoryUsage::CPU_READ) {
1075 config->mInputFormat->setInt32("using-sw-read-often", true);
1076 }
1077 if (config->mISConfig) {
1078 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1079 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1080 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001081 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001082 }
1083
1084 // NOTE: we don't blindly use client specified input size if specified as clients
1085 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1086 // client specified size is only used to ask for bigger buffers than component suggested
1087 // size.
1088 int32_t clientInputSize = 0;
1089 bool clientSpecifiedInputSize =
1090 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1091 // TEMP: enforce minimum buffer size of 1MB for video decoders
1092 // and 16K / 4K for audio encoders/decoders
1093 if (maxInputSize.value == 0) {
1094 if (config->mDomain & Config::IS_AUDIO) {
1095 maxInputSize.value = encoder ? 16384 : 4096;
1096 } else if (!encoder) {
1097 maxInputSize.value = 1048576u;
1098 }
1099 }
1100
1101 // verify that CSD fits into this size (if defined)
1102 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1103 sp<ABuffer> csd;
1104 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1105 if (csd && csd->size() > maxInputSize.value) {
1106 maxInputSize.value = csd->size();
1107 }
1108 }
1109 }
1110
1111 // TODO: do this based on component requiring linear allocator for input
1112 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1113 if (clientSpecifiedInputSize) {
1114 // Warn that we're overriding client's max input size if necessary.
1115 if ((uint32_t)clientInputSize < maxInputSize.value) {
1116 ALOGD("client requested max input size %d, which is smaller than "
1117 "what component recommended (%u); overriding with component "
1118 "recommendation.", clientInputSize, maxInputSize.value);
1119 ALOGW("This behavior is subject to change. It is recommended that "
1120 "app developers double check whether the requested "
1121 "max input size is in reasonable range.");
1122 } else {
1123 maxInputSize.value = clientInputSize;
1124 }
1125 }
1126 // Pass max input size on input format to the buffer channel (if supplied by the
1127 // component or by a default)
1128 if (maxInputSize.value) {
1129 config->mInputFormat->setInt32(
1130 KEY_MAX_INPUT_SIZE,
1131 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1132 }
1133 }
1134
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001135 int32_t clientPrepend;
1136 if ((config->mDomain & Config::IS_VIDEO)
1137 && (config->mDomain & Config::IS_ENCODER)
1138 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1139 && clientPrepend
1140 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1141 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1142 return BAD_VALUE;
1143 }
1144
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001145 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001146 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1147 // propagate HDR static info to output format for both encoders and decoders
1148 // if component supports this info, we will update from component, but only the raw port,
1149 // so don't propagate if component already filled it in.
1150 sp<ABuffer> hdrInfo;
1151 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1152 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1153 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1154 }
1155
1156 // Set desired color format from configuration parameter
1157 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001158 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1159 format = defaultColorFormat;
1160 }
1161 if (config->mDomain & Config::IS_ENCODER) {
1162 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001163 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1164 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001165 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001166 } else {
1167 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001168 }
1169 }
1170
1171 // propagate encoder delay and padding to output format
1172 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1173 int delay = 0;
1174 if (msg->findInt32("encoder-delay", &delay)) {
1175 config->mOutputFormat->setInt32("encoder-delay", delay);
1176 }
1177 int padding = 0;
1178 if (msg->findInt32("encoder-padding", &padding)) {
1179 config->mOutputFormat->setInt32("encoder-padding", padding);
1180 }
1181 }
1182
1183 // set channel-mask
1184 if (config->mDomain & Config::IS_AUDIO) {
1185 int32_t mask;
1186 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1187 if (config->mDomain & Config::IS_ENCODER) {
1188 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1189 } else {
1190 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1191 }
1192 }
1193 }
1194
Wonsik Kim3baecda2021-02-07 22:19:56 -08001195 std::unique_ptr<C2Param> colorTransferRequestParam;
1196 for (std::unique_ptr<C2Param> &param : params) {
1197 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1198 ALOGI("found color transfer request param");
1199 colorTransferRequestParam = std::move(param);
1200 }
1201 }
1202 int32_t colorTransferRequest = 0;
1203 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1204 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1205 colorTransferRequest = 0;
1206 }
1207
1208 if (colorTransferRequest != 0) {
1209 if (colorTransferRequestParam && *colorTransferRequestParam) {
1210 C2StreamColorAspectsInfo::output *info =
1211 static_cast<C2StreamColorAspectsInfo::output *>(
1212 colorTransferRequestParam.get());
1213 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1214 colorTransferRequest = 0;
1215 }
1216 } else {
1217 colorTransferRequest = 0;
1218 }
1219 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1220 }
1221
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001222 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1223 // Need to get stride/vstride
1224 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1225 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1226 // TODO: retrieve these values without allocating a buffer.
1227 // Currently allocating a buffer is necessary to retrieve the layout.
1228 int64_t blockUsage =
1229 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1230 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1231 width, height, pixelFormat, blockUsage, {comp->getName()});
1232 sp<GraphicBlockBuffer> buffer;
1233 if (block) {
1234 buffer = GraphicBlockBuffer::Allocate(
1235 config->mInputFormat,
1236 block,
1237 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1238 } else {
1239 ALOGD("Failed to allocate a graphic block "
1240 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1241 width, height, pixelFormat, (long long)blockUsage);
1242 // This means that byte buffer mode is not supported in this configuration
1243 // anyway. Skip setting stride/vstride to input format.
1244 }
1245 if (buffer) {
1246 sp<ABuffer> imageData = buffer->getImageData();
1247 MediaImage2 *img = nullptr;
1248 if (imageData && imageData->data()
1249 && imageData->size() >= sizeof(MediaImage2)) {
1250 img = (MediaImage2*)imageData->data();
1251 }
1252 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1253 int32_t stride = img->mPlane[0].mRowInc;
1254 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1255 if (img->mNumPlanes > 1 && stride > 0) {
1256 int64_t offsetDelta =
1257 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1258 if (offsetDelta % stride == 0) {
1259 int32_t vstride = int32_t(offsetDelta / stride);
1260 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1261 } else {
1262 ALOGD("Cannot report accurate slice height: "
1263 "offsetDelta = %lld stride = %d",
1264 (long long)offsetDelta, stride);
1265 }
1266 }
1267 }
1268 }
1269 }
1270 }
1271
1272 ALOGD("setup formats input: %s",
1273 config->mInputFormat->debugString().c_str());
1274 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001275 config->mOutputFormat->debugString().c_str());
1276 return OK;
1277 };
1278 if (tryAndReportOnError(doConfig) != OK) {
1279 return;
1280 }
1281
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001282 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1283 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001284
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001285 config->queryConfiguration(comp);
1286
Pawin Vongmasa36653902018-11-15 00:10:25 -08001287 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1288}
1289
1290void CCodec::initiateCreateInputSurface() {
1291 status_t err = [this] {
1292 Mutexed<State>::Locked state(mState);
1293 if (state->get() != ALLOCATED) {
1294 return UNKNOWN_ERROR;
1295 }
1296 // TODO: read it from intf() properly.
1297 if (state->comp->getName().find("encoder") == std::string::npos) {
1298 return INVALID_OPERATION;
1299 }
1300 return OK;
1301 }();
1302 if (err != OK) {
1303 mCallback->onInputSurfaceCreationFailed(err);
1304 return;
1305 }
1306
1307 (new AMessage(kWhatCreateInputSurface, this))->post();
1308}
1309
Lajos Molnar47118272019-01-31 16:28:04 -08001310sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1311 using namespace android::hardware::media::omx::V1_0;
1312 using namespace android::hardware::media::omx::V1_0::utils;
1313 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1314 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1315 android::sp<IOmx> omx = IOmx::getService();
1316 typedef android::hardware::graphics::bufferqueue::V1_0::
1317 IGraphicBufferProducer HGraphicBufferProducer;
1318 typedef android::hardware::media::omx::V1_0::
1319 IGraphicBufferSource HGraphicBufferSource;
1320 OmxStatus s;
1321 android::sp<HGraphicBufferProducer> gbp;
1322 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001323
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001324 using ::android::hardware::Return;
1325 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001326 [&s, &gbp, &gbs](
1327 OmxStatus status,
1328 const android::sp<HGraphicBufferProducer>& producer,
1329 const android::sp<HGraphicBufferSource>& source) {
1330 s = status;
1331 gbp = producer;
1332 gbs = source;
1333 });
1334 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001335 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001336 }
1337
1338 return nullptr;
1339}
1340
1341sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1342 sp<PersistentSurface> surface(CreateInputSurface());
1343
1344 if (surface == nullptr) {
1345 surface = CreateOmxInputSurface();
1346 }
1347
1348 return surface;
1349}
1350
Pawin Vongmasa36653902018-11-15 00:10:25 -08001351void CCodec::createInputSurface() {
1352 status_t err;
1353 sp<IGraphicBufferProducer> bufferProducer;
1354
1355 sp<AMessage> inputFormat;
1356 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001357 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001358 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001359 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1360 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001361 inputFormat = config->mInputFormat;
1362 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001363 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001364 }
1365
Lajos Molnar47118272019-01-31 16:28:04 -08001366 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001367 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1368 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1369 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001370
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001371 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001372 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1373 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001374 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001375 inputSurface));
1376 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001377 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001378 int32_t width = 0;
1379 (void)outputFormat->findInt32("width", &width);
1380 int32_t height = 0;
1381 (void)outputFormat->findInt32("height", &height);
1382 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001383 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001384 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001385 } else {
1386 ALOGE("Corrupted input surface");
1387 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1388 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001389 }
1390
1391 if (err != OK) {
1392 ALOGE("Failed to set up input surface: %d", err);
1393 mCallback->onInputSurfaceCreationFailed(err);
1394 return;
1395 }
1396
1397 mCallback->onInputSurfaceCreated(
1398 inputFormat,
1399 outputFormat,
1400 new BufferProducerWrapper(bufferProducer));
1401}
1402
1403status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001404 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1405 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001406 config->mUsingSurface = true;
1407
1408 // we are now using surface - apply default color aspects to input format - as well as
1409 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001410 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001411 ALOGD("input format %s to %s",
1412 inputFormatChanged ? "changed" : "unchanged",
1413 config->mInputFormat->debugString().c_str());
1414
1415 // configure dataspace
1416 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1417 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1418 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1419 surface->setDataSpace(dataSpace);
1420
1421 status_t err = mChannel->setInputSurface(surface);
1422 if (err != OK) {
1423 // undo input format update
1424 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001425 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001426 return err;
1427 }
1428 config->mInputSurface = surface;
1429
1430 if (config->mISConfig) {
1431 surface->configure(*config->mISConfig);
1432 } else {
1433 ALOGD("ISConfig: no configuration");
1434 }
1435
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001436 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001437}
1438
1439void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1440 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1441 msg->setObject("surface", surface);
1442 msg->post();
1443}
1444
1445void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1446 sp<AMessage> inputFormat;
1447 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001448 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001449 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001450 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1451 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001452 inputFormat = config->mInputFormat;
1453 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001454 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001455 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001456 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1457 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1458 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1459 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001460 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1461 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1462 if (err != OK) {
1463 ALOGE("Failed to set up input surface: %d", err);
1464 mCallback->onInputSurfaceDeclined(err);
1465 return;
1466 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001467 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001468 int32_t width = 0;
1469 (void)outputFormat->findInt32("width", &width);
1470 int32_t height = 0;
1471 (void)outputFormat->findInt32("height", &height);
1472 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001473 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001474 if (err != OK) {
1475 ALOGE("Failed to set up input surface: %d", err);
1476 mCallback->onInputSurfaceDeclined(err);
1477 return;
1478 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001479 } else {
1480 ALOGE("Failed to set input surface: Corrupted surface.");
1481 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1482 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001483 }
1484 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1485}
1486
1487void CCodec::initiateStart() {
1488 auto setStarting = [this] {
1489 Mutexed<State>::Locked state(mState);
1490 if (state->get() != ALLOCATED) {
1491 return UNKNOWN_ERROR;
1492 }
1493 state->set(STARTING);
1494 return OK;
1495 };
1496 if (tryAndReportOnError(setStarting) != OK) {
1497 return;
1498 }
1499
1500 (new AMessage(kWhatStart, this))->post();
1501}
1502
1503void CCodec::start() {
1504 std::shared_ptr<Codec2Client::Component> comp;
1505 auto checkStarting = [this, &comp] {
1506 Mutexed<State>::Locked state(mState);
1507 if (state->get() != STARTING) {
1508 return UNKNOWN_ERROR;
1509 }
1510 comp = state->comp;
1511 return OK;
1512 };
1513 if (tryAndReportOnError(checkStarting) != OK) {
1514 return;
1515 }
1516
1517 c2_status_t err = comp->start();
1518 if (err != C2_OK) {
1519 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1520 ACTION_CODE_FATAL);
1521 return;
1522 }
1523 sp<AMessage> inputFormat;
1524 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001525 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001526 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001527 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001528 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1529 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001530 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001531 // start triggers format dup
1532 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001533 if (config->mInputSurface) {
1534 err2 = config->mInputSurface->start();
1535 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001536 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001537 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001538 if (err2 != OK) {
1539 mCallback->onError(err2, ACTION_CODE_FATAL);
1540 return;
1541 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001542 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001543 if (err2 != OK) {
1544 mCallback->onError(err2, ACTION_CODE_FATAL);
1545 return;
1546 }
1547
1548 auto setRunning = [this] {
1549 Mutexed<State>::Locked state(mState);
1550 if (state->get() != STARTING) {
1551 return UNKNOWN_ERROR;
1552 }
1553 state->set(RUNNING);
1554 return OK;
1555 };
1556 if (tryAndReportOnError(setRunning) != OK) {
1557 return;
1558 }
1559 mCallback->onStartCompleted();
1560
1561 (void)mChannel->requestInitialInputBuffers();
1562}
1563
1564void CCodec::initiateShutdown(bool keepComponentAllocated) {
1565 if (keepComponentAllocated) {
1566 initiateStop();
1567 } else {
1568 initiateRelease();
1569 }
1570}
1571
1572void CCodec::initiateStop() {
1573 {
1574 Mutexed<State>::Locked state(mState);
1575 if (state->get() == ALLOCATED
1576 || state->get() == RELEASED
1577 || state->get() == STOPPING
1578 || state->get() == RELEASING) {
1579 // We're already stopped, released, or doing it right now.
1580 state.unlock();
1581 mCallback->onStopCompleted();
1582 state.lock();
1583 return;
1584 }
1585 state->set(STOPPING);
1586 }
1587
Wonsik Kim936a89c2020-05-08 16:07:50 -07001588 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001589 (new AMessage(kWhatStop, this))->post();
1590}
1591
1592void CCodec::stop() {
1593 std::shared_ptr<Codec2Client::Component> comp;
1594 {
1595 Mutexed<State>::Locked state(mState);
1596 if (state->get() == RELEASING) {
1597 state.unlock();
1598 // We're already stopped or release is in progress.
1599 mCallback->onStopCompleted();
1600 state.lock();
1601 return;
1602 } else if (state->get() != STOPPING) {
1603 state.unlock();
1604 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1605 state.lock();
1606 return;
1607 }
1608 comp = state->comp;
1609 }
1610 status_t err = comp->stop();
1611 if (err != C2_OK) {
1612 // TODO: convert err into status_t
1613 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1614 }
1615
1616 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001617 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1618 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001619 if (config->mInputSurface) {
1620 config->mInputSurface->disconnect();
1621 config->mInputSurface = nullptr;
1622 }
1623 }
1624 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001625 Mutexed<State>::Locked state(mState);
1626 if (state->get() == STOPPING) {
1627 state->set(ALLOCATED);
1628 }
1629 }
1630 mCallback->onStopCompleted();
1631}
1632
1633void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001634 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001635 {
1636 Mutexed<State>::Locked state(mState);
1637 if (state->get() == RELEASED || state->get() == RELEASING) {
1638 // We're already released or doing it right now.
1639 if (sendCallback) {
1640 state.unlock();
1641 mCallback->onReleaseCompleted();
1642 state.lock();
1643 }
1644 return;
1645 }
1646 if (state->get() == ALLOCATING) {
1647 state->set(RELEASING);
1648 // With the altered state allocate() would fail and clean up.
1649 if (sendCallback) {
1650 state.unlock();
1651 mCallback->onReleaseCompleted();
1652 state.lock();
1653 }
1654 return;
1655 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001656 if (state->get() == STARTING
1657 || state->get() == RUNNING
1658 || state->get() == STOPPING) {
1659 // Input surface may have been started, so clean up is needed.
1660 clearInputSurfaceIfNeeded = true;
1661 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001662 state->set(RELEASING);
1663 }
1664
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001665 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001666 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1667 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001668 if (config->mInputSurface) {
1669 config->mInputSurface->disconnect();
1670 config->mInputSurface = nullptr;
1671 }
1672 }
1673
Wonsik Kim936a89c2020-05-08 16:07:50 -07001674 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001675 // thiz holds strong ref to this while the thread is running.
1676 sp<CCodec> thiz(this);
1677 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1678}
1679
1680void CCodec::release(bool sendCallback) {
1681 std::shared_ptr<Codec2Client::Component> comp;
1682 {
1683 Mutexed<State>::Locked state(mState);
1684 if (state->get() == RELEASED) {
1685 if (sendCallback) {
1686 state.unlock();
1687 mCallback->onReleaseCompleted();
1688 state.lock();
1689 }
1690 return;
1691 }
1692 comp = state->comp;
1693 }
1694 comp->release();
1695
1696 {
1697 Mutexed<State>::Locked state(mState);
1698 state->set(RELEASED);
1699 state->comp.reset();
1700 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001701 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001702 if (sendCallback) {
1703 mCallback->onReleaseCompleted();
1704 }
1705}
1706
1707status_t CCodec::setSurface(const sp<Surface> &surface) {
1708 return mChannel->setSurface(surface);
1709}
1710
1711void CCodec::signalFlush() {
1712 status_t err = [this] {
1713 Mutexed<State>::Locked state(mState);
1714 if (state->get() == FLUSHED) {
1715 return ALREADY_EXISTS;
1716 }
1717 if (state->get() != RUNNING) {
1718 return UNKNOWN_ERROR;
1719 }
1720 state->set(FLUSHING);
1721 return OK;
1722 }();
1723 switch (err) {
1724 case ALREADY_EXISTS:
1725 mCallback->onFlushCompleted();
1726 return;
1727 case OK:
1728 break;
1729 default:
1730 mCallback->onError(err, ACTION_CODE_FATAL);
1731 return;
1732 }
1733
1734 mChannel->stop();
1735 (new AMessage(kWhatFlush, this))->post();
1736}
1737
1738void CCodec::flush() {
1739 std::shared_ptr<Codec2Client::Component> comp;
1740 auto checkFlushing = [this, &comp] {
1741 Mutexed<State>::Locked state(mState);
1742 if (state->get() != FLUSHING) {
1743 return UNKNOWN_ERROR;
1744 }
1745 comp = state->comp;
1746 return OK;
1747 };
1748 if (tryAndReportOnError(checkFlushing) != OK) {
1749 return;
1750 }
1751
1752 std::list<std::unique_ptr<C2Work>> flushedWork;
1753 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1754 {
1755 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1756 flushedWork.splice(flushedWork.end(), *queue);
1757 }
1758 if (err != C2_OK) {
1759 // TODO: convert err into status_t
1760 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1761 }
1762
1763 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001764
1765 {
1766 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001767 if (state->get() == FLUSHING) {
1768 state->set(FLUSHED);
1769 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001770 }
1771 mCallback->onFlushCompleted();
1772}
1773
1774void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001775 std::shared_ptr<Codec2Client::Component> comp;
1776 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001777 Mutexed<State>::Locked state(mState);
1778 if (state->get() != FLUSHED) {
1779 return UNKNOWN_ERROR;
1780 }
1781 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001782 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001783 return OK;
1784 };
1785 if (tryAndReportOnError(setResuming) != OK) {
1786 return;
1787 }
1788
Wonsik Kime75a5da2020-02-14 17:29:03 -08001789 {
1790 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1791 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001792 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001793 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001794 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001795 }
1796
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001797 (void)mChannel->start(nullptr, nullptr, [&]{
1798 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1799 const std::unique_ptr<Config> &config = *configLocked;
1800 return config->mBuffersBoundToCodec;
1801 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001802
1803 {
1804 Mutexed<State>::Locked state(mState);
1805 if (state->get() != RESUMING) {
1806 state.unlock();
1807 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1808 state.lock();
1809 return;
1810 }
1811 state->set(RUNNING);
1812 }
1813
1814 (void)mChannel->requestInitialInputBuffers();
1815}
1816
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001817void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001818 std::shared_ptr<Codec2Client::Component> comp;
1819 auto checkState = [this, &comp] {
1820 Mutexed<State>::Locked state(mState);
1821 if (state->get() == RELEASED) {
1822 return INVALID_OPERATION;
1823 }
1824 comp = state->comp;
1825 return OK;
1826 };
1827 if (tryAndReportOnError(checkState) != OK) {
1828 return;
1829 }
1830
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001831 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1832 // the behavior here.
1833 sp<AMessage> params = msg;
1834 int32_t bitrate;
1835 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1836 params = msg->dup();
1837 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1838 }
1839
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001840 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1841 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001842
1843 /**
1844 * Handle input surface parameters
1845 */
1846 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001847 && (config->mDomain & Config::IS_ENCODER)
1848 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001849 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001850
1851 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1852 config->mISConfig->mStopped = false;
1853 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1854 config->mISConfig->mStopped = true;
1855 }
1856
1857 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001858 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001859 config->mISConfig->mSuspended = value;
1860 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001861 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001862 }
1863
1864 (void)config->mInputSurface->configure(*config->mISConfig);
1865 if (config->mISConfig->mStopped) {
1866 config->mInputFormat->setInt64(
1867 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1868 }
1869 }
1870
1871 std::vector<std::unique_ptr<C2Param>> configUpdate;
1872 (void)config->getConfigUpdateFromSdkParams(
1873 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1874 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1875 // Parameter synchronization is not defined when using input surface. For now, route
1876 // these directly to the component.
1877 if (config->mInputSurface == nullptr
1878 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1879 || comp->getName().find("c2.android.") == 0)) {
1880 mChannel->setParameters(configUpdate);
1881 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08001882 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001883 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08001884 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001885 }
1886}
1887
1888void CCodec::signalEndOfInputStream() {
1889 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1890}
1891
1892void CCodec::signalRequestIDRFrame() {
1893 std::shared_ptr<Codec2Client::Component> comp;
1894 {
1895 Mutexed<State>::Locked state(mState);
1896 if (state->get() == RELEASED) {
1897 ALOGD("no IDR request sent since component is released");
1898 return;
1899 }
1900 comp = state->comp;
1901 }
1902 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001903 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1904 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001905 std::vector<std::unique_ptr<C2Param>> params;
1906 params.push_back(
1907 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1908 config->setParameters(comp, params, C2_MAY_BLOCK);
1909}
1910
Wonsik Kimab34ed62019-01-31 15:28:46 -08001911void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001912 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001913 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1914 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001915 }
1916 (new AMessage(kWhatWorkDone, this))->post();
1917}
1918
Wonsik Kimab34ed62019-01-31 15:28:46 -08001919void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1920 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001921 if (arrayIndex == 0) {
1922 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001923 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1924 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001925 if (config->mInputSurface) {
1926 config->mInputSurface->onInputBufferDone(frameIndex);
1927 }
1928 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001929}
1930
1931void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1932 TimePoint now = std::chrono::steady_clock::now();
1933 CCodecWatchdog::getInstance()->watch(this);
1934 switch (msg->what()) {
1935 case kWhatAllocate: {
1936 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001937 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001938 sp<RefBase> obj;
1939 CHECK(msg->findObject("codecInfo", &obj));
1940 allocate((MediaCodecInfo *)obj.get());
1941 break;
1942 }
1943 case kWhatConfigure: {
1944 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001945 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001946 sp<AMessage> format;
1947 CHECK(msg->findMessage("format", &format));
1948 configure(format);
1949 break;
1950 }
1951 case kWhatStart: {
1952 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001953 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001954 start();
1955 break;
1956 }
1957 case kWhatStop: {
1958 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001959 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001960 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001961 break;
1962 }
1963 case kWhatFlush: {
1964 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001965 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001966 flush();
1967 break;
1968 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001969 case kWhatRelease: {
1970 mChannel->release();
1971 mClient.reset();
1972 mClientListener.reset();
1973 break;
1974 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001975 case kWhatCreateInputSurface: {
1976 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001977 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001978 createInputSurface();
1979 break;
1980 }
1981 case kWhatSetInputSurface: {
1982 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001983 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001984 sp<RefBase> obj;
1985 CHECK(msg->findObject("surface", &obj));
1986 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1987 setInputSurface(surface);
1988 break;
1989 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001990 case kWhatWorkDone: {
1991 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001992 bool shouldPost = false;
1993 {
1994 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1995 if (queue->empty()) {
1996 break;
1997 }
1998 work.swap(queue->front());
1999 queue->pop_front();
2000 shouldPost = !queue->empty();
2001 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002002 if (shouldPost) {
2003 (new AMessage(kWhatWorkDone, this))->post();
2004 }
2005
Pawin Vongmasa36653902018-11-15 00:10:25 -08002006 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002007 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2008 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002009 Config::Watcher<C2StreamInitDataInfo::output> initData =
2010 config->watch<C2StreamInitDataInfo::output>();
2011 if (!work->worklets.empty()
2012 && (work->worklets.front()->output.flags
2013 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
2014
2015 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002016 std::vector<std::unique_ptr<C2Param>> updates;
2017 for (const std::unique_ptr<C2Param> &param
2018 : work->worklets.front()->output.configUpdate) {
2019 updates.push_back(C2Param::Copy(*param));
2020 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002021 unsigned stream = 0;
2022 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2023 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2024 // move all info into output-stream #0 domain
2025 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
2026 }
George Burgess IVc813a592020-02-22 22:54:44 -08002027
2028 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2029 // for now only do the first block
2030 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002031 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2032 // block.crop().left, block.crop().top,
2033 // block.crop().width, block.crop().height,
2034 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08002035 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08002036 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
2037 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07002038 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002039 }
2040 ++stream;
2041 }
2042
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002043 sp<AMessage> outputFormat = config->mOutputFormat;
2044 config->updateConfiguration(updates, config->mOutputDomain);
2045 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002046
2047 // copy standard infos to graphic buffers if not already present (otherwise, we
2048 // may overwrite the actual intermediate value with a final value)
2049 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07002050 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002051 C2StreamRotationInfo::output::PARAM_TYPE,
2052 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2053 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2054 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08002055 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08002056 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2057 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2058 };
2059 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2060 if (buf->data().graphicBlocks().size()) {
2061 for (C2Param::Index ix : stdGfxInfos) {
2062 if (!buf->hasInfo(ix)) {
2063 const C2Param *param =
2064 config->getConfigParameterValue(ix.withStream(stream));
2065 if (param) {
2066 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2067 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2068 }
2069 }
2070 }
2071 }
2072 ++stream;
2073 }
2074 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002075 if (config->mInputSurface) {
2076 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2077 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002078 mChannel->onWorkDone(
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002079 std::move(work), config->mOutputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002080 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002081 break;
2082 }
2083 case kWhatWatch: {
2084 // watch message already posted; no-op.
2085 break;
2086 }
2087 default: {
2088 ALOGE("unrecognized message");
2089 break;
2090 }
2091 }
2092 setDeadline(TimePoint::max(), 0ms, "none");
2093}
2094
2095void CCodec::setDeadline(
2096 const TimePoint &now,
2097 const std::chrono::milliseconds &timeout,
2098 const char *name) {
2099 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2100 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2101 deadline->set(now + (timeout * mult), name);
2102}
2103
2104void CCodec::initiateReleaseIfStuck() {
2105 std::string name;
2106 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002107 {
2108 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002109 if (deadline->get() < std::chrono::steady_clock::now()) {
2110 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002111 }
2112 if (deadline->get() != TimePoint::max()) {
2113 pendingDeadline = true;
2114 }
2115 }
2116 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002117 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2118 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2119 if (elapsed >= kWorkDurationThreshold) {
2120 name = "queue";
2121 }
2122 if (elapsed > 0s) {
2123 pendingDeadline = true;
2124 }
2125 }
2126 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002127 // We're not stuck.
2128 if (pendingDeadline) {
2129 // If we are not stuck yet but still has deadline coming up,
2130 // post watch message to check back later.
2131 (new AMessage(kWhatWatch, this))->post();
2132 }
2133 return;
2134 }
2135
2136 ALOGW("previous call to %s exceeded timeout", name.c_str());
2137 initiateRelease(false);
2138 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2139}
2140
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002141// static
2142PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002143 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002144 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002145 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002146 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2147 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002148 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002149 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2150 sp<IGraphicBufferProducer> gbp;
2151 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2152 status_t err = gbs->initCheck();
2153 if (err != OK) {
2154 ALOGE("Failed to create persistent input surface: error %d", err);
2155 return nullptr;
2156 }
2157 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002158 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002159 } else {
2160 return nullptr;
2161 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002162 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002163 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002164 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002165 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002166 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002167}
2168
Wonsik Kimffb889a2020-05-28 11:32:25 -07002169class IntfCache {
2170public:
2171 IntfCache() = default;
2172
2173 status_t init(const std::string &name) {
2174 std::shared_ptr<Codec2Client::Interface> intf{
2175 Codec2Client::CreateInterfaceByName(name.c_str())};
2176 if (!intf) {
2177 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2178 mInitStatus = NO_INIT;
2179 return NO_INIT;
2180 }
2181 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2182 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2183 C2ParamField{&sUsage, &sUsage.value}));
2184 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2185 if (err != C2_OK) {
2186 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2187 name.c_str(), err);
2188 mFields[0].status = err;
2189 }
2190 std::vector<std::unique_ptr<C2Param>> params;
2191 err = intf->query(
2192 {&mApiFeatures},
2193 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2194 C2_MAY_BLOCK,
2195 &params);
2196 if (err != C2_OK && err != C2_BAD_INDEX) {
2197 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2198 name.c_str(), err);
2199 }
2200 while (!params.empty()) {
2201 C2Param *param = params.back().release();
2202 params.pop_back();
2203 if (!param) {
2204 continue;
2205 }
2206 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2207 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002208 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002209 }
2210 }
2211 mInitStatus = OK;
2212 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002213 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002214
2215 status_t initCheck() const { return mInitStatus; }
2216
2217 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2218 CHECK_EQ(1u, mFields.size());
2219 return mFields[0];
2220 }
2221
2222 const C2ApiFeaturesSetting &getApiFeatures() const {
2223 return mApiFeatures;
2224 }
2225
2226 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2227 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2228 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2229 C2PortAllocatorsTuning::input::AllocUnique(0);
2230 param->invalidate();
2231 return param;
2232 }();
2233 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2234 }
2235
2236private:
2237 status_t mInitStatus{NO_INIT};
2238
2239 std::vector<C2FieldSupportedValuesQuery> mFields;
2240 C2ApiFeaturesSetting mApiFeatures;
2241 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2242};
2243
2244static const IntfCache &GetIntfCache(const std::string &name) {
2245 static IntfCache sNullIntfCache;
2246 static std::mutex sMutex;
2247 static std::map<std::string, IntfCache> sCache;
2248 std::unique_lock<std::mutex> lock{sMutex};
2249 auto it = sCache.find(name);
2250 if (it == sCache.end()) {
2251 lock.unlock();
2252 IntfCache intfCache;
2253 status_t err = intfCache.init(name);
2254 if (err != OK) {
2255 return sNullIntfCache;
2256 }
2257 lock.lock();
2258 it = sCache.insert({name, std::move(intfCache)}).first;
2259 }
2260 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002261}
2262
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002263static status_t GetCommonAllocatorIds(
2264 const std::vector<std::string> &names,
2265 C2Allocator::type_t type,
2266 std::set<C2Allocator::id_t> *ids) {
2267 int poolMask = GetCodec2PoolMask();
2268 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2269 C2Allocator::id_t defaultAllocatorId =
2270 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2271
2272 ids->clear();
2273 if (names.empty()) {
2274 return OK;
2275 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002276 bool firstIteration = true;
2277 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002278 const IntfCache &intfCache = GetIntfCache(name);
2279 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002280 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002281 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002282 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002283 if (firstIteration) {
2284 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002285 if (allocators && allocators.flexCount() > 0) {
2286 ids->insert(allocators.m.values,
2287 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002288 }
2289 if (ids->empty()) {
2290 // The component does not advertise allocators. Use default.
2291 ids->insert(defaultAllocatorId);
2292 }
2293 continue;
2294 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002295 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002296 if (allocators && allocators.flexCount() > 0) {
2297 filtered = true;
2298 for (auto it = ids->begin(); it != ids->end(); ) {
2299 bool found = false;
2300 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2301 if (allocators.m.values[j] == *it) {
2302 found = true;
2303 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002304 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002305 }
2306 if (found) {
2307 ++it;
2308 } else {
2309 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002310 }
2311 }
2312 }
2313 if (!filtered) {
2314 // The component does not advertise supported allocators. Use default.
2315 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2316 if (ids->size() != (containsDefault ? 1 : 0)) {
2317 ids->clear();
2318 if (containsDefault) {
2319 ids->insert(defaultAllocatorId);
2320 }
2321 }
2322 }
2323 }
2324 // Finally, filter with pool masks
2325 for (auto it = ids->begin(); it != ids->end(); ) {
2326 if ((poolMask >> *it) & 1) {
2327 ++it;
2328 } else {
2329 it = ids->erase(it);
2330 }
2331 }
2332 return OK;
2333}
2334
2335static status_t CalculateMinMaxUsage(
2336 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2337 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2338 *minUsage = 0;
2339 *maxUsage = ~0ull;
2340 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002341 const IntfCache &intfCache = GetIntfCache(name);
2342 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002343 continue;
2344 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002345 const C2FieldSupportedValuesQuery &usageSupportedValues =
2346 intfCache.getUsageSupportedValues();
2347 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002348 continue;
2349 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002350 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002351 if (supported.type != C2FieldSupportedValues::FLAGS) {
2352 continue;
2353 }
2354 if (supported.values.empty()) {
2355 *maxUsage = 0;
2356 continue;
2357 }
2358 *minUsage |= supported.values[0].u64;
2359 int64_t currentMaxUsage = 0;
2360 for (const C2Value::Primitive &flags : supported.values) {
2361 currentMaxUsage |= flags.u64;
2362 }
2363 *maxUsage &= currentMaxUsage;
2364 }
2365 return OK;
2366}
2367
2368// static
2369status_t CCodec::CanFetchLinearBlock(
2370 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002371 for (const std::string &name : names) {
2372 const IntfCache &intfCache = GetIntfCache(name);
2373 if (intfCache.initCheck() != OK) {
2374 continue;
2375 }
2376 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2377 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2378 *isCompatible = false;
2379 return OK;
2380 }
2381 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002382 std::set<C2Allocator::id_t> allocators;
2383 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2384 if (allocators.empty()) {
2385 *isCompatible = false;
2386 return OK;
2387 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002388
2389 uint64_t minUsage = 0;
2390 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002391 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002392 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002393 *isCompatible = ((maxUsage & minUsage) == minUsage);
2394 return OK;
2395}
2396
2397static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2398 static std::mutex sMutex{};
2399 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2400 std::unique_lock<std::mutex> lock{sMutex};
2401 std::shared_ptr<C2BlockPool> pool;
2402 auto it = sPools.find(allocId);
2403 if (it == sPools.end()) {
2404 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2405 if (err == OK) {
2406 sPools.emplace(allocId, pool);
2407 } else {
2408 pool.reset();
2409 }
2410 } else {
2411 pool = it->second;
2412 }
2413 return pool;
2414}
2415
2416// static
2417std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2418 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002419 std::set<C2Allocator::id_t> allocators;
2420 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2421 if (allocators.empty()) {
2422 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2423 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002424
2425 uint64_t minUsage = 0;
2426 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002427 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002428 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002429 if ((maxUsage & minUsage) != minUsage) {
2430 allocators.clear();
2431 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2432 }
2433 std::shared_ptr<C2LinearBlock> block;
2434 for (C2Allocator::id_t allocId : allocators) {
2435 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2436 if (!pool) {
2437 continue;
2438 }
2439 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2440 if (err != C2_OK || !block) {
2441 block.reset();
2442 continue;
2443 }
2444 break;
2445 }
2446 return block;
2447}
2448
2449// static
2450status_t CCodec::CanFetchGraphicBlock(
2451 const std::vector<std::string> &names, bool *isCompatible) {
2452 uint64_t minUsage = 0;
2453 uint64_t maxUsage = ~0ull;
2454 std::set<C2Allocator::id_t> allocators;
2455 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2456 if (allocators.empty()) {
2457 *isCompatible = false;
2458 return OK;
2459 }
2460 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2461 *isCompatible = ((maxUsage & minUsage) == minUsage);
2462 return OK;
2463}
2464
2465// static
2466std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2467 int32_t width,
2468 int32_t height,
2469 int32_t format,
2470 uint64_t usage,
2471 const std::vector<std::string> &names) {
2472 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2473 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2474 ALOGD("Unrecognized pixel format: %d", format);
2475 return nullptr;
2476 }
2477 uint64_t minUsage = 0;
2478 uint64_t maxUsage = ~0ull;
2479 std::set<C2Allocator::id_t> allocators;
2480 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2481 if (allocators.empty()) {
2482 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2483 }
2484 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2485 minUsage |= usage;
2486 if ((maxUsage & minUsage) != minUsage) {
2487 allocators.clear();
2488 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2489 }
2490 std::shared_ptr<C2GraphicBlock> block;
2491 for (C2Allocator::id_t allocId : allocators) {
2492 std::shared_ptr<C2BlockPool> pool;
2493 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2494 if (err != C2_OK || !pool) {
2495 continue;
2496 }
2497 err = pool->fetchGraphicBlock(
2498 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2499 if (err != C2_OK || !block) {
2500 block.reset();
2501 continue;
2502 }
2503 break;
2504 }
2505 return block;
2506}
2507
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002508} // namespace android
2509