blob: 092d6eebb21767893ecce01cb7055a7090c7580d [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
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700213 mSource->configure(
214 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800215 return OK;
216 }
217
218 void disconnect() override {
219 if (mNode == nullptr) {
220 return;
221 }
222 sp<IOMXBufferSource> source = mNode->getSource();
223 if (source == nullptr) {
224 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
225 return;
226 }
227 source->onOmxIdle();
228 source->onOmxLoaded();
229 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700230 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800231 }
232
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700233 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
234 if (status.isOk()) {
235 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
236 } else if (status.isDeadObject()) {
237 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800238 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700239 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800240 }
241
242 status_t start() override {
243 sp<IOMXBufferSource> source = mNode->getSource();
244 if (source == nullptr) {
245 return NO_INIT;
246 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900247
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800248 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800249 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900250
Wonsik Kim34d66012021-03-01 16:40:33 -0800251 OMX_PARAM_PORTDEFINITIONTYPE param;
252 param.nPortIndex = kPortIndexInput;
253 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
254 &param, sizeof(param));
255 if (err == OK) {
256 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900257 }
258
259 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800260 source->onInputBufferAdded(i);
261 }
262
263 source->onOmxExecuting();
264 return OK;
265 }
266
267 status_t signalEndOfInputStream() override {
268 return GetStatus(mSource->signalEndOfInputStream());
269 }
270
271 status_t configure(Config &config) {
272 std::stringstream status;
273 status_t err = OK;
274
275 // handle each configuration granually, in case we need to handle part of the configuration
276 // elsewhere
277
278 // TRICKY: we do not unset frame delay repeating
279 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
280 int64_t us = 1e6 / config.mMinFps + 0.5;
281 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
282 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
283 if (res != OK) {
284 status << " (=> " << asString(res) << ")";
285 err = res;
286 }
287 mConfig.mMinFps = config.mMinFps;
288 }
289
290 // pts gap
291 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
292 if (mNode != nullptr) {
293 OMX_PARAM_U32TYPE ptrGapParam = {};
294 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700295 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800296 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
297 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700298 // float -> uint32_t is undefined if the value is negative.
299 // First convert to int32_t to ensure the expected behavior.
300 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800301 (void)mNode->setParameter(
302 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
303 &ptrGapParam, sizeof(ptrGapParam));
304 }
305 }
306
307 // max fps
308 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700309 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800310 && config.mMaxFps != mConfig.mMaxFps) {
311 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
312 status << " maxFps=" << config.mMaxFps;
313 if (res != OK) {
314 status << " (=> " << asString(res) << ")";
315 err = res;
316 }
317 mConfig.mMaxFps = config.mMaxFps;
318 }
319
320 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
321 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
322 status << " timeOffset " << config.mTimeOffsetUs << "us";
323 if (res != OK) {
324 status << " (=> " << asString(res) << ")";
325 err = res;
326 }
327 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
328 }
329
330 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
331 status_t res =
332 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
333 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
334 if (res != OK) {
335 status << " (=> " << asString(res) << ")";
336 err = res;
337 }
338 mConfig.mCaptureFps = config.mCaptureFps;
339 mConfig.mCodedFps = config.mCodedFps;
340 }
341
342 if (config.mStartAtUs != mConfig.mStartAtUs
343 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
344 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
345 status << " start at " << config.mStartAtUs << "us";
346 if (res != OK) {
347 status << " (=> " << asString(res) << ")";
348 err = res;
349 }
350 mConfig.mStartAtUs = config.mStartAtUs;
351 mConfig.mStopped = config.mStopped;
352 }
353
354 // suspend-resume
355 if (config.mSuspended != mConfig.mSuspended) {
356 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
357 status << " " << (config.mSuspended ? "suspend" : "resume")
358 << " at " << config.mSuspendAtUs << "us";
359 if (res != OK) {
360 status << " (=> " << asString(res) << ")";
361 err = res;
362 }
363 mConfig.mSuspended = config.mSuspended;
364 mConfig.mSuspendAtUs = config.mSuspendAtUs;
365 }
366
367 if (config.mStopped != mConfig.mStopped && config.mStopped) {
368 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
369 status << " stop at " << config.mStopAtUs << "us";
370 if (res != OK) {
371 status << " (=> " << asString(res) << ")";
372 err = res;
373 } else {
374 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700375 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
376 [&res, &delayUs = config.mInputDelayUs](
377 auto status, auto stopTimeOffsetUs) {
378 res = static_cast<status_t>(status);
379 delayUs = stopTimeOffsetUs;
380 });
381 if (!trans.isOk()) {
382 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
383 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800384 if (res != OK) {
385 status << " (=> " << asString(res) << ")";
386 } else {
387 status << "=" << config.mInputDelayUs << "us";
388 }
389 mConfig.mInputDelayUs = config.mInputDelayUs;
390 }
391 mConfig.mStopAtUs = config.mStopAtUs;
392 mConfig.mStopped = config.mStopped;
393 }
394
395 // color aspects (android._color-aspects)
396
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700397 // consumer usage is queried earlier.
398
Wonsik Kimbd557932019-07-02 15:51:20 -0700399 if (status.str().empty()) {
400 ALOGD("ISConfig not changed");
401 } else {
402 ALOGD("ISConfig%s", status.str().c_str());
403 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800404 return err;
405 }
406
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700407 void onInputBufferDone(c2_cntr64_t index) override {
408 mNode->onInputBufferDone(index);
409 }
410
Wonsik Kim40aaf952021-01-29 14:58:12 -0800411 android_dataspace getDataspace() override {
412 return mNode->getDataspace();
413 }
414
Pawin Vongmasa36653902018-11-15 00:10:25 -0800415private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700416 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800417 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700418 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800419 uint32_t mWidth;
420 uint32_t mHeight;
421 Config mConfig;
422};
423
424class Codec2ClientInterfaceWrapper : public C2ComponentStore {
425 std::shared_ptr<Codec2Client> mClient;
426
427public:
428 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
429 : mClient(client) { }
430
431 virtual ~Codec2ClientInterfaceWrapper() = default;
432
433 virtual c2_status_t config_sm(
434 const std::vector<C2Param *> &params,
435 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
436 return mClient->config(params, C2_MAY_BLOCK, failures);
437 };
438
439 virtual c2_status_t copyBuffer(
440 std::shared_ptr<C2GraphicBuffer>,
441 std::shared_ptr<C2GraphicBuffer>) {
442 return C2_OMITTED;
443 }
444
445 virtual c2_status_t createComponent(
446 C2String, std::shared_ptr<C2Component> *const component) {
447 component->reset();
448 return C2_OMITTED;
449 }
450
451 virtual c2_status_t createInterface(
452 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
453 interface->reset();
454 return C2_OMITTED;
455 }
456
457 virtual c2_status_t query_sm(
458 const std::vector<C2Param *> &stackParams,
459 const std::vector<C2Param::Index> &heapParamIndices,
460 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
461 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
462 }
463
464 virtual c2_status_t querySupportedParams_nb(
465 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
466 return mClient->querySupportedParams(params);
467 }
468
469 virtual c2_status_t querySupportedValues_sm(
470 std::vector<C2FieldSupportedValuesQuery> &fields) const {
471 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
472 }
473
474 virtual C2String getName() const {
475 return mClient->getName();
476 }
477
478 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
479 return mClient->getParamReflector();
480 }
481
482 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
483 return std::vector<std::shared_ptr<const C2Component::Traits>>();
484 }
485};
486
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800487void RevertOutputFormatIfNeeded(
488 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
489 // We used to not report changes to these keys to the client.
490 const static std::set<std::string> sIgnoredKeys({
491 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800492 KEY_FRAME_RATE,
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800493 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800494 KEY_MAX_WIDTH,
495 KEY_MAX_HEIGHT,
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800496 "csd-0",
497 "csd-1",
498 "csd-2",
499 });
500 if (currentFormat == oldFormat) {
501 return;
502 }
503 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
504 AMessage::Type type;
505 for (size_t i = diff->countEntries(); i > 0; --i) {
506 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
507 diff->removeEntryAt(i - 1);
508 }
509 }
510 if (diff->countEntries() == 0) {
511 currentFormat = oldFormat;
512 }
513}
514
Pawin Vongmasa36653902018-11-15 00:10:25 -0800515} // namespace
516
517// CCodec::ClientListener
518
519struct CCodec::ClientListener : public Codec2Client::Listener {
520
521 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
522
523 virtual void onWorkDone(
524 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800525 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800526 (void)component;
527 sp<CCodec> codec(mCodec.promote());
528 if (!codec) {
529 return;
530 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800531 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800532 }
533
534 virtual void onTripped(
535 const std::weak_ptr<Codec2Client::Component>& component,
536 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
537 ) override {
538 // TODO
539 (void)component;
540 (void)settingResult;
541 }
542
543 virtual void onError(
544 const std::weak_ptr<Codec2Client::Component>& component,
545 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800546 {
547 // Component is only used for reporting as we use a separate listener for each instance
548 std::shared_ptr<Codec2Client::Component> comp = component.lock();
549 if (!comp) {
550 ALOGD("Component died with error: 0x%x", errorCode);
551 } else {
552 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
553 }
554 }
555
556 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800557 // Note: for now we do not propagate the error code to MediaCodec
558 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800559 sp<CCodec> codec(mCodec.promote());
560 if (!codec || !codec->mCallback) {
561 return;
562 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800563 codec->mCallback->onError(
564 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
565 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800566 }
567
568 virtual void onDeath(
569 const std::weak_ptr<Codec2Client::Component>& component) override {
570 { // Log the death of the component.
571 std::shared_ptr<Codec2Client::Component> comp = component.lock();
572 if (!comp) {
573 ALOGE("Codec2 component died.");
574 } else {
575 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
576 }
577 }
578
579 // Report to MediaCodec.
580 sp<CCodec> codec(mCodec.promote());
581 if (!codec || !codec->mCallback) {
582 return;
583 }
584 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
585 }
586
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800587 virtual void onFrameRendered(uint64_t bufferQueueId,
588 int32_t slotId,
589 int64_t timestampNs) override {
590 // TODO: implement
591 (void)bufferQueueId;
592 (void)slotId;
593 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800594 }
595
596 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800597 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800598 sp<CCodec> codec(mCodec.promote());
599 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800600 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800601 }
602 }
603
604private:
605 wp<CCodec> mCodec;
606};
607
608// CCodecCallbackImpl
609
610class CCodecCallbackImpl : public CCodecCallback {
611public:
612 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
613 ~CCodecCallbackImpl() override = default;
614
615 void onError(status_t err, enum ActionCode actionCode) override {
616 mCodec->mCallback->onError(err, actionCode);
617 }
618
619 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
620 mCodec->mCallback->onOutputFramesRendered(
621 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
622 }
623
Pawin Vongmasa36653902018-11-15 00:10:25 -0800624 void onOutputBuffersChanged() override {
625 mCodec->mCallback->onOutputBuffersChanged();
626 }
627
628private:
629 CCodec *mCodec;
630};
631
632// CCodec
633
634CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700635 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
636 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800637}
638
639CCodec::~CCodec() {
640}
641
642std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
643 return mChannel;
644}
645
646status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
647 status_t err = job();
648 if (err != C2_OK) {
649 mCallback->onError(err, ACTION_CODE_FATAL);
650 }
651 return err;
652}
653
654void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
655 auto setAllocating = [this] {
656 Mutexed<State>::Locked state(mState);
657 if (state->get() != RELEASED) {
658 return INVALID_OPERATION;
659 }
660 state->set(ALLOCATING);
661 return OK;
662 };
663 if (tryAndReportOnError(setAllocating) != OK) {
664 return;
665 }
666
667 sp<RefBase> codecInfo;
668 CHECK(msg->findObject("codecInfo", &codecInfo));
669 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
670
671 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
672 allocMsg->setObject("codecInfo", codecInfo);
673 allocMsg->post();
674}
675
676void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
677 if (codecInfo == nullptr) {
678 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
679 return;
680 }
681 ALOGD("allocate(%s)", codecInfo->getCodecName());
682 mClientListener.reset(new ClientListener(this));
683
684 AString componentName = codecInfo->getCodecName();
685 std::shared_ptr<Codec2Client> client;
686
687 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700688 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800689 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800690 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800691 SetPreferredCodec2ComponentStore(
692 std::make_shared<Codec2ClientInterfaceWrapper>(client));
693 }
694
695 std::shared_ptr<Codec2Client::Component> comp =
696 Codec2Client::CreateComponentByName(
697 componentName.c_str(),
698 mClientListener,
699 &client);
700 if (!comp) {
701 ALOGE("Failed Create component: %s", componentName.c_str());
702 Mutexed<State>::Locked state(mState);
703 state->set(RELEASED);
704 state.unlock();
705 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
706 state.lock();
707 return;
708 }
709 ALOGI("Created component [%s]", componentName.c_str());
710 mChannel->setComponent(comp);
711 auto setAllocated = [this, comp, client] {
712 Mutexed<State>::Locked state(mState);
713 if (state->get() != ALLOCATING) {
714 state->set(RELEASED);
715 return UNKNOWN_ERROR;
716 }
717 state->set(ALLOCATED);
718 state->comp = comp;
719 mClient = client;
720 return OK;
721 };
722 if (tryAndReportOnError(setAllocated) != OK) {
723 return;
724 }
725
726 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700727 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
728 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800729 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800730 if (err != OK) {
731 ALOGW("Failed to initialize configuration support");
732 // TODO: report error once we complete implementation.
733 }
734 config->queryConfiguration(comp);
735
736 mCallback->onComponentAllocated(componentName.c_str());
737}
738
739void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
740 auto checkAllocated = [this] {
741 Mutexed<State>::Locked state(mState);
742 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
743 };
744 if (tryAndReportOnError(checkAllocated) != OK) {
745 return;
746 }
747
748 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
749 msg->setMessage("format", format);
750 msg->post();
751}
752
753void CCodec::configure(const sp<AMessage> &msg) {
754 std::shared_ptr<Codec2Client::Component> comp;
755 auto checkAllocated = [this, &comp] {
756 Mutexed<State>::Locked state(mState);
757 if (state->get() != ALLOCATED) {
758 state->set(RELEASED);
759 return UNKNOWN_ERROR;
760 }
761 comp = state->comp;
762 return OK;
763 };
764 if (tryAndReportOnError(checkAllocated) != OK) {
765 return;
766 }
767
768 auto doConfig = [msg, comp, this]() -> status_t {
769 AString mime;
770 if (!msg->findString("mime", &mime)) {
771 return BAD_VALUE;
772 }
773
774 int32_t encoder;
775 if (!msg->findInt32("encoder", &encoder)) {
776 encoder = false;
777 }
778
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800779 int32_t flags;
780 if (!msg->findInt32("flags", &flags)) {
781 return BAD_VALUE;
782 }
783
Pawin Vongmasa36653902018-11-15 00:10:25 -0800784 // TODO: read from intf()
785 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
786 return UNKNOWN_ERROR;
787 }
788
789 int32_t storeMeta;
790 if (encoder
791 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
792 && storeMeta != kMetadataBufferTypeInvalid) {
793 if (storeMeta != kMetadataBufferTypeANWBuffer) {
794 ALOGD("Only ANW buffers are supported for legacy metadata mode");
795 return BAD_VALUE;
796 }
797 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
798 }
799
800 sp<RefBase> obj;
801 sp<Surface> surface;
802 if (msg->findObject("native-window", &obj)) {
803 surface = static_cast<Surface *>(obj.get());
804 setSurface(surface);
805 }
806
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700807 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
808 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800809 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800810 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
811 ALOGD("[%s] buffers are %sbound to CCodec for this session",
812 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800813
Wonsik Kim1114eea2019-02-25 14:35:24 -0800814 // Enforce required parameters
815 int32_t i32;
816 float flt;
817 if (config->mDomain & Config::IS_AUDIO) {
818 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
819 ALOGD("sample rate is missing, which is required for audio components.");
820 return BAD_VALUE;
821 }
822 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
823 ALOGD("channel count is missing, which is required for audio components.");
824 return BAD_VALUE;
825 }
826 if ((config->mDomain & Config::IS_ENCODER)
827 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
828 && !msg->findInt32(KEY_BIT_RATE, &i32)
829 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
830 ALOGD("bitrate is missing, which is required for audio encoders.");
831 return BAD_VALUE;
832 }
833 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800834 int32_t width = 0;
835 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800836 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800837 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800838 ALOGD("width is missing, which is required for image/video components.");
839 return BAD_VALUE;
840 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800841 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800842 ALOGD("height is missing, which is required for image/video components.");
843 return BAD_VALUE;
844 }
845 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700846 int32_t mode = BITRATE_MODE_VBR;
847 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700848 if (!msg->findInt32(KEY_QUALITY, &i32)) {
849 ALOGD("quality is missing, which is required for video encoders in CQ.");
850 return BAD_VALUE;
851 }
852 } else {
853 if (!msg->findInt32(KEY_BIT_RATE, &i32)
854 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
855 ALOGD("bitrate is missing, which is required for video encoders.");
856 return BAD_VALUE;
857 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800858 }
859 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
860 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
861 ALOGD("I frame interval is missing, which is required for video encoders.");
862 return BAD_VALUE;
863 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700864 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
865 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
866 ALOGD("frame rate is missing, which is required for video encoders.");
867 return BAD_VALUE;
868 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800869 }
870 }
871
Pawin Vongmasa36653902018-11-15 00:10:25 -0800872 /*
873 * Handle input surface configuration
874 */
875 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
876 && (config->mDomain & Config::IS_ENCODER)) {
877 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
878 {
879 config->mISConfig->mMinFps = 0;
880 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800881 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800882 config->mISConfig->mMinFps = 1e6 / value;
883 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700884 if (!msg->findFloat(
885 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
886 config->mISConfig->mMaxFps = -1;
887 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800888 config->mISConfig->mMinAdjustedFps = 0;
889 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800890 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800891 if (value < 0 && value >= INT32_MIN) {
892 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700893 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800894 } else if (value > 0 && value <= INT32_MAX) {
895 config->mISConfig->mMinAdjustedFps = 1e6 / value;
896 }
897 }
898 }
899
900 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700901 bool captureFpsFound = false;
902 double timeLapseFps;
903 float captureRate;
904 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
905 config->mISConfig->mCaptureFps = timeLapseFps;
906 captureFpsFound = true;
907 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
908 config->mISConfig->mCaptureFps = captureRate;
909 captureFpsFound = true;
910 }
911 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800912 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
913 }
914 }
915
916 {
917 config->mISConfig->mSuspended = false;
918 config->mISConfig->mSuspendAtUs = -1;
919 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800920 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800921 config->mISConfig->mSuspended = true;
922 }
923 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700924 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800925 }
926
927 /*
928 * Handle desired color format.
929 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700930 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800931 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700932 int32_t format = 0;
933 // Query vendor format for Flexible YUV
934 std::vector<std::unique_ptr<C2Param>> heapParams;
935 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
936 if (mClient->query(
937 {},
938 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
939 C2_MAY_BLOCK,
940 &heapParams) == C2_OK
941 && heapParams.size() == 1u) {
942 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
943 heapParams[0].get());
944 } else {
945 pixelFormatInfo = nullptr;
946 }
947 std::optional<uint32_t> flexPixelFormat{};
948 std::optional<uint32_t> flexPlanarPixelFormat{};
949 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
950 if (pixelFormatInfo && *pixelFormatInfo) {
951 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
952 const C2FlexiblePixelFormatDescriptorStruct &desc =
953 pixelFormatInfo->m.values[i];
954 if (desc.bitDepth != 8
955 || desc.subsampling != C2Color::YUV_420
956 // TODO(b/180076105): some device report wrong layout
957 // || desc.layout == C2Color::INTERLEAVED_PACKED
958 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
959 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
960 continue;
961 }
962 if (!flexPixelFormat) {
963 flexPixelFormat = desc.pixelFormat;
964 }
965 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
966 flexPlanarPixelFormat = desc.pixelFormat;
967 }
968 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
969 flexSemiPlanarPixelFormat = desc.pixelFormat;
970 }
971 }
972 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800973 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700974 // Also handle default color format (encoders require color format, so this is only
975 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -0800976 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700977 if (surface == nullptr) {
978 format = flexPixelFormat.value_or(COLOR_FormatYUV420Flexible);
979 } else {
980 format = COLOR_FormatSurface;
981 }
982 defaultColorFormat = format;
983 }
984 } else {
985 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
986 switch (format) {
987 case COLOR_FormatYUV420Flexible:
988 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
989 break;
990 case COLOR_FormatYUV420Planar:
991 case COLOR_FormatYUV420PackedPlanar:
992 format = flexPlanarPixelFormat.value_or(
993 flexPixelFormat.value_or(format));
994 break;
995 case COLOR_FormatYUV420SemiPlanar:
996 case COLOR_FormatYUV420PackedSemiPlanar:
997 format = flexSemiPlanarPixelFormat.value_or(
998 flexPixelFormat.value_or(format));
999 break;
1000 default:
1001 // No-op
1002 break;
1003 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001004 }
1005 }
1006
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001007 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001008 msg->setInt32("android._color-format", format);
1009 }
1010 }
1011
Wonsik Kim40aaf952021-01-29 14:58:12 -08001012 // get color aspects
1013 getColorAspectsFromFormat(msg, config->mClientColorAspects);
1014
Wonsik Kim77e97c72021-01-20 10:33:22 -08001015 /*
1016 * Handle dataspace
1017 */
1018 int32_t usingRecorder;
1019 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1020 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1021 int32_t width, height;
1022 if (msg->findInt32("width", &width)
1023 && msg->findInt32("height", &height)) {
Wonsik Kim40aaf952021-01-29 14:58:12 -08001024 setDefaultCodecColorAspectsIfNeeded(config->mClientColorAspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001025 // TODO: read dataspace / color aspect from the component
Wonsik Kim40aaf952021-01-29 14:58:12 -08001026 setColorAspectsIntoFormat(
1027 config->mClientColorAspects, const_cast<sp<AMessage> &>(msg));
1028 dataSpace = getDataSpaceForColorAspects(
1029 config->mClientColorAspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001030 }
1031 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1032 ALOGD("setting dataspace to %x", dataSpace);
1033 }
1034
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001035 int32_t subscribeToAllVendorParams;
1036 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1037 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1038 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1039 }
1040 }
1041
Pawin Vongmasa36653902018-11-15 00:10:25 -08001042 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001043 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1044 // the behavior here.
1045 sp<AMessage> sdkParams = msg;
1046 int32_t videoBitrate;
1047 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1048 sdkParams = msg->dup();
1049 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1050 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001051 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001052 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001053 if (err != OK) {
1054 ALOGW("failed to convert configuration to c2 params");
1055 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001056
1057 int32_t maxBframes = 0;
1058 if ((config->mDomain & Config::IS_ENCODER)
1059 && (config->mDomain & Config::IS_VIDEO)
1060 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1061 && maxBframes > 0) {
1062 std::unique_ptr<C2StreamGopTuning::output> gop =
1063 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1064 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1065 gop->m.values[1] = {
1066 C2Config::picture_type_t(P_FRAME | B_FRAME),
1067 uint32_t(maxBframes)
1068 };
1069 configUpdate.push_back(std::move(gop));
1070 }
1071
Pawin Vongmasa36653902018-11-15 00:10:25 -08001072 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1073 if (err != OK) {
1074 ALOGW("failed to configure c2 params");
1075 return err;
1076 }
1077
1078 std::vector<std::unique_ptr<C2Param>> params;
1079 C2StreamUsageTuning::input usage(0u, 0u);
1080 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001081 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001082
Wonsik Kim58d83332021-02-07 22:19:56 -08001083 C2Param::Index colorAspectsRequestIndex =
1084 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001085 std::initializer_list<C2Param::Index> indices {
Wonsik Kim58d83332021-02-07 22:19:56 -08001086 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001087 };
1088 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001089 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001090 indices,
1091 C2_DONT_BLOCK,
1092 &params);
1093 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1094 ALOGE("Failed to query component interface: %d", c2err);
1095 return UNKNOWN_ERROR;
1096 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001097 if (usage) {
1098 if (usage.value & C2MemoryUsage::CPU_READ) {
1099 config->mInputFormat->setInt32("using-sw-read-often", true);
1100 }
1101 if (config->mISConfig) {
1102 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1103 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1104 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001105 }
1106
1107 // NOTE: we don't blindly use client specified input size if specified as clients
1108 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1109 // client specified size is only used to ask for bigger buffers than component suggested
1110 // size.
1111 int32_t clientInputSize = 0;
1112 bool clientSpecifiedInputSize =
1113 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1114 // TEMP: enforce minimum buffer size of 1MB for video decoders
1115 // and 16K / 4K for audio encoders/decoders
1116 if (maxInputSize.value == 0) {
1117 if (config->mDomain & Config::IS_AUDIO) {
1118 maxInputSize.value = encoder ? 16384 : 4096;
1119 } else if (!encoder) {
1120 maxInputSize.value = 1048576u;
1121 }
1122 }
1123
1124 // verify that CSD fits into this size (if defined)
1125 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1126 sp<ABuffer> csd;
1127 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1128 if (csd && csd->size() > maxInputSize.value) {
1129 maxInputSize.value = csd->size();
1130 }
1131 }
1132 }
1133
1134 // TODO: do this based on component requiring linear allocator for input
1135 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1136 if (clientSpecifiedInputSize) {
1137 // Warn that we're overriding client's max input size if necessary.
1138 if ((uint32_t)clientInputSize < maxInputSize.value) {
1139 ALOGD("client requested max input size %d, which is smaller than "
1140 "what component recommended (%u); overriding with component "
1141 "recommendation.", clientInputSize, maxInputSize.value);
1142 ALOGW("This behavior is subject to change. It is recommended that "
1143 "app developers double check whether the requested "
1144 "max input size is in reasonable range.");
1145 } else {
1146 maxInputSize.value = clientInputSize;
1147 }
1148 }
1149 // Pass max input size on input format to the buffer channel (if supplied by the
1150 // component or by a default)
1151 if (maxInputSize.value) {
1152 config->mInputFormat->setInt32(
1153 KEY_MAX_INPUT_SIZE,
1154 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1155 }
1156 }
1157
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001158 int32_t clientPrepend;
1159 if ((config->mDomain & Config::IS_VIDEO)
1160 && (config->mDomain & Config::IS_ENCODER)
1161 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1162 && clientPrepend
1163 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1164 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1165 return BAD_VALUE;
1166 }
1167
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001168 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001169 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1170 // propagate HDR static info to output format for both encoders and decoders
1171 // if component supports this info, we will update from component, but only the raw port,
1172 // so don't propagate if component already filled it in.
1173 sp<ABuffer> hdrInfo;
1174 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1175 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1176 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1177 }
1178
1179 // Set desired color format from configuration parameter
1180 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001181 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1182 format = defaultColorFormat;
1183 }
1184 if (config->mDomain & Config::IS_ENCODER) {
1185 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001186 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1187 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001188 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001189 } else {
1190 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001191 }
1192 }
1193
1194 // propagate encoder delay and padding to output format
1195 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1196 int delay = 0;
1197 if (msg->findInt32("encoder-delay", &delay)) {
1198 config->mOutputFormat->setInt32("encoder-delay", delay);
1199 }
1200 int padding = 0;
1201 if (msg->findInt32("encoder-padding", &padding)) {
1202 config->mOutputFormat->setInt32("encoder-padding", padding);
1203 }
1204 }
1205
1206 // set channel-mask
1207 if (config->mDomain & Config::IS_AUDIO) {
1208 int32_t mask;
1209 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1210 if (config->mDomain & Config::IS_ENCODER) {
1211 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1212 } else {
1213 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1214 }
1215 }
1216 }
1217
Wonsik Kim58d83332021-02-07 22:19:56 -08001218 std::unique_ptr<C2Param> colorTransferRequestParam;
1219 for (std::unique_ptr<C2Param> &param : params) {
1220 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1221 ALOGI("found color transfer request param");
1222 colorTransferRequestParam = std::move(param);
1223 }
1224 }
1225 int32_t colorTransferRequest = 0;
1226 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1227 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1228 colorTransferRequest = 0;
1229 }
1230
1231 if (colorTransferRequest != 0) {
1232 if (colorTransferRequestParam && *colorTransferRequestParam) {
1233 C2StreamColorAspectsInfo::output *info =
1234 static_cast<C2StreamColorAspectsInfo::output *>(
1235 colorTransferRequestParam.get());
1236 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1237 colorTransferRequest = 0;
1238 }
1239 } else {
1240 colorTransferRequest = 0;
1241 }
1242 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1243 }
1244
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001245 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1246 // Need to get stride/vstride
1247 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1248 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1249 // TODO: retrieve these values without allocating a buffer.
1250 // Currently allocating a buffer is necessary to retrieve the layout.
1251 int64_t blockUsage =
1252 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1253 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1254 width, height, pixelFormat, blockUsage, {comp->getName()});
1255 sp<GraphicBlockBuffer> buffer;
1256 if (block) {
1257 buffer = GraphicBlockBuffer::Allocate(
1258 config->mInputFormat,
1259 block,
1260 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1261 } else {
1262 ALOGD("Failed to allocate a graphic block "
1263 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1264 width, height, pixelFormat, (long long)blockUsage);
1265 // This means that byte buffer mode is not supported in this configuration
1266 // anyway. Skip setting stride/vstride to input format.
1267 }
1268 if (buffer) {
1269 sp<ABuffer> imageData = buffer->getImageData();
1270 MediaImage2 *img = nullptr;
1271 if (imageData && imageData->data()
1272 && imageData->size() >= sizeof(MediaImage2)) {
1273 img = (MediaImage2*)imageData->data();
1274 }
1275 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1276 int32_t stride = img->mPlane[0].mRowInc;
1277 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1278 if (img->mNumPlanes > 1 && stride > 0) {
1279 int64_t offsetDelta =
1280 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1281 if (offsetDelta % stride == 0) {
1282 int32_t vstride = int32_t(offsetDelta / stride);
1283 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1284 } else {
1285 ALOGD("Cannot report accurate slice height: "
1286 "offsetDelta = %lld stride = %d",
1287 (long long)offsetDelta, stride);
1288 }
1289 }
1290 }
1291 }
1292 }
1293 }
1294
1295 ALOGD("setup formats input: %s",
1296 config->mInputFormat->debugString().c_str());
1297 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001298 config->mOutputFormat->debugString().c_str());
1299 return OK;
1300 };
1301 if (tryAndReportOnError(doConfig) != OK) {
1302 return;
1303 }
1304
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001305 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1306 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001307
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001308 config->queryConfiguration(comp);
1309
Pawin Vongmasa36653902018-11-15 00:10:25 -08001310 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1311}
1312
1313void CCodec::initiateCreateInputSurface() {
1314 status_t err = [this] {
1315 Mutexed<State>::Locked state(mState);
1316 if (state->get() != ALLOCATED) {
1317 return UNKNOWN_ERROR;
1318 }
1319 // TODO: read it from intf() properly.
1320 if (state->comp->getName().find("encoder") == std::string::npos) {
1321 return INVALID_OPERATION;
1322 }
1323 return OK;
1324 }();
1325 if (err != OK) {
1326 mCallback->onInputSurfaceCreationFailed(err);
1327 return;
1328 }
1329
1330 (new AMessage(kWhatCreateInputSurface, this))->post();
1331}
1332
Lajos Molnar47118272019-01-31 16:28:04 -08001333sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1334 using namespace android::hardware::media::omx::V1_0;
1335 using namespace android::hardware::media::omx::V1_0::utils;
1336 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1337 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1338 android::sp<IOmx> omx = IOmx::getService();
1339 typedef android::hardware::graphics::bufferqueue::V1_0::
1340 IGraphicBufferProducer HGraphicBufferProducer;
1341 typedef android::hardware::media::omx::V1_0::
1342 IGraphicBufferSource HGraphicBufferSource;
1343 OmxStatus s;
1344 android::sp<HGraphicBufferProducer> gbp;
1345 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001346
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001347 using ::android::hardware::Return;
1348 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001349 [&s, &gbp, &gbs](
1350 OmxStatus status,
1351 const android::sp<HGraphicBufferProducer>& producer,
1352 const android::sp<HGraphicBufferSource>& source) {
1353 s = status;
1354 gbp = producer;
1355 gbs = source;
1356 });
1357 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001358 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001359 }
1360
1361 return nullptr;
1362}
1363
1364sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1365 sp<PersistentSurface> surface(CreateInputSurface());
1366
1367 if (surface == nullptr) {
1368 surface = CreateOmxInputSurface();
1369 }
1370
1371 return surface;
1372}
1373
Pawin Vongmasa36653902018-11-15 00:10:25 -08001374void CCodec::createInputSurface() {
1375 status_t err;
1376 sp<IGraphicBufferProducer> bufferProducer;
1377
1378 sp<AMessage> inputFormat;
1379 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001380 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001381 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001382 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1383 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001384 inputFormat = config->mInputFormat;
1385 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001386 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001387 }
1388
Lajos Molnar47118272019-01-31 16:28:04 -08001389 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001390 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1391 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1392 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001393
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001394 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001395 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1396 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001397 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001398 inputSurface));
1399 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001400 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001401 int32_t width = 0;
1402 (void)outputFormat->findInt32("width", &width);
1403 int32_t height = 0;
1404 (void)outputFormat->findInt32("height", &height);
1405 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001406 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001407 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001408 } else {
1409 ALOGE("Corrupted input surface");
1410 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1411 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001412 }
1413
1414 if (err != OK) {
1415 ALOGE("Failed to set up input surface: %d", err);
1416 mCallback->onInputSurfaceCreationFailed(err);
1417 return;
1418 }
1419
1420 mCallback->onInputSurfaceCreated(
1421 inputFormat,
1422 outputFormat,
1423 new BufferProducerWrapper(bufferProducer));
1424}
1425
1426status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001427 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1428 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001429 config->mUsingSurface = true;
1430
1431 // we are now using surface - apply default color aspects to input format - as well as
1432 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001433 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001434 ALOGD("input format %s to %s",
1435 inputFormatChanged ? "changed" : "unchanged",
1436 config->mInputFormat->debugString().c_str());
1437
1438 // configure dataspace
1439 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1440 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1441 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1442 surface->setDataSpace(dataSpace);
1443
1444 status_t err = mChannel->setInputSurface(surface);
1445 if (err != OK) {
1446 // undo input format update
1447 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001448 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001449 return err;
1450 }
1451 config->mInputSurface = surface;
1452
1453 if (config->mISConfig) {
1454 surface->configure(*config->mISConfig);
1455 } else {
1456 ALOGD("ISConfig: no configuration");
1457 }
1458
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001459 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001460}
1461
1462void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1463 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1464 msg->setObject("surface", surface);
1465 msg->post();
1466}
1467
1468void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1469 sp<AMessage> inputFormat;
1470 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001471 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001472 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001473 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1474 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001475 inputFormat = config->mInputFormat;
1476 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001477 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001478 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001479 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1480 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1481 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1482 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001483 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1484 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1485 if (err != OK) {
1486 ALOGE("Failed to set up input surface: %d", err);
1487 mCallback->onInputSurfaceDeclined(err);
1488 return;
1489 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001490 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001491 int32_t width = 0;
1492 (void)outputFormat->findInt32("width", &width);
1493 int32_t height = 0;
1494 (void)outputFormat->findInt32("height", &height);
1495 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001496 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001497 if (err != OK) {
1498 ALOGE("Failed to set up input surface: %d", err);
1499 mCallback->onInputSurfaceDeclined(err);
1500 return;
1501 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001502 } else {
1503 ALOGE("Failed to set input surface: Corrupted surface.");
1504 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1505 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001506 }
1507 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1508}
1509
1510void CCodec::initiateStart() {
1511 auto setStarting = [this] {
1512 Mutexed<State>::Locked state(mState);
1513 if (state->get() != ALLOCATED) {
1514 return UNKNOWN_ERROR;
1515 }
1516 state->set(STARTING);
1517 return OK;
1518 };
1519 if (tryAndReportOnError(setStarting) != OK) {
1520 return;
1521 }
1522
1523 (new AMessage(kWhatStart, this))->post();
1524}
1525
1526void CCodec::start() {
1527 std::shared_ptr<Codec2Client::Component> comp;
1528 auto checkStarting = [this, &comp] {
1529 Mutexed<State>::Locked state(mState);
1530 if (state->get() != STARTING) {
1531 return UNKNOWN_ERROR;
1532 }
1533 comp = state->comp;
1534 return OK;
1535 };
1536 if (tryAndReportOnError(checkStarting) != OK) {
1537 return;
1538 }
1539
1540 c2_status_t err = comp->start();
1541 if (err != C2_OK) {
1542 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1543 ACTION_CODE_FATAL);
1544 return;
1545 }
1546 sp<AMessage> inputFormat;
1547 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001548 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001549 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001550 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001551 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1552 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001553 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001554 // start triggers format dup
1555 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001556 if (config->mInputSurface) {
1557 err2 = config->mInputSurface->start();
1558 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001559 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001560 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001561 if (err2 != OK) {
1562 mCallback->onError(err2, ACTION_CODE_FATAL);
1563 return;
1564 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001565 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001566 if (err2 != OK) {
1567 mCallback->onError(err2, ACTION_CODE_FATAL);
1568 return;
1569 }
1570
1571 auto setRunning = [this] {
1572 Mutexed<State>::Locked state(mState);
1573 if (state->get() != STARTING) {
1574 return UNKNOWN_ERROR;
1575 }
1576 state->set(RUNNING);
1577 return OK;
1578 };
1579 if (tryAndReportOnError(setRunning) != OK) {
1580 return;
1581 }
1582 mCallback->onStartCompleted();
1583
1584 (void)mChannel->requestInitialInputBuffers();
1585}
1586
1587void CCodec::initiateShutdown(bool keepComponentAllocated) {
1588 if (keepComponentAllocated) {
1589 initiateStop();
1590 } else {
1591 initiateRelease();
1592 }
1593}
1594
1595void CCodec::initiateStop() {
1596 {
1597 Mutexed<State>::Locked state(mState);
1598 if (state->get() == ALLOCATED
1599 || state->get() == RELEASED
1600 || state->get() == STOPPING
1601 || state->get() == RELEASING) {
1602 // We're already stopped, released, or doing it right now.
1603 state.unlock();
1604 mCallback->onStopCompleted();
1605 state.lock();
1606 return;
1607 }
1608 state->set(STOPPING);
1609 }
1610
Wonsik Kim936a89c2020-05-08 16:07:50 -07001611 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001612 (new AMessage(kWhatStop, this))->post();
1613}
1614
1615void CCodec::stop() {
1616 std::shared_ptr<Codec2Client::Component> comp;
1617 {
1618 Mutexed<State>::Locked state(mState);
1619 if (state->get() == RELEASING) {
1620 state.unlock();
1621 // We're already stopped or release is in progress.
1622 mCallback->onStopCompleted();
1623 state.lock();
1624 return;
1625 } else if (state->get() != STOPPING) {
1626 state.unlock();
1627 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1628 state.lock();
1629 return;
1630 }
1631 comp = state->comp;
1632 }
1633 status_t err = comp->stop();
1634 if (err != C2_OK) {
1635 // TODO: convert err into status_t
1636 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1637 }
1638
1639 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001640 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1641 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001642 if (config->mInputSurface) {
1643 config->mInputSurface->disconnect();
1644 config->mInputSurface = nullptr;
1645 }
1646 }
1647 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001648 Mutexed<State>::Locked state(mState);
1649 if (state->get() == STOPPING) {
1650 state->set(ALLOCATED);
1651 }
1652 }
1653 mCallback->onStopCompleted();
1654}
1655
1656void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001657 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001658 {
1659 Mutexed<State>::Locked state(mState);
1660 if (state->get() == RELEASED || state->get() == RELEASING) {
1661 // We're already released or doing it right now.
1662 if (sendCallback) {
1663 state.unlock();
1664 mCallback->onReleaseCompleted();
1665 state.lock();
1666 }
1667 return;
1668 }
1669 if (state->get() == ALLOCATING) {
1670 state->set(RELEASING);
1671 // With the altered state allocate() would fail and clean up.
1672 if (sendCallback) {
1673 state.unlock();
1674 mCallback->onReleaseCompleted();
1675 state.lock();
1676 }
1677 return;
1678 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001679 if (state->get() == STARTING
1680 || state->get() == RUNNING
1681 || state->get() == STOPPING) {
1682 // Input surface may have been started, so clean up is needed.
1683 clearInputSurfaceIfNeeded = true;
1684 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001685 state->set(RELEASING);
1686 }
1687
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001688 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001689 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1690 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001691 if (config->mInputSurface) {
1692 config->mInputSurface->disconnect();
1693 config->mInputSurface = nullptr;
1694 }
1695 }
1696
Wonsik Kim936a89c2020-05-08 16:07:50 -07001697 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001698 // thiz holds strong ref to this while the thread is running.
1699 sp<CCodec> thiz(this);
1700 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1701}
1702
1703void CCodec::release(bool sendCallback) {
1704 std::shared_ptr<Codec2Client::Component> comp;
1705 {
1706 Mutexed<State>::Locked state(mState);
1707 if (state->get() == RELEASED) {
1708 if (sendCallback) {
1709 state.unlock();
1710 mCallback->onReleaseCompleted();
1711 state.lock();
1712 }
1713 return;
1714 }
1715 comp = state->comp;
1716 }
1717 comp->release();
1718
1719 {
1720 Mutexed<State>::Locked state(mState);
1721 state->set(RELEASED);
1722 state->comp.reset();
1723 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001724 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001725 if (sendCallback) {
1726 mCallback->onReleaseCompleted();
1727 }
1728}
1729
1730status_t CCodec::setSurface(const sp<Surface> &surface) {
1731 return mChannel->setSurface(surface);
1732}
1733
1734void CCodec::signalFlush() {
1735 status_t err = [this] {
1736 Mutexed<State>::Locked state(mState);
1737 if (state->get() == FLUSHED) {
1738 return ALREADY_EXISTS;
1739 }
1740 if (state->get() != RUNNING) {
1741 return UNKNOWN_ERROR;
1742 }
1743 state->set(FLUSHING);
1744 return OK;
1745 }();
1746 switch (err) {
1747 case ALREADY_EXISTS:
1748 mCallback->onFlushCompleted();
1749 return;
1750 case OK:
1751 break;
1752 default:
1753 mCallback->onError(err, ACTION_CODE_FATAL);
1754 return;
1755 }
1756
1757 mChannel->stop();
1758 (new AMessage(kWhatFlush, this))->post();
1759}
1760
1761void CCodec::flush() {
1762 std::shared_ptr<Codec2Client::Component> comp;
1763 auto checkFlushing = [this, &comp] {
1764 Mutexed<State>::Locked state(mState);
1765 if (state->get() != FLUSHING) {
1766 return UNKNOWN_ERROR;
1767 }
1768 comp = state->comp;
1769 return OK;
1770 };
1771 if (tryAndReportOnError(checkFlushing) != OK) {
1772 return;
1773 }
1774
1775 std::list<std::unique_ptr<C2Work>> flushedWork;
1776 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1777 {
1778 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1779 flushedWork.splice(flushedWork.end(), *queue);
1780 }
1781 if (err != C2_OK) {
1782 // TODO: convert err into status_t
1783 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1784 }
1785
1786 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001787
1788 {
1789 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001790 if (state->get() == FLUSHING) {
1791 state->set(FLUSHED);
1792 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001793 }
1794 mCallback->onFlushCompleted();
1795}
1796
1797void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001798 std::shared_ptr<Codec2Client::Component> comp;
1799 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001800 Mutexed<State>::Locked state(mState);
1801 if (state->get() != FLUSHED) {
1802 return UNKNOWN_ERROR;
1803 }
1804 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001805 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001806 return OK;
1807 };
1808 if (tryAndReportOnError(setResuming) != OK) {
1809 return;
1810 }
1811
Wonsik Kime75a5da2020-02-14 17:29:03 -08001812 {
1813 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1814 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001815 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001816 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001817 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001818 }
1819
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001820 (void)mChannel->start(nullptr, nullptr, [&]{
1821 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1822 const std::unique_ptr<Config> &config = *configLocked;
1823 return config->mBuffersBoundToCodec;
1824 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001825
1826 {
1827 Mutexed<State>::Locked state(mState);
1828 if (state->get() != RESUMING) {
1829 state.unlock();
1830 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1831 state.lock();
1832 return;
1833 }
1834 state->set(RUNNING);
1835 }
1836
1837 (void)mChannel->requestInitialInputBuffers();
1838}
1839
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001840void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001841 std::shared_ptr<Codec2Client::Component> comp;
1842 auto checkState = [this, &comp] {
1843 Mutexed<State>::Locked state(mState);
1844 if (state->get() == RELEASED) {
1845 return INVALID_OPERATION;
1846 }
1847 comp = state->comp;
1848 return OK;
1849 };
1850 if (tryAndReportOnError(checkState) != OK) {
1851 return;
1852 }
1853
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001854 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1855 // the behavior here.
1856 sp<AMessage> params = msg;
1857 int32_t bitrate;
1858 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1859 params = msg->dup();
1860 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1861 }
1862
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001863 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1864 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001865
1866 /**
1867 * Handle input surface parameters
1868 */
1869 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001870 && (config->mDomain & Config::IS_ENCODER)
1871 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001872 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001873
1874 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1875 config->mISConfig->mStopped = false;
1876 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1877 config->mISConfig->mStopped = true;
1878 }
1879
1880 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001881 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001882 config->mISConfig->mSuspended = value;
1883 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001884 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001885 }
1886
1887 (void)config->mInputSurface->configure(*config->mISConfig);
1888 if (config->mISConfig->mStopped) {
1889 config->mInputFormat->setInt64(
1890 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1891 }
1892 }
1893
1894 std::vector<std::unique_ptr<C2Param>> configUpdate;
1895 (void)config->getConfigUpdateFromSdkParams(
1896 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1897 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1898 // Parameter synchronization is not defined when using input surface. For now, route
1899 // these directly to the component.
1900 if (config->mInputSurface == nullptr
1901 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1902 || comp->getName().find("c2.android.") == 0)) {
1903 mChannel->setParameters(configUpdate);
1904 } else {
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001905 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001906 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001907 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001908 }
1909}
1910
1911void CCodec::signalEndOfInputStream() {
1912 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1913}
1914
1915void CCodec::signalRequestIDRFrame() {
1916 std::shared_ptr<Codec2Client::Component> comp;
1917 {
1918 Mutexed<State>::Locked state(mState);
1919 if (state->get() == RELEASED) {
1920 ALOGD("no IDR request sent since component is released");
1921 return;
1922 }
1923 comp = state->comp;
1924 }
1925 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001926 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1927 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001928 std::vector<std::unique_ptr<C2Param>> params;
1929 params.push_back(
1930 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1931 config->setParameters(comp, params, C2_MAY_BLOCK);
1932}
1933
Wonsik Kimab34ed62019-01-31 15:28:46 -08001934void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001935 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001936 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1937 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001938 }
1939 (new AMessage(kWhatWorkDone, this))->post();
1940}
1941
Wonsik Kimab34ed62019-01-31 15:28:46 -08001942void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1943 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001944 if (arrayIndex == 0) {
1945 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001946 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1947 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001948 if (config->mInputSurface) {
1949 config->mInputSurface->onInputBufferDone(frameIndex);
1950 }
1951 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001952}
1953
Wonsik Kim40aaf952021-01-29 14:58:12 -08001954static void HandleDataspace(
1955 android_dataspace dataspace, ColorAspects *colorAspects, sp<AMessage> *format) {
1956 ColorUtils::convertDataSpaceToV0(dataspace);
1957 int32_t range, standard, transfer;
1958 range = (dataspace & HAL_DATASPACE_RANGE_MASK) >> HAL_DATASPACE_RANGE_SHIFT;
1959 if (range == 0) {
1960 range = ColorUtils::wrapColorAspectsIntoColorRange(
1961 colorAspects->mRange);
1962 }
1963 standard = (dataspace & HAL_DATASPACE_STANDARD_MASK) >> HAL_DATASPACE_STANDARD_SHIFT;
1964 if (standard == 0) {
1965 standard = ColorUtils::wrapColorAspectsIntoColorStandard(
1966 colorAspects->mPrimaries,
1967 colorAspects->mMatrixCoeffs);
1968 }
1969 transfer = (dataspace & HAL_DATASPACE_TRANSFER_MASK) >> HAL_DATASPACE_TRANSFER_SHIFT;
1970 if (transfer == 0) {
1971 transfer = ColorUtils::wrapColorAspectsIntoColorTransfer(
1972 colorAspects->mTransfer);
1973 }
1974 ColorAspects newColorAspects;
1975 ColorUtils::convertPlatformColorAspectsToCodecAspects(
1976 range, standard, transfer, newColorAspects);
1977 if (ColorUtils::checkIfAspectsChangedAndUnspecifyThem(
1978 newColorAspects, *colorAspects)) {
1979 *format = (*format)->dup();
1980 (*format)->setInt32(KEY_COLOR_RANGE, range);
1981 (*format)->setInt32(KEY_COLOR_STANDARD, standard);
1982 (*format)->setInt32(KEY_COLOR_TRANSFER, transfer);
1983 // Record current color aspects into |colorAspects|.
1984 // NOTE: newColorAspects could have been modified by
1985 // checkIfAspectsChangedAndUnspecifyThem() above,
1986 // so *colorAspects = newColorAspects does not work as intended.
1987 ColorUtils::convertPlatformColorAspectsToCodecAspects(
1988 range, standard, transfer, *colorAspects);
1989 }
1990}
1991
Pawin Vongmasa36653902018-11-15 00:10:25 -08001992void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1993 TimePoint now = std::chrono::steady_clock::now();
1994 CCodecWatchdog::getInstance()->watch(this);
1995 switch (msg->what()) {
1996 case kWhatAllocate: {
1997 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001998 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001999 sp<RefBase> obj;
2000 CHECK(msg->findObject("codecInfo", &obj));
2001 allocate((MediaCodecInfo *)obj.get());
2002 break;
2003 }
2004 case kWhatConfigure: {
2005 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002006 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002007 sp<AMessage> format;
2008 CHECK(msg->findMessage("format", &format));
2009 configure(format);
2010 break;
2011 }
2012 case kWhatStart: {
2013 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002014 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002015 start();
2016 break;
2017 }
2018 case kWhatStop: {
2019 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002020 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002021 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002022 break;
2023 }
2024 case kWhatFlush: {
2025 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002026 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002027 flush();
2028 break;
2029 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002030 case kWhatRelease: {
2031 mChannel->release();
2032 mClient.reset();
2033 mClientListener.reset();
2034 break;
2035 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002036 case kWhatCreateInputSurface: {
2037 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002038 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002039 createInputSurface();
2040 break;
2041 }
2042 case kWhatSetInputSurface: {
2043 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002044 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002045 sp<RefBase> obj;
2046 CHECK(msg->findObject("surface", &obj));
2047 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2048 setInputSurface(surface);
2049 break;
2050 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002051 case kWhatWorkDone: {
2052 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002053 bool shouldPost = false;
2054 {
2055 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2056 if (queue->empty()) {
2057 break;
2058 }
2059 work.swap(queue->front());
2060 queue->pop_front();
2061 shouldPost = !queue->empty();
2062 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002063 if (shouldPost) {
2064 (new AMessage(kWhatWorkDone, this))->post();
2065 }
2066
Pawin Vongmasa36653902018-11-15 00:10:25 -08002067 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002068 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2069 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002070 Config::Watcher<C2StreamInitDataInfo::output> initData =
2071 config->watch<C2StreamInitDataInfo::output>();
2072 if (!work->worklets.empty()
2073 && (work->worklets.front()->output.flags
2074 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
2075
2076 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002077 std::vector<std::unique_ptr<C2Param>> updates;
2078 for (const std::unique_ptr<C2Param> &param
2079 : work->worklets.front()->output.configUpdate) {
2080 updates.push_back(C2Param::Copy(*param));
2081 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002082 unsigned stream = 0;
2083 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2084 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2085 // move all info into output-stream #0 domain
2086 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
2087 }
George Burgess IVc813a592020-02-22 22:54:44 -08002088
2089 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2090 // for now only do the first block
2091 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002092 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2093 // block.crop().left, block.crop().top,
2094 // block.crop().width, block.crop().height,
2095 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08002096 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08002097 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
2098 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07002099 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002100 }
2101 ++stream;
2102 }
2103
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002104 sp<AMessage> outputFormat = config->mOutputFormat;
2105 config->updateConfiguration(updates, config->mOutputDomain);
Wonsik Kim40aaf952021-01-29 14:58:12 -08002106 if (config->mInputSurface) {
2107 android_dataspace ds = config->mInputSurface->getDataspace();
2108 HandleDataspace(ds, &config->mClientColorAspects, &config->mOutputFormat);
2109 }
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002110 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002111
2112 // copy standard infos to graphic buffers if not already present (otherwise, we
2113 // may overwrite the actual intermediate value with a final value)
2114 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07002115 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002116 C2StreamRotationInfo::output::PARAM_TYPE,
2117 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2118 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2119 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08002120 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08002121 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2122 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2123 };
2124 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2125 if (buf->data().graphicBlocks().size()) {
2126 for (C2Param::Index ix : stdGfxInfos) {
2127 if (!buf->hasInfo(ix)) {
2128 const C2Param *param =
2129 config->getConfigParameterValue(ix.withStream(stream));
2130 if (param) {
2131 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2132 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2133 }
2134 }
2135 }
2136 }
2137 ++stream;
2138 }
2139 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002140 if (config->mInputSurface) {
2141 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2142 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002143 mChannel->onWorkDone(
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002144 std::move(work), config->mOutputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002145 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002146 break;
2147 }
2148 case kWhatWatch: {
2149 // watch message already posted; no-op.
2150 break;
2151 }
2152 default: {
2153 ALOGE("unrecognized message");
2154 break;
2155 }
2156 }
2157 setDeadline(TimePoint::max(), 0ms, "none");
2158}
2159
2160void CCodec::setDeadline(
2161 const TimePoint &now,
2162 const std::chrono::milliseconds &timeout,
2163 const char *name) {
2164 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2165 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2166 deadline->set(now + (timeout * mult), name);
2167}
2168
2169void CCodec::initiateReleaseIfStuck() {
2170 std::string name;
2171 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002172 {
2173 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002174 if (deadline->get() < std::chrono::steady_clock::now()) {
2175 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002176 }
2177 if (deadline->get() != TimePoint::max()) {
2178 pendingDeadline = true;
2179 }
2180 }
2181 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002182 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2183 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2184 if (elapsed >= kWorkDurationThreshold) {
2185 name = "queue";
2186 }
2187 if (elapsed > 0s) {
2188 pendingDeadline = true;
2189 }
2190 }
2191 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002192 // We're not stuck.
2193 if (pendingDeadline) {
2194 // If we are not stuck yet but still has deadline coming up,
2195 // post watch message to check back later.
2196 (new AMessage(kWhatWatch, this))->post();
2197 }
2198 return;
2199 }
2200
2201 ALOGW("previous call to %s exceeded timeout", name.c_str());
2202 initiateRelease(false);
2203 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2204}
2205
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002206// static
2207PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002208 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002209 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002210 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002211 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2212 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002213 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002214 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2215 sp<IGraphicBufferProducer> gbp;
2216 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2217 status_t err = gbs->initCheck();
2218 if (err != OK) {
2219 ALOGE("Failed to create persistent input surface: error %d", err);
2220 return nullptr;
2221 }
2222 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002223 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002224 } else {
2225 return nullptr;
2226 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002227 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002228 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002229 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002230 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002231 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002232}
2233
Wonsik Kimffb889a2020-05-28 11:32:25 -07002234class IntfCache {
2235public:
2236 IntfCache() = default;
2237
2238 status_t init(const std::string &name) {
2239 std::shared_ptr<Codec2Client::Interface> intf{
2240 Codec2Client::CreateInterfaceByName(name.c_str())};
2241 if (!intf) {
2242 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2243 mInitStatus = NO_INIT;
2244 return NO_INIT;
2245 }
2246 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2247 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2248 C2ParamField{&sUsage, &sUsage.value}));
2249 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2250 if (err != C2_OK) {
2251 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2252 name.c_str(), err);
2253 mFields[0].status = err;
2254 }
2255 std::vector<std::unique_ptr<C2Param>> params;
2256 err = intf->query(
2257 {&mApiFeatures},
2258 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2259 C2_MAY_BLOCK,
2260 &params);
2261 if (err != C2_OK && err != C2_BAD_INDEX) {
2262 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2263 name.c_str(), err);
2264 }
2265 while (!params.empty()) {
2266 C2Param *param = params.back().release();
2267 params.pop_back();
2268 if (!param) {
2269 continue;
2270 }
2271 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2272 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002273 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002274 }
2275 }
2276 mInitStatus = OK;
2277 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002278 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002279
2280 status_t initCheck() const { return mInitStatus; }
2281
2282 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2283 CHECK_EQ(1u, mFields.size());
2284 return mFields[0];
2285 }
2286
2287 const C2ApiFeaturesSetting &getApiFeatures() const {
2288 return mApiFeatures;
2289 }
2290
2291 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2292 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2293 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2294 C2PortAllocatorsTuning::input::AllocUnique(0);
2295 param->invalidate();
2296 return param;
2297 }();
2298 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2299 }
2300
2301private:
2302 status_t mInitStatus{NO_INIT};
2303
2304 std::vector<C2FieldSupportedValuesQuery> mFields;
2305 C2ApiFeaturesSetting mApiFeatures;
2306 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2307};
2308
2309static const IntfCache &GetIntfCache(const std::string &name) {
2310 static IntfCache sNullIntfCache;
2311 static std::mutex sMutex;
2312 static std::map<std::string, IntfCache> sCache;
2313 std::unique_lock<std::mutex> lock{sMutex};
2314 auto it = sCache.find(name);
2315 if (it == sCache.end()) {
2316 lock.unlock();
2317 IntfCache intfCache;
2318 status_t err = intfCache.init(name);
2319 if (err != OK) {
2320 return sNullIntfCache;
2321 }
2322 lock.lock();
2323 it = sCache.insert({name, std::move(intfCache)}).first;
2324 }
2325 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002326}
2327
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002328static status_t GetCommonAllocatorIds(
2329 const std::vector<std::string> &names,
2330 C2Allocator::type_t type,
2331 std::set<C2Allocator::id_t> *ids) {
2332 int poolMask = GetCodec2PoolMask();
2333 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2334 C2Allocator::id_t defaultAllocatorId =
2335 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2336
2337 ids->clear();
2338 if (names.empty()) {
2339 return OK;
2340 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002341 bool firstIteration = true;
2342 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002343 const IntfCache &intfCache = GetIntfCache(name);
2344 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002345 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002346 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002347 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002348 if (firstIteration) {
2349 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002350 if (allocators && allocators.flexCount() > 0) {
2351 ids->insert(allocators.m.values,
2352 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002353 }
2354 if (ids->empty()) {
2355 // The component does not advertise allocators. Use default.
2356 ids->insert(defaultAllocatorId);
2357 }
2358 continue;
2359 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002360 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002361 if (allocators && allocators.flexCount() > 0) {
2362 filtered = true;
2363 for (auto it = ids->begin(); it != ids->end(); ) {
2364 bool found = false;
2365 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2366 if (allocators.m.values[j] == *it) {
2367 found = true;
2368 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002369 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002370 }
2371 if (found) {
2372 ++it;
2373 } else {
2374 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002375 }
2376 }
2377 }
2378 if (!filtered) {
2379 // The component does not advertise supported allocators. Use default.
2380 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2381 if (ids->size() != (containsDefault ? 1 : 0)) {
2382 ids->clear();
2383 if (containsDefault) {
2384 ids->insert(defaultAllocatorId);
2385 }
2386 }
2387 }
2388 }
2389 // Finally, filter with pool masks
2390 for (auto it = ids->begin(); it != ids->end(); ) {
2391 if ((poolMask >> *it) & 1) {
2392 ++it;
2393 } else {
2394 it = ids->erase(it);
2395 }
2396 }
2397 return OK;
2398}
2399
2400static status_t CalculateMinMaxUsage(
2401 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2402 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2403 *minUsage = 0;
2404 *maxUsage = ~0ull;
2405 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002406 const IntfCache &intfCache = GetIntfCache(name);
2407 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002408 continue;
2409 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002410 const C2FieldSupportedValuesQuery &usageSupportedValues =
2411 intfCache.getUsageSupportedValues();
2412 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002413 continue;
2414 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002415 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002416 if (supported.type != C2FieldSupportedValues::FLAGS) {
2417 continue;
2418 }
2419 if (supported.values.empty()) {
2420 *maxUsage = 0;
2421 continue;
2422 }
2423 *minUsage |= supported.values[0].u64;
2424 int64_t currentMaxUsage = 0;
2425 for (const C2Value::Primitive &flags : supported.values) {
2426 currentMaxUsage |= flags.u64;
2427 }
2428 *maxUsage &= currentMaxUsage;
2429 }
2430 return OK;
2431}
2432
2433// static
2434status_t CCodec::CanFetchLinearBlock(
2435 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002436 for (const std::string &name : names) {
2437 const IntfCache &intfCache = GetIntfCache(name);
2438 if (intfCache.initCheck() != OK) {
2439 continue;
2440 }
2441 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2442 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2443 *isCompatible = false;
2444 return OK;
2445 }
2446 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002447 uint64_t minUsage = usage.expected;
2448 uint64_t maxUsage = ~0ull;
2449 std::set<C2Allocator::id_t> allocators;
2450 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2451 if (allocators.empty()) {
2452 *isCompatible = false;
2453 return OK;
2454 }
2455 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2456 *isCompatible = ((maxUsage & minUsage) == minUsage);
2457 return OK;
2458}
2459
2460static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2461 static std::mutex sMutex{};
2462 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2463 std::unique_lock<std::mutex> lock{sMutex};
2464 std::shared_ptr<C2BlockPool> pool;
2465 auto it = sPools.find(allocId);
2466 if (it == sPools.end()) {
2467 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2468 if (err == OK) {
2469 sPools.emplace(allocId, pool);
2470 } else {
2471 pool.reset();
2472 }
2473 } else {
2474 pool = it->second;
2475 }
2476 return pool;
2477}
2478
2479// static
2480std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2481 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
2482 uint64_t minUsage = usage.expected;
2483 uint64_t maxUsage = ~0ull;
2484 std::set<C2Allocator::id_t> allocators;
2485 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2486 if (allocators.empty()) {
2487 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2488 }
2489 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2490 if ((maxUsage & minUsage) != minUsage) {
2491 allocators.clear();
2492 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2493 }
2494 std::shared_ptr<C2LinearBlock> block;
2495 for (C2Allocator::id_t allocId : allocators) {
2496 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2497 if (!pool) {
2498 continue;
2499 }
2500 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2501 if (err != C2_OK || !block) {
2502 block.reset();
2503 continue;
2504 }
2505 break;
2506 }
2507 return block;
2508}
2509
2510// static
2511status_t CCodec::CanFetchGraphicBlock(
2512 const std::vector<std::string> &names, bool *isCompatible) {
2513 uint64_t minUsage = 0;
2514 uint64_t maxUsage = ~0ull;
2515 std::set<C2Allocator::id_t> allocators;
2516 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2517 if (allocators.empty()) {
2518 *isCompatible = false;
2519 return OK;
2520 }
2521 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2522 *isCompatible = ((maxUsage & minUsage) == minUsage);
2523 return OK;
2524}
2525
2526// static
2527std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2528 int32_t width,
2529 int32_t height,
2530 int32_t format,
2531 uint64_t usage,
2532 const std::vector<std::string> &names) {
2533 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2534 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2535 ALOGD("Unrecognized pixel format: %d", format);
2536 return nullptr;
2537 }
2538 uint64_t minUsage = 0;
2539 uint64_t maxUsage = ~0ull;
2540 std::set<C2Allocator::id_t> allocators;
2541 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2542 if (allocators.empty()) {
2543 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2544 }
2545 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2546 minUsage |= usage;
2547 if ((maxUsage & minUsage) != minUsage) {
2548 allocators.clear();
2549 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2550 }
2551 std::shared_ptr<C2GraphicBlock> block;
2552 for (C2Allocator::id_t allocId : allocators) {
2553 std::shared_ptr<C2BlockPool> pool;
2554 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2555 if (err != C2_OK || !pool) {
2556 continue;
2557 }
2558 err = pool->fetchGraphicBlock(
2559 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2560 if (err != C2_OK || !block) {
2561 block.reset();
2562 continue;
2563 }
2564 break;
2565 }
2566 return block;
2567}
2568
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002569} // namespace android
2570