blob: 2c00594296f2238aadfce5c9136616aaa8804412 [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 Kim1f5063d2021-05-03 15:41:17 -070041#include <media/stagefright/foundation/avc_utils.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070042#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
43#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070044#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080045#include <media/stagefright/BufferProducerWrapper.h>
46#include <media/stagefright/MediaCodecConstants.h>
47#include <media/stagefright/PersistentSurface.h>
ted.sun765db4d2020-06-23 14:03:41 +080048#include <utils/NativeHandle.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080049
50#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080051#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070052#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080053#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080054#include "InputSurfaceWrapper.h"
55
56extern "C" android::PersistentSurface *CreateInputSurface();
57
58namespace android {
59
60using namespace std::chrono_literals;
61using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
62using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080063using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080064
Wonsik Kim9917d4a2019-10-24 12:56:38 -070065typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070066typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070067
Pawin Vongmasa36653902018-11-15 00:10:25 -080068namespace {
69
70class CCodecWatchdog : public AHandler {
71private:
72 enum {
73 kWhatWatch,
74 };
75 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
76
77public:
78 static sp<CCodecWatchdog> getInstance() {
79 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
80 static std::once_flag flag;
81 // Call Init() only once.
82 std::call_once(flag, Init, instance);
83 return instance;
84 }
85
86 ~CCodecWatchdog() = default;
87
88 void watch(sp<CCodec> codec) {
89 bool shouldPost = false;
90 {
91 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
92 // If a watch message is in flight, piggy-back this instance as well.
93 // Otherwise, post a new watch message.
94 shouldPost = codecs->empty();
95 codecs->emplace(codec);
96 }
97 if (shouldPost) {
98 ALOGV("posting watch message");
99 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
100 }
101 }
102
103protected:
104 void onMessageReceived(const sp<AMessage> &msg) {
105 switch (msg->what()) {
106 case kWhatWatch: {
107 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
108 ALOGV("watch for %zu codecs", codecs->size());
109 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
110 sp<CCodec> codec = it->promote();
111 if (codec == nullptr) {
112 continue;
113 }
114 codec->initiateReleaseIfStuck();
115 }
116 codecs->clear();
117 break;
118 }
119
120 default: {
121 TRESPASS("CCodecWatchdog: unrecognized message");
122 }
123 }
124 }
125
126private:
127 CCodecWatchdog() : mLooper(new ALooper) {}
128
129 static void Init(const sp<CCodecWatchdog> &thiz) {
130 ALOGV("Init");
131 thiz->mLooper->setName("CCodecWatchdog");
132 thiz->mLooper->registerHandler(thiz);
133 thiz->mLooper->start();
134 }
135
136 sp<ALooper> mLooper;
137
138 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
139};
140
141class C2InputSurfaceWrapper : public InputSurfaceWrapper {
142public:
143 explicit C2InputSurfaceWrapper(
144 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
145 mSurface(surface) {
146 }
147
148 ~C2InputSurfaceWrapper() override = default;
149
150 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
151 if (mConnection != nullptr) {
152 return ALREADY_EXISTS;
153 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800154 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800155 }
156
157 void disconnect() override {
158 if (mConnection != nullptr) {
159 mConnection->disconnect();
160 mConnection = nullptr;
161 }
162 }
163
164 status_t start() override {
165 // InputSurface does not distinguish started state
166 return OK;
167 }
168
169 status_t signalEndOfInputStream() override {
170 C2InputSurfaceEosTuning eos(true);
171 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800172 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800173 if (err != C2_OK) {
174 return UNKNOWN_ERROR;
175 }
176 return OK;
177 }
178
179 status_t configure(Config &config __unused) {
180 // TODO
181 return OK;
182 }
183
184private:
185 std::shared_ptr<Codec2Client::InputSurface> mSurface;
186 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
187};
188
189class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
190public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700191 typedef hardware::media::omx::V1_0::Status OmxStatus;
192
Pawin Vongmasa36653902018-11-15 00:10:25 -0800193 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700194 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800195 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700196 uint32_t height,
197 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800198 : mSource(source), mWidth(width), mHeight(height) {
199 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700200 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800201 }
202 ~GraphicBufferSourceWrapper() override = default;
203
204 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
205 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700206 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800207 mNode->setFrameSize(mWidth, mHeight);
208
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700209 // Usage is queried during configure(), so setting it beforehand.
210 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
211 (void)mNode->setParameter(
212 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
213 &usage, sizeof(usage));
214
Yanqiang Fanc56f3e62021-09-28 16:54:07 +0800215 return GetStatus(mSource->configure(
216 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800217 }
218
219 void disconnect() override {
220 if (mNode == nullptr) {
221 return;
222 }
223 sp<IOMXBufferSource> source = mNode->getSource();
224 if (source == nullptr) {
225 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
226 return;
227 }
228 source->onOmxIdle();
229 source->onOmxLoaded();
230 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700231 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800232 }
233
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700234 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
235 if (status.isOk()) {
236 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
237 } else if (status.isDeadObject()) {
238 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800239 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700240 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800241 }
242
243 status_t start() override {
244 sp<IOMXBufferSource> source = mNode->getSource();
245 if (source == nullptr) {
246 return NO_INIT;
247 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900248
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800249 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800250 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900251
Wonsik Kim34d66012021-03-01 16:40:33 -0800252 OMX_PARAM_PORTDEFINITIONTYPE param;
253 param.nPortIndex = kPortIndexInput;
254 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
255 &param, sizeof(param));
256 if (err == OK) {
257 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900258 }
259
260 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800261 source->onInputBufferAdded(i);
262 }
263
264 source->onOmxExecuting();
265 return OK;
266 }
267
268 status_t signalEndOfInputStream() override {
269 return GetStatus(mSource->signalEndOfInputStream());
270 }
271
272 status_t configure(Config &config) {
273 std::stringstream status;
274 status_t err = OK;
275
276 // handle each configuration granually, in case we need to handle part of the configuration
277 // elsewhere
278
279 // TRICKY: we do not unset frame delay repeating
280 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
281 int64_t us = 1e6 / config.mMinFps + 0.5;
282 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
283 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
284 if (res != OK) {
285 status << " (=> " << asString(res) << ")";
286 err = res;
287 }
288 mConfig.mMinFps = config.mMinFps;
289 }
290
291 // pts gap
292 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
293 if (mNode != nullptr) {
294 OMX_PARAM_U32TYPE ptrGapParam = {};
295 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700296 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800297 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
298 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700299 // float -> uint32_t is undefined if the value is negative.
300 // First convert to int32_t to ensure the expected behavior.
301 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800302 (void)mNode->setParameter(
303 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
304 &ptrGapParam, sizeof(ptrGapParam));
305 }
306 }
307
308 // max fps
309 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700310 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800311 && config.mMaxFps != mConfig.mMaxFps) {
312 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
313 status << " maxFps=" << config.mMaxFps;
314 if (res != OK) {
315 status << " (=> " << asString(res) << ")";
316 err = res;
317 }
318 mConfig.mMaxFps = config.mMaxFps;
319 }
320
321 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
322 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
323 status << " timeOffset " << config.mTimeOffsetUs << "us";
324 if (res != OK) {
325 status << " (=> " << asString(res) << ")";
326 err = res;
327 }
328 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
329 }
330
331 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
332 status_t res =
333 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
334 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
335 if (res != OK) {
336 status << " (=> " << asString(res) << ")";
337 err = res;
338 }
339 mConfig.mCaptureFps = config.mCaptureFps;
340 mConfig.mCodedFps = config.mCodedFps;
341 }
342
343 if (config.mStartAtUs != mConfig.mStartAtUs
344 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
345 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
346 status << " start at " << config.mStartAtUs << "us";
347 if (res != OK) {
348 status << " (=> " << asString(res) << ")";
349 err = res;
350 }
351 mConfig.mStartAtUs = config.mStartAtUs;
352 mConfig.mStopped = config.mStopped;
353 }
354
355 // suspend-resume
356 if (config.mSuspended != mConfig.mSuspended) {
357 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
358 status << " " << (config.mSuspended ? "suspend" : "resume")
359 << " at " << config.mSuspendAtUs << "us";
360 if (res != OK) {
361 status << " (=> " << asString(res) << ")";
362 err = res;
363 }
364 mConfig.mSuspended = config.mSuspended;
365 mConfig.mSuspendAtUs = config.mSuspendAtUs;
366 }
367
368 if (config.mStopped != mConfig.mStopped && config.mStopped) {
369 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
370 status << " stop at " << config.mStopAtUs << "us";
371 if (res != OK) {
372 status << " (=> " << asString(res) << ")";
373 err = res;
374 } else {
375 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700376 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
377 [&res, &delayUs = config.mInputDelayUs](
378 auto status, auto stopTimeOffsetUs) {
379 res = static_cast<status_t>(status);
380 delayUs = stopTimeOffsetUs;
381 });
382 if (!trans.isOk()) {
383 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
384 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800385 if (res != OK) {
386 status << " (=> " << asString(res) << ")";
387 } else {
388 status << "=" << config.mInputDelayUs << "us";
389 }
390 mConfig.mInputDelayUs = config.mInputDelayUs;
391 }
392 mConfig.mStopAtUs = config.mStopAtUs;
393 mConfig.mStopped = config.mStopped;
394 }
395
396 // color aspects (android._color-aspects)
397
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700398 // consumer usage is queried earlier.
399
Wonsik Kima1335e12021-04-22 16:28:29 -0700400 // priority
401 if (mConfig.mPriority != config.mPriority) {
402 if (config.mPriority != INT_MAX) {
403 mNode->setPriority(config.mPriority);
404 }
405 mConfig.mPriority = config.mPriority;
406 }
407
Wonsik Kimbd557932019-07-02 15:51:20 -0700408 if (status.str().empty()) {
409 ALOGD("ISConfig not changed");
410 } else {
411 ALOGD("ISConfig%s", status.str().c_str());
412 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800413 return err;
414 }
415
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700416 void onInputBufferDone(c2_cntr64_t index) override {
417 mNode->onInputBufferDone(index);
418 }
419
Wonsik Kim673dd192021-01-29 14:58:12 -0800420 android_dataspace getDataspace() override {
421 return mNode->getDataspace();
422 }
423
Pawin Vongmasa36653902018-11-15 00:10:25 -0800424private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700425 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800426 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700427 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800428 uint32_t mWidth;
429 uint32_t mHeight;
430 Config mConfig;
431};
432
433class Codec2ClientInterfaceWrapper : public C2ComponentStore {
434 std::shared_ptr<Codec2Client> mClient;
435
436public:
437 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
438 : mClient(client) { }
439
440 virtual ~Codec2ClientInterfaceWrapper() = default;
441
442 virtual c2_status_t config_sm(
443 const std::vector<C2Param *> &params,
444 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
445 return mClient->config(params, C2_MAY_BLOCK, failures);
446 };
447
448 virtual c2_status_t copyBuffer(
449 std::shared_ptr<C2GraphicBuffer>,
450 std::shared_ptr<C2GraphicBuffer>) {
451 return C2_OMITTED;
452 }
453
454 virtual c2_status_t createComponent(
455 C2String, std::shared_ptr<C2Component> *const component) {
456 component->reset();
457 return C2_OMITTED;
458 }
459
460 virtual c2_status_t createInterface(
461 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
462 interface->reset();
463 return C2_OMITTED;
464 }
465
466 virtual c2_status_t query_sm(
467 const std::vector<C2Param *> &stackParams,
468 const std::vector<C2Param::Index> &heapParamIndices,
469 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
470 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
471 }
472
473 virtual c2_status_t querySupportedParams_nb(
474 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
475 return mClient->querySupportedParams(params);
476 }
477
478 virtual c2_status_t querySupportedValues_sm(
479 std::vector<C2FieldSupportedValuesQuery> &fields) const {
480 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
481 }
482
483 virtual C2String getName() const {
484 return mClient->getName();
485 }
486
487 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
488 return mClient->getParamReflector();
489 }
490
491 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
492 return std::vector<std::shared_ptr<const C2Component::Traits>>();
493 }
494};
495
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800496void RevertOutputFormatIfNeeded(
497 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
498 // We used to not report changes to these keys to the client.
499 const static std::set<std::string> sIgnoredKeys({
500 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800501 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800502 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800503 KEY_MAX_WIDTH,
504 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800505 "csd-0",
506 "csd-1",
507 "csd-2",
508 });
509 if (currentFormat == oldFormat) {
510 return;
511 }
512 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
513 AMessage::Type type;
514 for (size_t i = diff->countEntries(); i > 0; --i) {
515 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
516 diff->removeEntryAt(i - 1);
517 }
518 }
519 if (diff->countEntries() == 0) {
520 currentFormat = oldFormat;
521 }
522}
523
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700524void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700525 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700526 const sp<AMessage> &outputFormat) {
527 if (mediaType == MIMETYPE_VIDEO_AVC) {
528 // Codec specific data should be SPS and PPS in a single buffer,
529 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
530 // We separate the two and put them into the output format
531 // under the keys "csd-0" and "csd-1".
532
533 unsigned csdIndex = 0;
534
535 const uint8_t *nalStart;
536 size_t nalSize;
537 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
538 sp<ABuffer> csd = new ABuffer(nalSize + 4);
539 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
540 memcpy(csd->data() + 4, nalStart, nalSize);
541
542 outputFormat->setBuffer(
543 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
544
545 ++csdIndex;
546 }
547
548 if (csdIndex != 2) {
549 ALOGW("Expected two NAL units from AVC codec config, but %u found",
550 csdIndex);
551 }
552 } else {
553 // For everything else we just stash the codec specific data into
554 // the output format as a single piece of csd under "csd-0".
555 sp<ABuffer> csd = new ABuffer(size);
556 memcpy(csd->data(), data, size);
557 csd->setRange(0, size);
558 outputFormat->setBuffer("csd-0", csd);
559 }
560}
561
Pawin Vongmasa36653902018-11-15 00:10:25 -0800562} // namespace
563
564// CCodec::ClientListener
565
566struct CCodec::ClientListener : public Codec2Client::Listener {
567
568 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
569
570 virtual void onWorkDone(
571 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800572 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800573 (void)component;
574 sp<CCodec> codec(mCodec.promote());
575 if (!codec) {
576 return;
577 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800578 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800579 }
580
581 virtual void onTripped(
582 const std::weak_ptr<Codec2Client::Component>& component,
583 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
584 ) override {
585 // TODO
586 (void)component;
587 (void)settingResult;
588 }
589
590 virtual void onError(
591 const std::weak_ptr<Codec2Client::Component>& component,
592 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800593 {
594 // Component is only used for reporting as we use a separate listener for each instance
595 std::shared_ptr<Codec2Client::Component> comp = component.lock();
596 if (!comp) {
597 ALOGD("Component died with error: 0x%x", errorCode);
598 } else {
599 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
600 }
601 }
602
603 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800604 // Note: for now we do not propagate the error code to MediaCodec
605 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800606 sp<CCodec> codec(mCodec.promote());
607 if (!codec || !codec->mCallback) {
608 return;
609 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800610 codec->mCallback->onError(
611 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
612 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800613 }
614
615 virtual void onDeath(
616 const std::weak_ptr<Codec2Client::Component>& component) override {
617 { // Log the death of the component.
618 std::shared_ptr<Codec2Client::Component> comp = component.lock();
619 if (!comp) {
620 ALOGE("Codec2 component died.");
621 } else {
622 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
623 }
624 }
625
626 // Report to MediaCodec.
627 sp<CCodec> codec(mCodec.promote());
628 if (!codec || !codec->mCallback) {
629 return;
630 }
631 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
632 }
633
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800634 virtual void onFrameRendered(uint64_t bufferQueueId,
635 int32_t slotId,
636 int64_t timestampNs) override {
637 // TODO: implement
638 (void)bufferQueueId;
639 (void)slotId;
640 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800641 }
642
643 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800644 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800645 sp<CCodec> codec(mCodec.promote());
646 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800647 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800648 }
649 }
650
651private:
652 wp<CCodec> mCodec;
653};
654
655// CCodecCallbackImpl
656
657class CCodecCallbackImpl : public CCodecCallback {
658public:
659 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
660 ~CCodecCallbackImpl() override = default;
661
662 void onError(status_t err, enum ActionCode actionCode) override {
663 mCodec->mCallback->onError(err, actionCode);
664 }
665
666 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
667 mCodec->mCallback->onOutputFramesRendered(
668 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
669 }
670
Pawin Vongmasa36653902018-11-15 00:10:25 -0800671 void onOutputBuffersChanged() override {
672 mCodec->mCallback->onOutputBuffersChanged();
673 }
674
Guillaume Chelfi5ffbcb32021-04-12 14:23:43 +0200675 void onFirstTunnelFrameReady() override {
676 mCodec->mCallback->onFirstTunnelFrameReady();
677 }
678
Pawin Vongmasa36653902018-11-15 00:10:25 -0800679private:
680 CCodec *mCodec;
681};
682
683// CCodec
684
685CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700686 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
687 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800688}
689
690CCodec::~CCodec() {
691}
692
693std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
694 return mChannel;
695}
696
697status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
698 status_t err = job();
699 if (err != C2_OK) {
700 mCallback->onError(err, ACTION_CODE_FATAL);
701 }
702 return err;
703}
704
705void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
706 auto setAllocating = [this] {
707 Mutexed<State>::Locked state(mState);
708 if (state->get() != RELEASED) {
709 return INVALID_OPERATION;
710 }
711 state->set(ALLOCATING);
712 return OK;
713 };
714 if (tryAndReportOnError(setAllocating) != OK) {
715 return;
716 }
717
718 sp<RefBase> codecInfo;
719 CHECK(msg->findObject("codecInfo", &codecInfo));
720 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
721
722 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
723 allocMsg->setObject("codecInfo", codecInfo);
724 allocMsg->post();
725}
726
727void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
728 if (codecInfo == nullptr) {
729 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
730 return;
731 }
732 ALOGD("allocate(%s)", codecInfo->getCodecName());
733 mClientListener.reset(new ClientListener(this));
734
735 AString componentName = codecInfo->getCodecName();
736 std::shared_ptr<Codec2Client> client;
737
738 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700739 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800740 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800741 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800742 SetPreferredCodec2ComponentStore(
743 std::make_shared<Codec2ClientInterfaceWrapper>(client));
744 }
745
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900746 std::shared_ptr<Codec2Client::Component> comp;
747 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748 componentName.c_str(),
749 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900750 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800751 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900752 if (status != C2_OK) {
753 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800754 Mutexed<State>::Locked state(mState);
755 state->set(RELEASED);
756 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900757 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800758 state.lock();
759 return;
760 }
761 ALOGI("Created component [%s]", componentName.c_str());
762 mChannel->setComponent(comp);
763 auto setAllocated = [this, comp, client] {
764 Mutexed<State>::Locked state(mState);
765 if (state->get() != ALLOCATING) {
766 state->set(RELEASED);
767 return UNKNOWN_ERROR;
768 }
769 state->set(ALLOCATED);
770 state->comp = comp;
771 mClient = client;
772 return OK;
773 };
774 if (tryAndReportOnError(setAllocated) != OK) {
775 return;
776 }
777
778 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700779 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
780 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800781 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800782 if (err != OK) {
783 ALOGW("Failed to initialize configuration support");
784 // TODO: report error once we complete implementation.
785 }
786 config->queryConfiguration(comp);
787
788 mCallback->onComponentAllocated(componentName.c_str());
789}
790
791void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
792 auto checkAllocated = [this] {
793 Mutexed<State>::Locked state(mState);
794 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
795 };
796 if (tryAndReportOnError(checkAllocated) != OK) {
797 return;
798 }
799
800 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
801 msg->setMessage("format", format);
802 msg->post();
803}
804
805void CCodec::configure(const sp<AMessage> &msg) {
806 std::shared_ptr<Codec2Client::Component> comp;
807 auto checkAllocated = [this, &comp] {
808 Mutexed<State>::Locked state(mState);
809 if (state->get() != ALLOCATED) {
810 state->set(RELEASED);
811 return UNKNOWN_ERROR;
812 }
813 comp = state->comp;
814 return OK;
815 };
816 if (tryAndReportOnError(checkAllocated) != OK) {
817 return;
818 }
819
820 auto doConfig = [msg, comp, this]() -> status_t {
821 AString mime;
822 if (!msg->findString("mime", &mime)) {
823 return BAD_VALUE;
824 }
825
826 int32_t encoder;
827 if (!msg->findInt32("encoder", &encoder)) {
828 encoder = false;
829 }
830
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800831 int32_t flags;
832 if (!msg->findInt32("flags", &flags)) {
833 return BAD_VALUE;
834 }
835
Pawin Vongmasa36653902018-11-15 00:10:25 -0800836 // TODO: read from intf()
837 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
838 return UNKNOWN_ERROR;
839 }
840
841 int32_t storeMeta;
842 if (encoder
843 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
844 && storeMeta != kMetadataBufferTypeInvalid) {
845 if (storeMeta != kMetadataBufferTypeANWBuffer) {
846 ALOGD("Only ANW buffers are supported for legacy metadata mode");
847 return BAD_VALUE;
848 }
849 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
850 }
851
ted.sun765db4d2020-06-23 14:03:41 +0800852 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800853 sp<RefBase> obj;
854 sp<Surface> surface;
855 if (msg->findObject("native-window", &obj)) {
856 surface = static_cast<Surface *>(obj.get());
ted.sun765db4d2020-06-23 14:03:41 +0800857 // setup tunneled playback
858 if (surface != nullptr) {
859 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
860 const std::unique_ptr<Config> &config = *configLocked;
861 if ((config->mDomain & Config::IS_DECODER)
862 && (config->mDomain & Config::IS_VIDEO)) {
863 int32_t tunneled;
864 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
865 ALOGI("Configuring TUNNELED video playback.");
866
867 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
868 if (err != OK) {
869 ALOGE("configureTunneledVideoPlayback failed!");
870 return err;
871 }
872 config->mTunneled = true;
873 }
874 }
875 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800876 setSurface(surface);
877 }
878
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700879 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
880 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800881 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800882 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
883 ALOGD("[%s] buffers are %sbound to CCodec for this session",
884 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800885
Wonsik Kim1114eea2019-02-25 14:35:24 -0800886 // Enforce required parameters
887 int32_t i32;
888 float flt;
889 if (config->mDomain & Config::IS_AUDIO) {
890 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
891 ALOGD("sample rate is missing, which is required for audio components.");
892 return BAD_VALUE;
893 }
894 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
895 ALOGD("channel count is missing, which is required for audio components.");
896 return BAD_VALUE;
897 }
898 if ((config->mDomain & Config::IS_ENCODER)
899 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
900 && !msg->findInt32(KEY_BIT_RATE, &i32)
901 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
902 ALOGD("bitrate is missing, which is required for audio encoders.");
903 return BAD_VALUE;
904 }
905 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800906 int32_t width = 0;
907 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800908 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800909 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800910 ALOGD("width is missing, which is required for image/video components.");
911 return BAD_VALUE;
912 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800913 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800914 ALOGD("height is missing, which is required for image/video components.");
915 return BAD_VALUE;
916 }
917 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700918 int32_t mode = BITRATE_MODE_VBR;
919 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700920 if (!msg->findInt32(KEY_QUALITY, &i32)) {
921 ALOGD("quality is missing, which is required for video encoders in CQ.");
922 return BAD_VALUE;
923 }
924 } else {
925 if (!msg->findInt32(KEY_BIT_RATE, &i32)
926 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
927 ALOGD("bitrate is missing, which is required for video encoders.");
928 return BAD_VALUE;
929 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800930 }
931 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
932 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
933 ALOGD("I frame interval is missing, which is required for video encoders.");
934 return BAD_VALUE;
935 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700936 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
937 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
938 ALOGD("frame rate is missing, which is required for video encoders.");
939 return BAD_VALUE;
940 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800941 }
942 }
943
Pawin Vongmasa36653902018-11-15 00:10:25 -0800944 /*
945 * Handle input surface configuration
946 */
947 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
948 && (config->mDomain & Config::IS_ENCODER)) {
949 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
950 {
951 config->mISConfig->mMinFps = 0;
952 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800953 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800954 config->mISConfig->mMinFps = 1e6 / value;
955 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700956 if (!msg->findFloat(
957 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
958 config->mISConfig->mMaxFps = -1;
959 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800960 config->mISConfig->mMinAdjustedFps = 0;
961 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800962 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800963 if (value < 0 && value >= INT32_MIN) {
964 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700965 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800966 } else if (value > 0 && value <= INT32_MAX) {
967 config->mISConfig->mMinAdjustedFps = 1e6 / value;
968 }
969 }
970 }
971
972 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700973 bool captureFpsFound = false;
974 double timeLapseFps;
975 float captureRate;
976 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
977 config->mISConfig->mCaptureFps = timeLapseFps;
978 captureFpsFound = true;
979 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
980 config->mISConfig->mCaptureFps = captureRate;
981 captureFpsFound = true;
982 }
983 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800984 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
985 }
986 }
987
988 {
989 config->mISConfig->mSuspended = false;
990 config->mISConfig->mSuspendAtUs = -1;
991 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800992 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800993 config->mISConfig->mSuspended = true;
994 }
995 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700996 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -0700997 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800998 }
999
1000 /*
1001 * Handle desired color format.
1002 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001003 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001004 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001005 int32_t format = 0;
1006 // Query vendor format for Flexible YUV
1007 std::vector<std::unique_ptr<C2Param>> heapParams;
1008 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
1009 if (mClient->query(
1010 {},
1011 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1012 C2_MAY_BLOCK,
1013 &heapParams) == C2_OK
1014 && heapParams.size() == 1u) {
1015 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1016 heapParams[0].get());
1017 } else {
1018 pixelFormatInfo = nullptr;
1019 }
1020 std::optional<uint32_t> flexPixelFormat{};
1021 std::optional<uint32_t> flexPlanarPixelFormat{};
1022 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
1023 if (pixelFormatInfo && *pixelFormatInfo) {
1024 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1025 const C2FlexiblePixelFormatDescriptorStruct &desc =
1026 pixelFormatInfo->m.values[i];
1027 if (desc.bitDepth != 8
1028 || desc.subsampling != C2Color::YUV_420
1029 // TODO(b/180076105): some device report wrong layout
1030 // || desc.layout == C2Color::INTERLEAVED_PACKED
1031 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1032 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1033 continue;
1034 }
1035 if (!flexPixelFormat) {
1036 flexPixelFormat = desc.pixelFormat;
1037 }
1038 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
1039 flexPlanarPixelFormat = desc.pixelFormat;
1040 }
1041 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
1042 flexSemiPlanarPixelFormat = desc.pixelFormat;
1043 }
1044 }
1045 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001046 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001047 // Also handle default color format (encoders require color format, so this is only
1048 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001049 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001050 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001051 const char *prefix = "";
1052 if (flexSemiPlanarPixelFormat) {
1053 format = COLOR_FormatYUV420SemiPlanar;
1054 prefix = "semi-";
1055 } else {
1056 format = COLOR_FormatYUV420Planar;
1057 }
1058 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1059 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001060 } else {
1061 format = COLOR_FormatSurface;
1062 }
1063 defaultColorFormat = format;
1064 }
1065 } else {
1066 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
1067 switch (format) {
1068 case COLOR_FormatYUV420Flexible:
1069 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
1070 break;
1071 case COLOR_FormatYUV420Planar:
1072 case COLOR_FormatYUV420PackedPlanar:
1073 format = flexPlanarPixelFormat.value_or(
1074 flexPixelFormat.value_or(format));
1075 break;
1076 case COLOR_FormatYUV420SemiPlanar:
1077 case COLOR_FormatYUV420PackedSemiPlanar:
1078 format = flexSemiPlanarPixelFormat.value_or(
1079 flexPixelFormat.value_or(format));
1080 break;
1081 default:
1082 // No-op
1083 break;
1084 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001085 }
1086 }
1087
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001088 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001089 msg->setInt32("android._color-format", format);
1090 }
1091 }
1092
Wonsik Kim77e97c72021-01-20 10:33:22 -08001093 /*
1094 * Handle dataspace
1095 */
1096 int32_t usingRecorder;
1097 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1098 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1099 int32_t width, height;
1100 if (msg->findInt32("width", &width)
1101 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001102 ColorAspects aspects;
1103 getColorAspectsFromFormat(msg, aspects);
1104 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001105 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001106 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1107 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001108 }
1109 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1110 ALOGD("setting dataspace to %x", dataSpace);
1111 }
1112
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001113 int32_t subscribeToAllVendorParams;
1114 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1115 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1116 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1117 }
1118 }
1119
Pawin Vongmasa36653902018-11-15 00:10:25 -08001120 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001121 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1122 // the behavior here.
1123 sp<AMessage> sdkParams = msg;
1124 int32_t videoBitrate;
1125 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1126 sdkParams = msg->dup();
1127 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1128 }
ted.sun765db4d2020-06-23 14:03:41 +08001129 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001130 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001131 if (err != OK) {
1132 ALOGW("failed to convert configuration to c2 params");
1133 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001134
1135 int32_t maxBframes = 0;
1136 if ((config->mDomain & Config::IS_ENCODER)
1137 && (config->mDomain & Config::IS_VIDEO)
1138 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1139 && maxBframes > 0) {
1140 std::unique_ptr<C2StreamGopTuning::output> gop =
1141 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1142 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1143 gop->m.values[1] = {
1144 C2Config::picture_type_t(P_FRAME | B_FRAME),
1145 uint32_t(maxBframes)
1146 };
1147 configUpdate.push_back(std::move(gop));
1148 }
1149
Ray Essicka0ae6972021-03-10 19:40:01 -08001150 if ((config->mDomain & Config::IS_ENCODER)
1151 && (config->mDomain & Config::IS_VIDEO)) {
1152 // we may not use all 3 of these entries
1153 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1154 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1155 0u /* stream */);
1156
1157 int ix = 0;
1158
1159 int32_t iMax = INT32_MAX;
1160 int32_t iMin = INT32_MIN;
1161 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1162 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1163 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1164 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1165 }
1166
1167 int32_t pMax = INT32_MAX;
1168 int32_t pMin = INT32_MIN;
1169 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1170 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1171 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1172 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1173 }
1174
1175 int32_t bMax = INT32_MAX;
1176 int32_t bMin = INT32_MIN;
1177 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1178 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1179 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1180 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1181 }
1182
1183 // adjust to reflect actual use.
1184 qp->setFlexCount(ix);
1185
1186 configUpdate.push_back(std::move(qp));
1187 }
1188
Wonsik Kima1335e12021-04-22 16:28:29 -07001189 int32_t background = 0;
1190 if ((config->mDomain & Config::IS_VIDEO)
1191 && msg->findInt32("android._background-mode", &background)
1192 && background) {
1193 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1194 if (config->mISConfig) {
1195 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1196 }
1197 }
1198
Pawin Vongmasa36653902018-11-15 00:10:25 -08001199 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1200 if (err != OK) {
1201 ALOGW("failed to configure c2 params");
1202 return err;
1203 }
1204
1205 std::vector<std::unique_ptr<C2Param>> params;
1206 C2StreamUsageTuning::input usage(0u, 0u);
1207 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001208 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001209
Wonsik Kim3baecda2021-02-07 22:19:56 -08001210 C2Param::Index colorAspectsRequestIndex =
1211 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001212 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001213 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001214 };
Chaejung Lim86c22dc2021-12-23 00:41:05 -08001215 int32_t colorTransferRequest = 0;
1216 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1217 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1218 colorTransferRequest = 0;
1219 }
1220 c2_status_t c2err = C2_OK;
1221 if (colorTransferRequest != 0) {
1222 c2err = comp->query(
1223 { &usage, &maxInputSize, &prepend },
1224 indices,
1225 C2_DONT_BLOCK,
1226 &params);
1227 } else {
1228 c2err = comp->query(
1229 { &usage, &maxInputSize, &prepend },
1230 {},
1231 C2_DONT_BLOCK,
1232 &params);
1233 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001234 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1235 ALOGE("Failed to query component interface: %d", c2err);
1236 return UNKNOWN_ERROR;
1237 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001238 if (usage) {
1239 if (usage.value & C2MemoryUsage::CPU_READ) {
1240 config->mInputFormat->setInt32("using-sw-read-often", true);
1241 }
1242 if (config->mISConfig) {
1243 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1244 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1245 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001246 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001247 }
1248
1249 // NOTE: we don't blindly use client specified input size if specified as clients
1250 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1251 // client specified size is only used to ask for bigger buffers than component suggested
1252 // size.
1253 int32_t clientInputSize = 0;
1254 bool clientSpecifiedInputSize =
1255 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1256 // TEMP: enforce minimum buffer size of 1MB for video decoders
1257 // and 16K / 4K for audio encoders/decoders
1258 if (maxInputSize.value == 0) {
1259 if (config->mDomain & Config::IS_AUDIO) {
1260 maxInputSize.value = encoder ? 16384 : 4096;
1261 } else if (!encoder) {
1262 maxInputSize.value = 1048576u;
1263 }
1264 }
1265
1266 // verify that CSD fits into this size (if defined)
1267 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1268 sp<ABuffer> csd;
1269 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1270 if (csd && csd->size() > maxInputSize.value) {
1271 maxInputSize.value = csd->size();
1272 }
1273 }
1274 }
1275
1276 // TODO: do this based on component requiring linear allocator for input
1277 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1278 if (clientSpecifiedInputSize) {
1279 // Warn that we're overriding client's max input size if necessary.
1280 if ((uint32_t)clientInputSize < maxInputSize.value) {
1281 ALOGD("client requested max input size %d, which is smaller than "
1282 "what component recommended (%u); overriding with component "
1283 "recommendation.", clientInputSize, maxInputSize.value);
1284 ALOGW("This behavior is subject to change. It is recommended that "
1285 "app developers double check whether the requested "
1286 "max input size is in reasonable range.");
1287 } else {
1288 maxInputSize.value = clientInputSize;
1289 }
1290 }
1291 // Pass max input size on input format to the buffer channel (if supplied by the
1292 // component or by a default)
1293 if (maxInputSize.value) {
1294 config->mInputFormat->setInt32(
1295 KEY_MAX_INPUT_SIZE,
1296 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1297 }
1298 }
1299
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001300 int32_t clientPrepend;
1301 if ((config->mDomain & Config::IS_VIDEO)
1302 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001303 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001304 && clientPrepend
1305 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001306 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001307 return BAD_VALUE;
1308 }
1309
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001310 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001311 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1312 // propagate HDR static info to output format for both encoders and decoders
1313 // if component supports this info, we will update from component, but only the raw port,
1314 // so don't propagate if component already filled it in.
1315 sp<ABuffer> hdrInfo;
1316 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1317 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1318 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1319 }
1320
1321 // Set desired color format from configuration parameter
1322 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001323 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1324 format = defaultColorFormat;
1325 }
1326 if (config->mDomain & Config::IS_ENCODER) {
1327 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001328 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1329 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001330 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001331 } else {
1332 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001333 }
1334 }
1335
1336 // propagate encoder delay and padding to output format
1337 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1338 int delay = 0;
1339 if (msg->findInt32("encoder-delay", &delay)) {
1340 config->mOutputFormat->setInt32("encoder-delay", delay);
1341 }
1342 int padding = 0;
1343 if (msg->findInt32("encoder-padding", &padding)) {
1344 config->mOutputFormat->setInt32("encoder-padding", padding);
1345 }
1346 }
1347
Pawin Vongmasa36653902018-11-15 00:10:25 -08001348 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001349 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001350 int32_t mask;
1351 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1352 if (config->mDomain & Config::IS_ENCODER) {
1353 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1354 } else {
1355 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1356 }
1357 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001358
1359 // set PCM encoding
1360 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1361 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1362 if (encoder) {
1363 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1364 } else {
1365 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1366 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001367 }
1368
Wonsik Kim3baecda2021-02-07 22:19:56 -08001369 std::unique_ptr<C2Param> colorTransferRequestParam;
1370 for (std::unique_ptr<C2Param> &param : params) {
1371 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1372 ALOGI("found color transfer request param");
1373 colorTransferRequestParam = std::move(param);
1374 }
1375 }
Wonsik Kim3baecda2021-02-07 22:19:56 -08001376
1377 if (colorTransferRequest != 0) {
1378 if (colorTransferRequestParam && *colorTransferRequestParam) {
1379 C2StreamColorAspectsInfo::output *info =
1380 static_cast<C2StreamColorAspectsInfo::output *>(
1381 colorTransferRequestParam.get());
1382 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1383 colorTransferRequest = 0;
1384 }
1385 } else {
1386 colorTransferRequest = 0;
1387 }
1388 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1389 }
1390
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001391 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1392 // Need to get stride/vstride
1393 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1394 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1395 // TODO: retrieve these values without allocating a buffer.
1396 // Currently allocating a buffer is necessary to retrieve the layout.
1397 int64_t blockUsage =
1398 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1399 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1400 width, height, pixelFormat, blockUsage, {comp->getName()});
1401 sp<GraphicBlockBuffer> buffer;
1402 if (block) {
1403 buffer = GraphicBlockBuffer::Allocate(
1404 config->mInputFormat,
1405 block,
1406 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1407 } else {
1408 ALOGD("Failed to allocate a graphic block "
1409 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1410 width, height, pixelFormat, (long long)blockUsage);
1411 // This means that byte buffer mode is not supported in this configuration
1412 // anyway. Skip setting stride/vstride to input format.
1413 }
1414 if (buffer) {
1415 sp<ABuffer> imageData = buffer->getImageData();
1416 MediaImage2 *img = nullptr;
1417 if (imageData && imageData->data()
1418 && imageData->size() >= sizeof(MediaImage2)) {
1419 img = (MediaImage2*)imageData->data();
1420 }
1421 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1422 int32_t stride = img->mPlane[0].mRowInc;
1423 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1424 if (img->mNumPlanes > 1 && stride > 0) {
1425 int64_t offsetDelta =
1426 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1427 if (offsetDelta % stride == 0) {
1428 int32_t vstride = int32_t(offsetDelta / stride);
1429 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1430 } else {
1431 ALOGD("Cannot report accurate slice height: "
1432 "offsetDelta = %lld stride = %d",
1433 (long long)offsetDelta, stride);
1434 }
1435 }
1436 }
1437 }
1438 }
1439 }
1440
Wonsik Kimec585c32021-10-01 01:11:00 -07001441 if (config->mTunneled) {
1442 config->mOutputFormat->setInt32("android._tunneled", 1);
1443 }
1444
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001445 ALOGD("setup formats input: %s",
1446 config->mInputFormat->debugString().c_str());
1447 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001448 config->mOutputFormat->debugString().c_str());
1449 return OK;
1450 };
1451 if (tryAndReportOnError(doConfig) != OK) {
1452 return;
1453 }
1454
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001455 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1456 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001457
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001458 config->queryConfiguration(comp);
1459
Pawin Vongmasa36653902018-11-15 00:10:25 -08001460 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1461}
1462
1463void CCodec::initiateCreateInputSurface() {
1464 status_t err = [this] {
1465 Mutexed<State>::Locked state(mState);
1466 if (state->get() != ALLOCATED) {
1467 return UNKNOWN_ERROR;
1468 }
1469 // TODO: read it from intf() properly.
1470 if (state->comp->getName().find("encoder") == std::string::npos) {
1471 return INVALID_OPERATION;
1472 }
1473 return OK;
1474 }();
1475 if (err != OK) {
1476 mCallback->onInputSurfaceCreationFailed(err);
1477 return;
1478 }
1479
1480 (new AMessage(kWhatCreateInputSurface, this))->post();
1481}
1482
Lajos Molnar47118272019-01-31 16:28:04 -08001483sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1484 using namespace android::hardware::media::omx::V1_0;
1485 using namespace android::hardware::media::omx::V1_0::utils;
1486 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1487 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1488 android::sp<IOmx> omx = IOmx::getService();
1489 typedef android::hardware::graphics::bufferqueue::V1_0::
1490 IGraphicBufferProducer HGraphicBufferProducer;
1491 typedef android::hardware::media::omx::V1_0::
1492 IGraphicBufferSource HGraphicBufferSource;
1493 OmxStatus s;
1494 android::sp<HGraphicBufferProducer> gbp;
1495 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001496
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001497 using ::android::hardware::Return;
1498 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001499 [&s, &gbp, &gbs](
1500 OmxStatus status,
1501 const android::sp<HGraphicBufferProducer>& producer,
1502 const android::sp<HGraphicBufferSource>& source) {
1503 s = status;
1504 gbp = producer;
1505 gbs = source;
1506 });
1507 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001508 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001509 }
1510
1511 return nullptr;
1512}
1513
1514sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1515 sp<PersistentSurface> surface(CreateInputSurface());
1516
1517 if (surface == nullptr) {
1518 surface = CreateOmxInputSurface();
1519 }
1520
1521 return surface;
1522}
1523
Pawin Vongmasa36653902018-11-15 00:10:25 -08001524void CCodec::createInputSurface() {
1525 status_t err;
1526 sp<IGraphicBufferProducer> bufferProducer;
1527
Pawin Vongmasa36653902018-11-15 00:10:25 -08001528 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001529 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001530 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001531 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1532 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001533 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001534 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001535 }
1536
Lajos Molnar47118272019-01-31 16:28:04 -08001537 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001538 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1539 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1540 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001541
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001542 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001543 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1544 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001545 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001546 inputSurface));
1547 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001548 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001549 int32_t width = 0;
1550 (void)outputFormat->findInt32("width", &width);
1551 int32_t height = 0;
1552 (void)outputFormat->findInt32("height", &height);
1553 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001554 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001555 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001556 } else {
1557 ALOGE("Corrupted input surface");
1558 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1559 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001560 }
1561
1562 if (err != OK) {
1563 ALOGE("Failed to set up input surface: %d", err);
1564 mCallback->onInputSurfaceCreationFailed(err);
1565 return;
1566 }
1567
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001568 // Formats can change after setupInputSurface
1569 sp<AMessage> inputFormat;
1570 {
1571 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1572 const std::unique_ptr<Config> &config = *configLocked;
1573 inputFormat = config->mInputFormat;
1574 outputFormat = config->mOutputFormat;
1575 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001576 mCallback->onInputSurfaceCreated(
1577 inputFormat,
1578 outputFormat,
1579 new BufferProducerWrapper(bufferProducer));
1580}
1581
1582status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001583 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1584 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001585 config->mUsingSurface = true;
1586
1587 // we are now using surface - apply default color aspects to input format - as well as
1588 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001589 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001590
1591 // configure dataspace
1592 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
Wonsik Kim66b19552021-08-02 16:07:49 -07001593
1594 // The output format contains app-configured color aspects, and the input format
1595 // has the default color aspects. Use the default for the unspecified params.
1596 ColorAspects inputColorAspects, colorAspects;
1597 getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
1598 getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
1599 if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
1600 colorAspects.mRange = inputColorAspects.mRange;
1601 }
1602 if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
1603 colorAspects.mPrimaries = inputColorAspects.mPrimaries;
1604 }
1605 if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
1606 colorAspects.mTransfer = inputColorAspects.mTransfer;
1607 }
1608 if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
1609 colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
1610 }
1611 android_dataspace dataSpace = getDataSpaceForColorAspects(
1612 colorAspects, /* mayExtend = */ false);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001613 surface->setDataSpace(dataSpace);
Wonsik Kim66b19552021-08-02 16:07:49 -07001614 setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
1615 config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
1616
1617 ALOGD("input format %s to %s",
1618 inputFormatChanged ? "changed" : "unchanged",
1619 config->mInputFormat->debugString().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001620
1621 status_t err = mChannel->setInputSurface(surface);
1622 if (err != OK) {
1623 // undo input format update
1624 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001625 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001626 return err;
1627 }
1628 config->mInputSurface = surface;
1629
1630 if (config->mISConfig) {
1631 surface->configure(*config->mISConfig);
1632 } else {
1633 ALOGD("ISConfig: no configuration");
1634 }
1635
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001636 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001637}
1638
1639void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1640 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1641 msg->setObject("surface", surface);
1642 msg->post();
1643}
1644
1645void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001646 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001647 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001648 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001649 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1650 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001651 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001652 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001653 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001654 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1655 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1656 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1657 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001658 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1659 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1660 if (err != OK) {
1661 ALOGE("Failed to set up input surface: %d", err);
1662 mCallback->onInputSurfaceDeclined(err);
1663 return;
1664 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001665 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001666 int32_t width = 0;
1667 (void)outputFormat->findInt32("width", &width);
1668 int32_t height = 0;
1669 (void)outputFormat->findInt32("height", &height);
1670 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001671 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001672 if (err != OK) {
1673 ALOGE("Failed to set up input surface: %d", err);
1674 mCallback->onInputSurfaceDeclined(err);
1675 return;
1676 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001677 } else {
1678 ALOGE("Failed to set input surface: Corrupted surface.");
1679 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1680 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001681 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001682 // Formats can change after setupInputSurface
1683 sp<AMessage> inputFormat;
1684 {
1685 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1686 const std::unique_ptr<Config> &config = *configLocked;
1687 inputFormat = config->mInputFormat;
1688 outputFormat = config->mOutputFormat;
1689 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001690 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1691}
1692
1693void CCodec::initiateStart() {
1694 auto setStarting = [this] {
1695 Mutexed<State>::Locked state(mState);
1696 if (state->get() != ALLOCATED) {
1697 return UNKNOWN_ERROR;
1698 }
1699 state->set(STARTING);
1700 return OK;
1701 };
1702 if (tryAndReportOnError(setStarting) != OK) {
1703 return;
1704 }
1705
1706 (new AMessage(kWhatStart, this))->post();
1707}
1708
1709void CCodec::start() {
1710 std::shared_ptr<Codec2Client::Component> comp;
1711 auto checkStarting = [this, &comp] {
1712 Mutexed<State>::Locked state(mState);
1713 if (state->get() != STARTING) {
1714 return UNKNOWN_ERROR;
1715 }
1716 comp = state->comp;
1717 return OK;
1718 };
1719 if (tryAndReportOnError(checkStarting) != OK) {
1720 return;
1721 }
1722
1723 c2_status_t err = comp->start();
1724 if (err != C2_OK) {
1725 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1726 ACTION_CODE_FATAL);
1727 return;
1728 }
1729 sp<AMessage> inputFormat;
1730 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001731 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001732 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001733 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001734 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1735 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001736 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001737 // start triggers format dup
1738 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001739 if (config->mInputSurface) {
1740 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001741 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001742 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001743 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001744 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001745 if (err2 != OK) {
1746 mCallback->onError(err2, ACTION_CODE_FATAL);
1747 return;
1748 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001749 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001750 if (err2 != OK) {
1751 mCallback->onError(err2, ACTION_CODE_FATAL);
1752 return;
1753 }
1754
1755 auto setRunning = [this] {
1756 Mutexed<State>::Locked state(mState);
1757 if (state->get() != STARTING) {
1758 return UNKNOWN_ERROR;
1759 }
1760 state->set(RUNNING);
1761 return OK;
1762 };
1763 if (tryAndReportOnError(setRunning) != OK) {
1764 return;
1765 }
1766 mCallback->onStartCompleted();
1767
1768 (void)mChannel->requestInitialInputBuffers();
1769}
1770
1771void CCodec::initiateShutdown(bool keepComponentAllocated) {
1772 if (keepComponentAllocated) {
1773 initiateStop();
1774 } else {
1775 initiateRelease();
1776 }
1777}
1778
1779void CCodec::initiateStop() {
1780 {
1781 Mutexed<State>::Locked state(mState);
1782 if (state->get() == ALLOCATED
1783 || state->get() == RELEASED
1784 || state->get() == STOPPING
1785 || state->get() == RELEASING) {
1786 // We're already stopped, released, or doing it right now.
1787 state.unlock();
1788 mCallback->onStopCompleted();
1789 state.lock();
1790 return;
1791 }
1792 state->set(STOPPING);
1793 }
1794
Wonsik Kim936a89c2020-05-08 16:07:50 -07001795 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001796 (new AMessage(kWhatStop, this))->post();
1797}
1798
1799void CCodec::stop() {
1800 std::shared_ptr<Codec2Client::Component> comp;
1801 {
1802 Mutexed<State>::Locked state(mState);
1803 if (state->get() == RELEASING) {
1804 state.unlock();
1805 // We're already stopped or release is in progress.
1806 mCallback->onStopCompleted();
1807 state.lock();
1808 return;
1809 } else if (state->get() != STOPPING) {
1810 state.unlock();
1811 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1812 state.lock();
1813 return;
1814 }
1815 comp = state->comp;
1816 }
1817 status_t err = comp->stop();
1818 if (err != C2_OK) {
1819 // TODO: convert err into status_t
1820 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1821 }
1822
1823 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001824 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1825 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001826 if (config->mInputSurface) {
1827 config->mInputSurface->disconnect();
1828 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001829 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001830 }
1831 }
1832 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001833 Mutexed<State>::Locked state(mState);
1834 if (state->get() == STOPPING) {
1835 state->set(ALLOCATED);
1836 }
1837 }
1838 mCallback->onStopCompleted();
1839}
1840
1841void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001842 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001843 {
1844 Mutexed<State>::Locked state(mState);
1845 if (state->get() == RELEASED || state->get() == RELEASING) {
1846 // We're already released or doing it right now.
1847 if (sendCallback) {
1848 state.unlock();
1849 mCallback->onReleaseCompleted();
1850 state.lock();
1851 }
1852 return;
1853 }
1854 if (state->get() == ALLOCATING) {
1855 state->set(RELEASING);
1856 // With the altered state allocate() would fail and clean up.
1857 if (sendCallback) {
1858 state.unlock();
1859 mCallback->onReleaseCompleted();
1860 state.lock();
1861 }
1862 return;
1863 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001864 if (state->get() == STARTING
1865 || state->get() == RUNNING
1866 || state->get() == STOPPING) {
1867 // Input surface may have been started, so clean up is needed.
1868 clearInputSurfaceIfNeeded = true;
1869 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001870 state->set(RELEASING);
1871 }
1872
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001873 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001874 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1875 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001876 if (config->mInputSurface) {
1877 config->mInputSurface->disconnect();
1878 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001879 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001880 }
1881 }
1882
Wonsik Kim936a89c2020-05-08 16:07:50 -07001883 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001884 // thiz holds strong ref to this while the thread is running.
1885 sp<CCodec> thiz(this);
1886 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1887}
1888
1889void CCodec::release(bool sendCallback) {
1890 std::shared_ptr<Codec2Client::Component> comp;
1891 {
1892 Mutexed<State>::Locked state(mState);
1893 if (state->get() == RELEASED) {
1894 if (sendCallback) {
1895 state.unlock();
1896 mCallback->onReleaseCompleted();
1897 state.lock();
1898 }
1899 return;
1900 }
1901 comp = state->comp;
1902 }
1903 comp->release();
1904
1905 {
1906 Mutexed<State>::Locked state(mState);
1907 state->set(RELEASED);
1908 state->comp.reset();
1909 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001910 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001911 if (sendCallback) {
1912 mCallback->onReleaseCompleted();
1913 }
1914}
1915
1916status_t CCodec::setSurface(const sp<Surface> &surface) {
Wonsik Kim75e22f42021-04-14 23:34:51 -07001917 {
1918 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1919 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08001920 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
1921 status_t err = OK;
1922
Wonsik Kim75e22f42021-04-14 23:34:51 -07001923 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08001924 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07001925 nativeWindow.get(),
1926 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
1927 if (err != OK) {
1928 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
1929 nativeWindow.get(), config->mSidebandHandle->handle(), err);
1930 return err;
1931 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08001932 } else {
1933 // Explicitly reset the sideband handle of the window for
1934 // non-tunneled video in case the window was previously used
1935 // for a tunneled video playback.
1936 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
1937 if (err != OK) {
1938 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
1939 return err;
1940 }
ted.sun765db4d2020-06-23 14:03:41 +08001941 }
1942 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001943 return mChannel->setSurface(surface);
1944}
1945
1946void CCodec::signalFlush() {
1947 status_t err = [this] {
1948 Mutexed<State>::Locked state(mState);
1949 if (state->get() == FLUSHED) {
1950 return ALREADY_EXISTS;
1951 }
1952 if (state->get() != RUNNING) {
1953 return UNKNOWN_ERROR;
1954 }
1955 state->set(FLUSHING);
1956 return OK;
1957 }();
1958 switch (err) {
1959 case ALREADY_EXISTS:
1960 mCallback->onFlushCompleted();
1961 return;
1962 case OK:
1963 break;
1964 default:
1965 mCallback->onError(err, ACTION_CODE_FATAL);
1966 return;
1967 }
1968
1969 mChannel->stop();
1970 (new AMessage(kWhatFlush, this))->post();
1971}
1972
1973void CCodec::flush() {
1974 std::shared_ptr<Codec2Client::Component> comp;
1975 auto checkFlushing = [this, &comp] {
1976 Mutexed<State>::Locked state(mState);
1977 if (state->get() != FLUSHING) {
1978 return UNKNOWN_ERROR;
1979 }
1980 comp = state->comp;
1981 return OK;
1982 };
1983 if (tryAndReportOnError(checkFlushing) != OK) {
1984 return;
1985 }
1986
1987 std::list<std::unique_ptr<C2Work>> flushedWork;
1988 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1989 {
1990 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1991 flushedWork.splice(flushedWork.end(), *queue);
1992 }
1993 if (err != C2_OK) {
1994 // TODO: convert err into status_t
1995 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1996 }
1997
1998 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001999
2000 {
2001 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002002 if (state->get() == FLUSHING) {
2003 state->set(FLUSHED);
2004 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002005 }
2006 mCallback->onFlushCompleted();
2007}
2008
2009void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002010 std::shared_ptr<Codec2Client::Component> comp;
2011 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002012 Mutexed<State>::Locked state(mState);
2013 if (state->get() != FLUSHED) {
2014 return UNKNOWN_ERROR;
2015 }
2016 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002017 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002018 return OK;
2019 };
2020 if (tryAndReportOnError(setResuming) != OK) {
2021 return;
2022 }
2023
Wonsik Kime75a5da2020-02-14 17:29:03 -08002024 {
2025 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2026 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002027 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002028 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002029 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002030 }
2031
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002032 (void)mChannel->start(nullptr, nullptr, [&]{
2033 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2034 const std::unique_ptr<Config> &config = *configLocked;
2035 return config->mBuffersBoundToCodec;
2036 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002037
2038 {
2039 Mutexed<State>::Locked state(mState);
2040 if (state->get() != RESUMING) {
2041 state.unlock();
2042 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2043 state.lock();
2044 return;
2045 }
2046 state->set(RUNNING);
2047 }
2048
2049 (void)mChannel->requestInitialInputBuffers();
2050}
2051
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002052void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002053 std::shared_ptr<Codec2Client::Component> comp;
2054 auto checkState = [this, &comp] {
2055 Mutexed<State>::Locked state(mState);
2056 if (state->get() == RELEASED) {
2057 return INVALID_OPERATION;
2058 }
2059 comp = state->comp;
2060 return OK;
2061 };
2062 if (tryAndReportOnError(checkState) != OK) {
2063 return;
2064 }
2065
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002066 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2067 // the behavior here.
2068 sp<AMessage> params = msg;
2069 int32_t bitrate;
2070 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2071 params = msg->dup();
2072 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2073 }
2074
Houxiang Dai5a97b472021-03-22 17:56:04 +08002075 int32_t syncId = 0;
2076 if (params->findInt32("audio-hw-sync", &syncId)
2077 || params->findInt32("hw-av-sync-id", &syncId)) {
2078 configureTunneledVideoPlayback(comp, nullptr, params);
2079 }
2080
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002081 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2082 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002083
2084 /**
2085 * Handle input surface parameters
2086 */
2087 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002088 && (config->mDomain & Config::IS_ENCODER)
2089 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002090 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002091
2092 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2093 config->mISConfig->mStopped = false;
2094 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2095 config->mISConfig->mStopped = true;
2096 }
2097
2098 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002099 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002100 config->mISConfig->mSuspended = value;
2101 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002102 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002103 }
2104
2105 (void)config->mInputSurface->configure(*config->mISConfig);
2106 if (config->mISConfig->mStopped) {
2107 config->mInputFormat->setInt64(
2108 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2109 }
2110 }
2111
2112 std::vector<std::unique_ptr<C2Param>> configUpdate;
2113 (void)config->getConfigUpdateFromSdkParams(
2114 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2115 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2116 // Parameter synchronization is not defined when using input surface. For now, route
2117 // these directly to the component.
2118 if (config->mInputSurface == nullptr
2119 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2120 || comp->getName().find("c2.android.") == 0)) {
2121 mChannel->setParameters(configUpdate);
2122 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002123 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002124 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002125 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002126 }
2127}
2128
2129void CCodec::signalEndOfInputStream() {
2130 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2131}
2132
2133void CCodec::signalRequestIDRFrame() {
2134 std::shared_ptr<Codec2Client::Component> comp;
2135 {
2136 Mutexed<State>::Locked state(mState);
2137 if (state->get() == RELEASED) {
2138 ALOGD("no IDR request sent since component is released");
2139 return;
2140 }
2141 comp = state->comp;
2142 }
2143 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002144 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2145 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002146 std::vector<std::unique_ptr<C2Param>> params;
2147 params.push_back(
2148 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2149 config->setParameters(comp, params, C2_MAY_BLOCK);
2150}
2151
Wonsik Kim874ad382021-03-12 09:59:36 -08002152status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2153 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2154 const std::unique_ptr<Config> &config = *configLocked;
2155 return config->querySupportedParameters(names);
2156}
2157
2158status_t CCodec::describeParameter(
2159 const std::string &name, CodecParameterDescriptor *desc) {
2160 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2161 const std::unique_ptr<Config> &config = *configLocked;
2162 return config->describe(name, desc);
2163}
2164
2165status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2166 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2167 if (!comp) {
2168 return INVALID_OPERATION;
2169 }
2170 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2171 const std::unique_ptr<Config> &config = *configLocked;
2172 return config->subscribeToVendorConfigUpdate(comp, names);
2173}
2174
2175status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2176 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2177 if (!comp) {
2178 return INVALID_OPERATION;
2179 }
2180 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2181 const std::unique_ptr<Config> &config = *configLocked;
2182 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2183}
2184
Wonsik Kimab34ed62019-01-31 15:28:46 -08002185void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002186 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002187 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2188 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002189 }
2190 (new AMessage(kWhatWorkDone, this))->post();
2191}
2192
Wonsik Kimab34ed62019-01-31 15:28:46 -08002193void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2194 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002195 if (arrayIndex == 0) {
2196 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002197 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2198 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002199 if (config->mInputSurface) {
2200 config->mInputSurface->onInputBufferDone(frameIndex);
2201 }
2202 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002203}
2204
2205void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2206 TimePoint now = std::chrono::steady_clock::now();
2207 CCodecWatchdog::getInstance()->watch(this);
2208 switch (msg->what()) {
2209 case kWhatAllocate: {
2210 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002211 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002212 sp<RefBase> obj;
2213 CHECK(msg->findObject("codecInfo", &obj));
2214 allocate((MediaCodecInfo *)obj.get());
2215 break;
2216 }
2217 case kWhatConfigure: {
2218 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002219 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002220 sp<AMessage> format;
2221 CHECK(msg->findMessage("format", &format));
2222 configure(format);
2223 break;
2224 }
2225 case kWhatStart: {
2226 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002227 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002228 start();
2229 break;
2230 }
2231 case kWhatStop: {
2232 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002233 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002234 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002235 break;
2236 }
2237 case kWhatFlush: {
2238 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002239 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002240 flush();
2241 break;
2242 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002243 case kWhatRelease: {
2244 mChannel->release();
2245 mClient.reset();
2246 mClientListener.reset();
2247 break;
2248 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002249 case kWhatCreateInputSurface: {
2250 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002251 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002252 createInputSurface();
2253 break;
2254 }
2255 case kWhatSetInputSurface: {
2256 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002257 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002258 sp<RefBase> obj;
2259 CHECK(msg->findObject("surface", &obj));
2260 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2261 setInputSurface(surface);
2262 break;
2263 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002264 case kWhatWorkDone: {
2265 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002266 bool shouldPost = false;
2267 {
2268 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2269 if (queue->empty()) {
2270 break;
2271 }
2272 work.swap(queue->front());
2273 queue->pop_front();
2274 shouldPost = !queue->empty();
2275 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002276 if (shouldPost) {
2277 (new AMessage(kWhatWorkDone, this))->post();
2278 }
2279
Pawin Vongmasa36653902018-11-15 00:10:25 -08002280 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002281 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002282 sp<AMessage> outputFormat = nullptr;
2283 {
2284 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2285 const std::unique_ptr<Config> &config = *configLocked;
2286 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2287 config->watch<C2StreamInitDataInfo::output>();
2288 if (!work->worklets.empty()
2289 && (work->worklets.front()->output.flags
2290 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002291
Wonsik Kim75e22f42021-04-14 23:34:51 -07002292 // copy buffer info to config
2293 std::vector<std::unique_ptr<C2Param>> updates;
2294 for (const std::unique_ptr<C2Param> &param
2295 : work->worklets.front()->output.configUpdate) {
2296 updates.push_back(C2Param::Copy(*param));
2297 }
2298 unsigned stream = 0;
2299 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2300 work->worklets.front()->output.buffers;
2301 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2302 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2303 // move all info into output-stream #0 domain
2304 updates.emplace_back(
2305 C2Param::CopyAsStream(*info, true /* output */, stream));
2306 }
2307
2308 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2309 // for now only do the first block
2310 if (!blocks.empty()) {
2311 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2312 // block.crop().left, block.crop().top,
2313 // block.crop().width, block.crop().height,
2314 // block.width(), block.height());
2315 const C2ConstGraphicBlock &block = blocks[0];
2316 updates.emplace_back(new C2StreamCropRectInfo::output(
2317 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002318 }
2319 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002320 }
George Burgess IVc813a592020-02-22 22:54:44 -08002321
Wonsik Kim75e22f42021-04-14 23:34:51 -07002322 sp<AMessage> oldFormat = config->mOutputFormat;
2323 config->updateConfiguration(updates, config->mOutputDomain);
2324 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002325
Wonsik Kim75e22f42021-04-14 23:34:51 -07002326 // copy standard infos to graphic buffers if not already present (otherwise, we
2327 // may overwrite the actual intermediate value with a final value)
2328 stream = 0;
2329 const static C2Param::Index stdGfxInfos[] = {
2330 C2StreamRotationInfo::output::PARAM_TYPE,
2331 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2332 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2333 C2StreamHdrStaticInfo::output::PARAM_TYPE,
2334 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
2335 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2336 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2337 };
2338 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2339 if (buf->data().graphicBlocks().size()) {
2340 for (C2Param::Index ix : stdGfxInfos) {
2341 if (!buf->hasInfo(ix)) {
2342 const C2Param *param =
2343 config->getConfigParameterValue(ix.withStream(stream));
2344 if (param) {
2345 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2346 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2347 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002348 }
2349 }
2350 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002351 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002352 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002353 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002354 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302355 if (work->worklets.empty()
2356 || !work->worklets.back()
2357 || (work->worklets.back()->output.flags
2358 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2359 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2360 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002361 }
2362 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002363 initData = initDataWatcher.update();
2364 AmendOutputFormatWithCodecSpecificData(
2365 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2366 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002367 }
2368 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002369 }
2370 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002371 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002372 break;
2373 }
2374 case kWhatWatch: {
2375 // watch message already posted; no-op.
2376 break;
2377 }
2378 default: {
2379 ALOGE("unrecognized message");
2380 break;
2381 }
2382 }
2383 setDeadline(TimePoint::max(), 0ms, "none");
2384}
2385
2386void CCodec::setDeadline(
2387 const TimePoint &now,
2388 const std::chrono::milliseconds &timeout,
2389 const char *name) {
2390 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2391 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2392 deadline->set(now + (timeout * mult), name);
2393}
2394
ted.sun765db4d2020-06-23 14:03:41 +08002395status_t CCodec::configureTunneledVideoPlayback(
2396 std::shared_ptr<Codec2Client::Component> comp,
2397 sp<NativeHandle> *sidebandHandle,
2398 const sp<AMessage> &msg) {
2399 std::vector<std::unique_ptr<C2SettingResult>> failures;
2400
2401 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2402 C2PortTunneledModeTuning::output::AllocUnique(
2403 1,
2404 C2PortTunneledModeTuning::Struct::SIDEBAND,
2405 C2PortTunneledModeTuning::Struct::REALTIME,
2406 0);
2407 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2408 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2409 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2410 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2411 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2412 } else {
2413 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2414 tunneledPlayback->setFlexCount(0);
2415 }
2416 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2417 if (c2err != C2_OK) {
2418 return UNKNOWN_ERROR;
2419 }
2420
Houxiang Dai5a97b472021-03-22 17:56:04 +08002421 if (sidebandHandle == nullptr) {
2422 return OK;
2423 }
2424
ted.sun765db4d2020-06-23 14:03:41 +08002425 std::vector<std::unique_ptr<C2Param>> params;
2426 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2427 if (c2err == C2_OK && params.size() == 1u) {
2428 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2429 C2PortTunnelHandleTuning::output::From(params[0].get());
2430 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2431 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2432 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2433 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2434 memcpy(handle->data, videoTunnelSideband->m.values,
2435 sizeof(int32_t) * videoTunnelSideband->flexCount());
2436 return OK;
2437 } else {
2438 return NO_MEMORY;
2439 }
2440 }
2441 return UNKNOWN_ERROR;
2442}
2443
Pawin Vongmasa36653902018-11-15 00:10:25 -08002444void CCodec::initiateReleaseIfStuck() {
2445 std::string name;
2446 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002447 {
2448 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002449 if (deadline->get() < std::chrono::steady_clock::now()) {
2450 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002451 }
2452 if (deadline->get() != TimePoint::max()) {
2453 pendingDeadline = true;
2454 }
2455 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002456 bool tunneled = false;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002457 bool isMediaTypeKnown = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002458 {
Wonsik Kimabca11e2021-04-30 13:11:41 -07002459 static const std::set<std::string> kKnownMediaTypes{
2460 MIMETYPE_VIDEO_VP8,
2461 MIMETYPE_VIDEO_VP9,
2462 MIMETYPE_VIDEO_AV1,
2463 MIMETYPE_VIDEO_AVC,
2464 MIMETYPE_VIDEO_HEVC,
2465 MIMETYPE_VIDEO_MPEG4,
2466 MIMETYPE_VIDEO_H263,
2467 MIMETYPE_VIDEO_MPEG2,
2468 MIMETYPE_VIDEO_RAW,
2469 MIMETYPE_VIDEO_DOLBY_VISION,
2470
2471 MIMETYPE_AUDIO_AMR_NB,
2472 MIMETYPE_AUDIO_AMR_WB,
2473 MIMETYPE_AUDIO_MPEG,
2474 MIMETYPE_AUDIO_AAC,
2475 MIMETYPE_AUDIO_QCELP,
2476 MIMETYPE_AUDIO_VORBIS,
2477 MIMETYPE_AUDIO_OPUS,
2478 MIMETYPE_AUDIO_G711_ALAW,
2479 MIMETYPE_AUDIO_G711_MLAW,
2480 MIMETYPE_AUDIO_RAW,
2481 MIMETYPE_AUDIO_FLAC,
2482 MIMETYPE_AUDIO_MSGSM,
2483 MIMETYPE_AUDIO_AC3,
2484 MIMETYPE_AUDIO_EAC3,
2485
2486 MIMETYPE_IMAGE_ANDROID_HEIC,
2487 };
Wonsik Kim75e22f42021-04-14 23:34:51 -07002488 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2489 const std::unique_ptr<Config> &config = *configLocked;
2490 tunneled = config->mTunneled;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002491 isMediaTypeKnown = (kKnownMediaTypes.count(config->mCodingMediaType) != 0);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002492 }
Wonsik Kimabca11e2021-04-30 13:11:41 -07002493 if (!tunneled && isMediaTypeKnown && name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002494 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2495 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2496 if (elapsed >= kWorkDurationThreshold) {
2497 name = "queue";
2498 }
2499 if (elapsed > 0s) {
2500 pendingDeadline = true;
2501 }
2502 }
2503 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002504 // We're not stuck.
2505 if (pendingDeadline) {
2506 // If we are not stuck yet but still has deadline coming up,
2507 // post watch message to check back later.
2508 (new AMessage(kWhatWatch, this))->post();
2509 }
2510 return;
2511 }
2512
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002513 C2String compName;
2514 {
2515 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002516 if (!state->comp) {
2517 ALOGD("previous call to %s exceeded timeout "
2518 "and the component is already released", name.c_str());
2519 return;
2520 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002521 compName = state->comp->getName();
2522 }
2523 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2524
Pawin Vongmasa36653902018-11-15 00:10:25 -08002525 initiateRelease(false);
2526 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2527}
2528
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002529// static
2530PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002531 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002532 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002533 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002534 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2535 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002536 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002537 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2538 sp<IGraphicBufferProducer> gbp;
2539 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2540 status_t err = gbs->initCheck();
2541 if (err != OK) {
2542 ALOGE("Failed to create persistent input surface: error %d", err);
2543 return nullptr;
2544 }
2545 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002546 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002547 } else {
2548 return nullptr;
2549 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002550 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002551 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002552 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002553 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002554 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002555}
2556
Wonsik Kimffb889a2020-05-28 11:32:25 -07002557class IntfCache {
2558public:
2559 IntfCache() = default;
2560
2561 status_t init(const std::string &name) {
2562 std::shared_ptr<Codec2Client::Interface> intf{
2563 Codec2Client::CreateInterfaceByName(name.c_str())};
2564 if (!intf) {
2565 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2566 mInitStatus = NO_INIT;
2567 return NO_INIT;
2568 }
2569 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2570 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2571 C2ParamField{&sUsage, &sUsage.value}));
2572 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2573 if (err != C2_OK) {
2574 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2575 name.c_str(), err);
2576 mFields[0].status = err;
2577 }
2578 std::vector<std::unique_ptr<C2Param>> params;
2579 err = intf->query(
2580 {&mApiFeatures},
2581 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2582 C2_MAY_BLOCK,
2583 &params);
2584 if (err != C2_OK && err != C2_BAD_INDEX) {
2585 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2586 name.c_str(), err);
2587 }
2588 while (!params.empty()) {
2589 C2Param *param = params.back().release();
2590 params.pop_back();
2591 if (!param) {
2592 continue;
2593 }
2594 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2595 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002596 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002597 }
2598 }
2599 mInitStatus = OK;
2600 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002601 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002602
2603 status_t initCheck() const { return mInitStatus; }
2604
2605 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2606 CHECK_EQ(1u, mFields.size());
2607 return mFields[0];
2608 }
2609
2610 const C2ApiFeaturesSetting &getApiFeatures() const {
2611 return mApiFeatures;
2612 }
2613
2614 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2615 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2616 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2617 C2PortAllocatorsTuning::input::AllocUnique(0);
2618 param->invalidate();
2619 return param;
2620 }();
2621 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2622 }
2623
2624private:
2625 status_t mInitStatus{NO_INIT};
2626
2627 std::vector<C2FieldSupportedValuesQuery> mFields;
2628 C2ApiFeaturesSetting mApiFeatures;
2629 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2630};
2631
2632static const IntfCache &GetIntfCache(const std::string &name) {
2633 static IntfCache sNullIntfCache;
2634 static std::mutex sMutex;
2635 static std::map<std::string, IntfCache> sCache;
2636 std::unique_lock<std::mutex> lock{sMutex};
2637 auto it = sCache.find(name);
2638 if (it == sCache.end()) {
2639 lock.unlock();
2640 IntfCache intfCache;
2641 status_t err = intfCache.init(name);
2642 if (err != OK) {
2643 return sNullIntfCache;
2644 }
2645 lock.lock();
2646 it = sCache.insert({name, std::move(intfCache)}).first;
2647 }
2648 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002649}
2650
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002651static status_t GetCommonAllocatorIds(
2652 const std::vector<std::string> &names,
2653 C2Allocator::type_t type,
2654 std::set<C2Allocator::id_t> *ids) {
2655 int poolMask = GetCodec2PoolMask();
2656 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2657 C2Allocator::id_t defaultAllocatorId =
2658 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2659
2660 ids->clear();
2661 if (names.empty()) {
2662 return OK;
2663 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002664 bool firstIteration = true;
2665 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002666 const IntfCache &intfCache = GetIntfCache(name);
2667 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002668 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002669 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002670 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002671 if (firstIteration) {
2672 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002673 if (allocators && allocators.flexCount() > 0) {
2674 ids->insert(allocators.m.values,
2675 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002676 }
2677 if (ids->empty()) {
2678 // The component does not advertise allocators. Use default.
2679 ids->insert(defaultAllocatorId);
2680 }
2681 continue;
2682 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002683 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002684 if (allocators && allocators.flexCount() > 0) {
2685 filtered = true;
2686 for (auto it = ids->begin(); it != ids->end(); ) {
2687 bool found = false;
2688 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2689 if (allocators.m.values[j] == *it) {
2690 found = true;
2691 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002692 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002693 }
2694 if (found) {
2695 ++it;
2696 } else {
2697 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002698 }
2699 }
2700 }
2701 if (!filtered) {
2702 // The component does not advertise supported allocators. Use default.
2703 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2704 if (ids->size() != (containsDefault ? 1 : 0)) {
2705 ids->clear();
2706 if (containsDefault) {
2707 ids->insert(defaultAllocatorId);
2708 }
2709 }
2710 }
2711 }
2712 // Finally, filter with pool masks
2713 for (auto it = ids->begin(); it != ids->end(); ) {
2714 if ((poolMask >> *it) & 1) {
2715 ++it;
2716 } else {
2717 it = ids->erase(it);
2718 }
2719 }
2720 return OK;
2721}
2722
2723static status_t CalculateMinMaxUsage(
2724 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2725 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2726 *minUsage = 0;
2727 *maxUsage = ~0ull;
2728 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002729 const IntfCache &intfCache = GetIntfCache(name);
2730 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002731 continue;
2732 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002733 const C2FieldSupportedValuesQuery &usageSupportedValues =
2734 intfCache.getUsageSupportedValues();
2735 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002736 continue;
2737 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002738 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002739 if (supported.type != C2FieldSupportedValues::FLAGS) {
2740 continue;
2741 }
2742 if (supported.values.empty()) {
2743 *maxUsage = 0;
2744 continue;
2745 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08002746 if (supported.values.size() > 1) {
2747 *minUsage |= supported.values[1].u64;
2748 } else {
2749 *minUsage |= supported.values[0].u64;
2750 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002751 int64_t currentMaxUsage = 0;
2752 for (const C2Value::Primitive &flags : supported.values) {
2753 currentMaxUsage |= flags.u64;
2754 }
2755 *maxUsage &= currentMaxUsage;
2756 }
2757 return OK;
2758}
2759
2760// static
2761status_t CCodec::CanFetchLinearBlock(
2762 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002763 for (const std::string &name : names) {
2764 const IntfCache &intfCache = GetIntfCache(name);
2765 if (intfCache.initCheck() != OK) {
2766 continue;
2767 }
2768 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2769 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2770 *isCompatible = false;
2771 return OK;
2772 }
2773 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002774 std::set<C2Allocator::id_t> allocators;
2775 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2776 if (allocators.empty()) {
2777 *isCompatible = false;
2778 return OK;
2779 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002780
2781 uint64_t minUsage = 0;
2782 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002783 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002784 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002785 *isCompatible = ((maxUsage & minUsage) == minUsage);
2786 return OK;
2787}
2788
2789static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2790 static std::mutex sMutex{};
2791 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2792 std::unique_lock<std::mutex> lock{sMutex};
2793 std::shared_ptr<C2BlockPool> pool;
2794 auto it = sPools.find(allocId);
2795 if (it == sPools.end()) {
2796 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2797 if (err == OK) {
2798 sPools.emplace(allocId, pool);
2799 } else {
2800 pool.reset();
2801 }
2802 } else {
2803 pool = it->second;
2804 }
2805 return pool;
2806}
2807
2808// static
2809std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2810 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002811 std::set<C2Allocator::id_t> allocators;
2812 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2813 if (allocators.empty()) {
2814 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2815 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002816
2817 uint64_t minUsage = 0;
2818 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002819 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002820 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002821 if ((maxUsage & minUsage) != minUsage) {
2822 allocators.clear();
2823 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2824 }
2825 std::shared_ptr<C2LinearBlock> block;
2826 for (C2Allocator::id_t allocId : allocators) {
2827 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2828 if (!pool) {
2829 continue;
2830 }
2831 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2832 if (err != C2_OK || !block) {
2833 block.reset();
2834 continue;
2835 }
2836 break;
2837 }
2838 return block;
2839}
2840
2841// static
2842status_t CCodec::CanFetchGraphicBlock(
2843 const std::vector<std::string> &names, bool *isCompatible) {
2844 uint64_t minUsage = 0;
2845 uint64_t maxUsage = ~0ull;
2846 std::set<C2Allocator::id_t> allocators;
2847 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2848 if (allocators.empty()) {
2849 *isCompatible = false;
2850 return OK;
2851 }
2852 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2853 *isCompatible = ((maxUsage & minUsage) == minUsage);
2854 return OK;
2855}
2856
2857// static
2858std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2859 int32_t width,
2860 int32_t height,
2861 int32_t format,
2862 uint64_t usage,
2863 const std::vector<std::string> &names) {
2864 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2865 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2866 ALOGD("Unrecognized pixel format: %d", format);
2867 return nullptr;
2868 }
2869 uint64_t minUsage = 0;
2870 uint64_t maxUsage = ~0ull;
2871 std::set<C2Allocator::id_t> allocators;
2872 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2873 if (allocators.empty()) {
2874 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2875 }
2876 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2877 minUsage |= usage;
2878 if ((maxUsage & minUsage) != minUsage) {
2879 allocators.clear();
2880 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2881 }
2882 std::shared_ptr<C2GraphicBlock> block;
2883 for (C2Allocator::id_t allocId : allocators) {
2884 std::shared_ptr<C2BlockPool> pool;
2885 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2886 if (err != C2_OK || !pool) {
2887 continue;
2888 }
2889 err = pool->fetchGraphicBlock(
2890 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2891 if (err != C2_OK || !block) {
2892 block.reset();
2893 continue;
2894 }
2895 break;
2896 }
2897 return block;
2898}
2899
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002900} // namespace android