blob: 620531739debec4446748a5e691fb992ed272404 [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodec"
19#include <utils/Log.h>
20
21#include <sstream>
22#include <thread>
23
24#include <C2Config.h>
25#include <C2Debug.h>
26#include <C2ParamInternal.h>
27#include <C2PlatformSupport.h>
28
Pawin Vongmasa36653902018-11-15 00:10:25 -080029#include <android/IOMXBufferSource.h>
Pawin Vongmasabf69de92019-10-29 06:21:27 -070030#include <android/hardware/media/c2/1.0/IInputSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080031#include <android/hardware/media/omx/1.0/IGraphicBufferSource.h>
32#include <android/hardware/media/omx/1.0/IOmx.h>
33#include <android-base/stringprintf.h>
34#include <cutils/properties.h>
35#include <gui/IGraphicBufferProducer.h>
36#include <gui/Surface.h>
37#include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070038#include <media/omx/1.0/WOmxNode.h>
39#include <media/openmax/OMX_Core.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080040#include <media/openmax/OMX_IndexExt.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070041#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
42#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070043#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080044#include <media/stagefright/BufferProducerWrapper.h>
45#include <media/stagefright/MediaCodecConstants.h>
46#include <media/stagefright/PersistentSurface.h>
ted.sun765db4d2020-06-23 14:03:41 +080047#include <utils/NativeHandle.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080048
49#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080050#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070051#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080052#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080053#include "InputSurfaceWrapper.h"
54
55extern "C" android::PersistentSurface *CreateInputSurface();
56
57namespace android {
58
59using namespace std::chrono_literals;
60using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
61using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080062using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080063
Wonsik Kim9917d4a2019-10-24 12:56:38 -070064typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070065typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070066
Pawin Vongmasa36653902018-11-15 00:10:25 -080067namespace {
68
69class CCodecWatchdog : public AHandler {
70private:
71 enum {
72 kWhatWatch,
73 };
74 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
75
76public:
77 static sp<CCodecWatchdog> getInstance() {
78 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
79 static std::once_flag flag;
80 // Call Init() only once.
81 std::call_once(flag, Init, instance);
82 return instance;
83 }
84
85 ~CCodecWatchdog() = default;
86
87 void watch(sp<CCodec> codec) {
88 bool shouldPost = false;
89 {
90 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
91 // If a watch message is in flight, piggy-back this instance as well.
92 // Otherwise, post a new watch message.
93 shouldPost = codecs->empty();
94 codecs->emplace(codec);
95 }
96 if (shouldPost) {
97 ALOGV("posting watch message");
98 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
99 }
100 }
101
102protected:
103 void onMessageReceived(const sp<AMessage> &msg) {
104 switch (msg->what()) {
105 case kWhatWatch: {
106 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
107 ALOGV("watch for %zu codecs", codecs->size());
108 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
109 sp<CCodec> codec = it->promote();
110 if (codec == nullptr) {
111 continue;
112 }
113 codec->initiateReleaseIfStuck();
114 }
115 codecs->clear();
116 break;
117 }
118
119 default: {
120 TRESPASS("CCodecWatchdog: unrecognized message");
121 }
122 }
123 }
124
125private:
126 CCodecWatchdog() : mLooper(new ALooper) {}
127
128 static void Init(const sp<CCodecWatchdog> &thiz) {
129 ALOGV("Init");
130 thiz->mLooper->setName("CCodecWatchdog");
131 thiz->mLooper->registerHandler(thiz);
132 thiz->mLooper->start();
133 }
134
135 sp<ALooper> mLooper;
136
137 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
138};
139
140class C2InputSurfaceWrapper : public InputSurfaceWrapper {
141public:
142 explicit C2InputSurfaceWrapper(
143 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
144 mSurface(surface) {
145 }
146
147 ~C2InputSurfaceWrapper() override = default;
148
149 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
150 if (mConnection != nullptr) {
151 return ALREADY_EXISTS;
152 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800153 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800154 }
155
156 void disconnect() override {
157 if (mConnection != nullptr) {
158 mConnection->disconnect();
159 mConnection = nullptr;
160 }
161 }
162
163 status_t start() override {
164 // InputSurface does not distinguish started state
165 return OK;
166 }
167
168 status_t signalEndOfInputStream() override {
169 C2InputSurfaceEosTuning eos(true);
170 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800171 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800172 if (err != C2_OK) {
173 return UNKNOWN_ERROR;
174 }
175 return OK;
176 }
177
178 status_t configure(Config &config __unused) {
179 // TODO
180 return OK;
181 }
182
183private:
184 std::shared_ptr<Codec2Client::InputSurface> mSurface;
185 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
186};
187
188class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
189public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700190 typedef hardware::media::omx::V1_0::Status OmxStatus;
191
Pawin Vongmasa36653902018-11-15 00:10:25 -0800192 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700193 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800194 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700195 uint32_t height,
196 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800197 : mSource(source), mWidth(width), mHeight(height) {
198 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700199 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800200 }
201 ~GraphicBufferSourceWrapper() override = default;
202
203 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
204 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700205 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800206 mNode->setFrameSize(mWidth, mHeight);
207
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700208 // Usage is queried during configure(), so setting it beforehand.
209 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
210 (void)mNode->setParameter(
211 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
212 &usage, sizeof(usage));
213
Pawin Vongmasa36653902018-11-15 00:10:25 -0800214 // NOTE: we do not use/pass through color aspects from GraphicBufferSource as we
215 // communicate that directly to the component.
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700216 mSource->configure(
217 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800218 return OK;
219 }
220
221 void disconnect() override {
222 if (mNode == nullptr) {
223 return;
224 }
225 sp<IOMXBufferSource> source = mNode->getSource();
226 if (source == nullptr) {
227 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
228 return;
229 }
230 source->onOmxIdle();
231 source->onOmxLoaded();
232 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700233 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800234 }
235
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700236 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
237 if (status.isOk()) {
238 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
239 } else if (status.isDeadObject()) {
240 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800241 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700242 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800243 }
244
245 status_t start() override {
246 sp<IOMXBufferSource> source = mNode->getSource();
247 if (source == nullptr) {
248 return NO_INIT;
249 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900250
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800251 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800252 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900253
Wonsik Kim34d66012021-03-01 16:40:33 -0800254 OMX_PARAM_PORTDEFINITIONTYPE param;
255 param.nPortIndex = kPortIndexInput;
256 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
257 &param, sizeof(param));
258 if (err == OK) {
259 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900260 }
261
262 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800263 source->onInputBufferAdded(i);
264 }
265
266 source->onOmxExecuting();
267 return OK;
268 }
269
270 status_t signalEndOfInputStream() override {
271 return GetStatus(mSource->signalEndOfInputStream());
272 }
273
274 status_t configure(Config &config) {
275 std::stringstream status;
276 status_t err = OK;
277
278 // handle each configuration granually, in case we need to handle part of the configuration
279 // elsewhere
280
281 // TRICKY: we do not unset frame delay repeating
282 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
283 int64_t us = 1e6 / config.mMinFps + 0.5;
284 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
285 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
286 if (res != OK) {
287 status << " (=> " << asString(res) << ")";
288 err = res;
289 }
290 mConfig.mMinFps = config.mMinFps;
291 }
292
293 // pts gap
294 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
295 if (mNode != nullptr) {
296 OMX_PARAM_U32TYPE ptrGapParam = {};
297 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700298 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800299 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
300 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700301 // float -> uint32_t is undefined if the value is negative.
302 // First convert to int32_t to ensure the expected behavior.
303 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800304 (void)mNode->setParameter(
305 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
306 &ptrGapParam, sizeof(ptrGapParam));
307 }
308 }
309
310 // max fps
311 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700312 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800313 && config.mMaxFps != mConfig.mMaxFps) {
314 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
315 status << " maxFps=" << config.mMaxFps;
316 if (res != OK) {
317 status << " (=> " << asString(res) << ")";
318 err = res;
319 }
320 mConfig.mMaxFps = config.mMaxFps;
321 }
322
323 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
324 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
325 status << " timeOffset " << config.mTimeOffsetUs << "us";
326 if (res != OK) {
327 status << " (=> " << asString(res) << ")";
328 err = res;
329 }
330 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
331 }
332
333 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
334 status_t res =
335 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
336 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
337 if (res != OK) {
338 status << " (=> " << asString(res) << ")";
339 err = res;
340 }
341 mConfig.mCaptureFps = config.mCaptureFps;
342 mConfig.mCodedFps = config.mCodedFps;
343 }
344
345 if (config.mStartAtUs != mConfig.mStartAtUs
346 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
347 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
348 status << " start at " << config.mStartAtUs << "us";
349 if (res != OK) {
350 status << " (=> " << asString(res) << ")";
351 err = res;
352 }
353 mConfig.mStartAtUs = config.mStartAtUs;
354 mConfig.mStopped = config.mStopped;
355 }
356
357 // suspend-resume
358 if (config.mSuspended != mConfig.mSuspended) {
359 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
360 status << " " << (config.mSuspended ? "suspend" : "resume")
361 << " at " << config.mSuspendAtUs << "us";
362 if (res != OK) {
363 status << " (=> " << asString(res) << ")";
364 err = res;
365 }
366 mConfig.mSuspended = config.mSuspended;
367 mConfig.mSuspendAtUs = config.mSuspendAtUs;
368 }
369
370 if (config.mStopped != mConfig.mStopped && config.mStopped) {
371 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
372 status << " stop at " << config.mStopAtUs << "us";
373 if (res != OK) {
374 status << " (=> " << asString(res) << ")";
375 err = res;
376 } else {
377 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700378 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
379 [&res, &delayUs = config.mInputDelayUs](
380 auto status, auto stopTimeOffsetUs) {
381 res = static_cast<status_t>(status);
382 delayUs = stopTimeOffsetUs;
383 });
384 if (!trans.isOk()) {
385 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
386 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800387 if (res != OK) {
388 status << " (=> " << asString(res) << ")";
389 } else {
390 status << "=" << config.mInputDelayUs << "us";
391 }
392 mConfig.mInputDelayUs = config.mInputDelayUs;
393 }
394 mConfig.mStopAtUs = config.mStopAtUs;
395 mConfig.mStopped = config.mStopped;
396 }
397
398 // color aspects (android._color-aspects)
399
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700400 // consumer usage is queried earlier.
401
Wonsik Kimbd557932019-07-02 15:51:20 -0700402 if (status.str().empty()) {
403 ALOGD("ISConfig not changed");
404 } else {
405 ALOGD("ISConfig%s", status.str().c_str());
406 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800407 return err;
408 }
409
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700410 void onInputBufferDone(c2_cntr64_t index) override {
411 mNode->onInputBufferDone(index);
412 }
413
Pawin Vongmasa36653902018-11-15 00:10:25 -0800414private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700415 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800416 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700417 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800418 uint32_t mWidth;
419 uint32_t mHeight;
420 Config mConfig;
421};
422
423class Codec2ClientInterfaceWrapper : public C2ComponentStore {
424 std::shared_ptr<Codec2Client> mClient;
425
426public:
427 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
428 : mClient(client) { }
429
430 virtual ~Codec2ClientInterfaceWrapper() = default;
431
432 virtual c2_status_t config_sm(
433 const std::vector<C2Param *> &params,
434 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
435 return mClient->config(params, C2_MAY_BLOCK, failures);
436 };
437
438 virtual c2_status_t copyBuffer(
439 std::shared_ptr<C2GraphicBuffer>,
440 std::shared_ptr<C2GraphicBuffer>) {
441 return C2_OMITTED;
442 }
443
444 virtual c2_status_t createComponent(
445 C2String, std::shared_ptr<C2Component> *const component) {
446 component->reset();
447 return C2_OMITTED;
448 }
449
450 virtual c2_status_t createInterface(
451 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
452 interface->reset();
453 return C2_OMITTED;
454 }
455
456 virtual c2_status_t query_sm(
457 const std::vector<C2Param *> &stackParams,
458 const std::vector<C2Param::Index> &heapParamIndices,
459 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
460 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
461 }
462
463 virtual c2_status_t querySupportedParams_nb(
464 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
465 return mClient->querySupportedParams(params);
466 }
467
468 virtual c2_status_t querySupportedValues_sm(
469 std::vector<C2FieldSupportedValuesQuery> &fields) const {
470 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
471 }
472
473 virtual C2String getName() const {
474 return mClient->getName();
475 }
476
477 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
478 return mClient->getParamReflector();
479 }
480
481 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
482 return std::vector<std::shared_ptr<const C2Component::Traits>>();
483 }
484};
485
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800486void RevertOutputFormatIfNeeded(
487 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
488 // We used to not report changes to these keys to the client.
489 const static std::set<std::string> sIgnoredKeys({
490 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800491 KEY_FRAME_RATE,
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800492 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800493 KEY_MAX_WIDTH,
494 KEY_MAX_HEIGHT,
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800495 "csd-0",
496 "csd-1",
497 "csd-2",
498 });
499 if (currentFormat == oldFormat) {
500 return;
501 }
502 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
503 AMessage::Type type;
504 for (size_t i = diff->countEntries(); i > 0; --i) {
505 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
506 diff->removeEntryAt(i - 1);
507 }
508 }
509 if (diff->countEntries() == 0) {
510 currentFormat = oldFormat;
511 }
512}
513
Pawin Vongmasa36653902018-11-15 00:10:25 -0800514} // namespace
515
516// CCodec::ClientListener
517
518struct CCodec::ClientListener : public Codec2Client::Listener {
519
520 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
521
522 virtual void onWorkDone(
523 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800524 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800525 (void)component;
526 sp<CCodec> codec(mCodec.promote());
527 if (!codec) {
528 return;
529 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800530 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800531 }
532
533 virtual void onTripped(
534 const std::weak_ptr<Codec2Client::Component>& component,
535 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
536 ) override {
537 // TODO
538 (void)component;
539 (void)settingResult;
540 }
541
542 virtual void onError(
543 const std::weak_ptr<Codec2Client::Component>& component,
544 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800545 {
546 // Component is only used for reporting as we use a separate listener for each instance
547 std::shared_ptr<Codec2Client::Component> comp = component.lock();
548 if (!comp) {
549 ALOGD("Component died with error: 0x%x", errorCode);
550 } else {
551 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
552 }
553 }
554
555 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800556 // Note: for now we do not propagate the error code to MediaCodec
557 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800558 sp<CCodec> codec(mCodec.promote());
559 if (!codec || !codec->mCallback) {
560 return;
561 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800562 codec->mCallback->onError(
563 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
564 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800565 }
566
567 virtual void onDeath(
568 const std::weak_ptr<Codec2Client::Component>& component) override {
569 { // Log the death of the component.
570 std::shared_ptr<Codec2Client::Component> comp = component.lock();
571 if (!comp) {
572 ALOGE("Codec2 component died.");
573 } else {
574 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
575 }
576 }
577
578 // Report to MediaCodec.
579 sp<CCodec> codec(mCodec.promote());
580 if (!codec || !codec->mCallback) {
581 return;
582 }
583 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
584 }
585
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800586 virtual void onFrameRendered(uint64_t bufferQueueId,
587 int32_t slotId,
588 int64_t timestampNs) override {
589 // TODO: implement
590 (void)bufferQueueId;
591 (void)slotId;
592 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800593 }
594
595 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800596 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800597 sp<CCodec> codec(mCodec.promote());
598 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800599 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800600 }
601 }
602
603private:
604 wp<CCodec> mCodec;
605};
606
607// CCodecCallbackImpl
608
609class CCodecCallbackImpl : public CCodecCallback {
610public:
611 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
612 ~CCodecCallbackImpl() override = default;
613
614 void onError(status_t err, enum ActionCode actionCode) override {
615 mCodec->mCallback->onError(err, actionCode);
616 }
617
618 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
619 mCodec->mCallback->onOutputFramesRendered(
620 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
621 }
622
Pawin Vongmasa36653902018-11-15 00:10:25 -0800623 void onOutputBuffersChanged() override {
624 mCodec->mCallback->onOutputBuffersChanged();
625 }
626
627private:
628 CCodec *mCodec;
629};
630
631// CCodec
632
633CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700634 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
635 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800636}
637
638CCodec::~CCodec() {
639}
640
641std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
642 return mChannel;
643}
644
645status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
646 status_t err = job();
647 if (err != C2_OK) {
648 mCallback->onError(err, ACTION_CODE_FATAL);
649 }
650 return err;
651}
652
653void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
654 auto setAllocating = [this] {
655 Mutexed<State>::Locked state(mState);
656 if (state->get() != RELEASED) {
657 return INVALID_OPERATION;
658 }
659 state->set(ALLOCATING);
660 return OK;
661 };
662 if (tryAndReportOnError(setAllocating) != OK) {
663 return;
664 }
665
666 sp<RefBase> codecInfo;
667 CHECK(msg->findObject("codecInfo", &codecInfo));
668 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
669
670 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
671 allocMsg->setObject("codecInfo", codecInfo);
672 allocMsg->post();
673}
674
675void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
676 if (codecInfo == nullptr) {
677 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
678 return;
679 }
680 ALOGD("allocate(%s)", codecInfo->getCodecName());
681 mClientListener.reset(new ClientListener(this));
682
683 AString componentName = codecInfo->getCodecName();
684 std::shared_ptr<Codec2Client> client;
685
686 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700687 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800688 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800689 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800690 SetPreferredCodec2ComponentStore(
691 std::make_shared<Codec2ClientInterfaceWrapper>(client));
692 }
693
694 std::shared_ptr<Codec2Client::Component> comp =
695 Codec2Client::CreateComponentByName(
696 componentName.c_str(),
697 mClientListener,
698 &client);
699 if (!comp) {
700 ALOGE("Failed Create component: %s", componentName.c_str());
701 Mutexed<State>::Locked state(mState);
702 state->set(RELEASED);
703 state.unlock();
704 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
705 state.lock();
706 return;
707 }
708 ALOGI("Created component [%s]", componentName.c_str());
709 mChannel->setComponent(comp);
710 auto setAllocated = [this, comp, client] {
711 Mutexed<State>::Locked state(mState);
712 if (state->get() != ALLOCATING) {
713 state->set(RELEASED);
714 return UNKNOWN_ERROR;
715 }
716 state->set(ALLOCATED);
717 state->comp = comp;
718 mClient = client;
719 return OK;
720 };
721 if (tryAndReportOnError(setAllocated) != OK) {
722 return;
723 }
724
725 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700726 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
727 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800728 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800729 if (err != OK) {
730 ALOGW("Failed to initialize configuration support");
731 // TODO: report error once we complete implementation.
732 }
733 config->queryConfiguration(comp);
734
735 mCallback->onComponentAllocated(componentName.c_str());
736}
737
738void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
739 auto checkAllocated = [this] {
740 Mutexed<State>::Locked state(mState);
741 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
742 };
743 if (tryAndReportOnError(checkAllocated) != OK) {
744 return;
745 }
746
747 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
748 msg->setMessage("format", format);
749 msg->post();
750}
751
752void CCodec::configure(const sp<AMessage> &msg) {
753 std::shared_ptr<Codec2Client::Component> comp;
754 auto checkAllocated = [this, &comp] {
755 Mutexed<State>::Locked state(mState);
756 if (state->get() != ALLOCATED) {
757 state->set(RELEASED);
758 return UNKNOWN_ERROR;
759 }
760 comp = state->comp;
761 return OK;
762 };
763 if (tryAndReportOnError(checkAllocated) != OK) {
764 return;
765 }
766
767 auto doConfig = [msg, comp, this]() -> status_t {
768 AString mime;
769 if (!msg->findString("mime", &mime)) {
770 return BAD_VALUE;
771 }
772
773 int32_t encoder;
774 if (!msg->findInt32("encoder", &encoder)) {
775 encoder = false;
776 }
777
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800778 int32_t flags;
779 if (!msg->findInt32("flags", &flags)) {
780 return BAD_VALUE;
781 }
782
Pawin Vongmasa36653902018-11-15 00:10:25 -0800783 // TODO: read from intf()
784 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
785 return UNKNOWN_ERROR;
786 }
787
788 int32_t storeMeta;
789 if (encoder
790 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
791 && storeMeta != kMetadataBufferTypeInvalid) {
792 if (storeMeta != kMetadataBufferTypeANWBuffer) {
793 ALOGD("Only ANW buffers are supported for legacy metadata mode");
794 return BAD_VALUE;
795 }
796 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
797 }
798
ted.sun765db4d2020-06-23 14:03:41 +0800799 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800800 sp<RefBase> obj;
801 sp<Surface> surface;
802 if (msg->findObject("native-window", &obj)) {
803 surface = static_cast<Surface *>(obj.get());
ted.sun765db4d2020-06-23 14:03:41 +0800804 // setup tunneled playback
805 if (surface != nullptr) {
806 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
807 const std::unique_ptr<Config> &config = *configLocked;
808 if ((config->mDomain & Config::IS_DECODER)
809 && (config->mDomain & Config::IS_VIDEO)) {
810 int32_t tunneled;
811 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
812 ALOGI("Configuring TUNNELED video playback.");
813
814 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
815 if (err != OK) {
816 ALOGE("configureTunneledVideoPlayback failed!");
817 return err;
818 }
819 config->mTunneled = true;
820 }
821 }
822 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800823 setSurface(surface);
824 }
825
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700826 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
827 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800828 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800829 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
830 ALOGD("[%s] buffers are %sbound to CCodec for this session",
831 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800832
Wonsik Kim1114eea2019-02-25 14:35:24 -0800833 // Enforce required parameters
834 int32_t i32;
835 float flt;
836 if (config->mDomain & Config::IS_AUDIO) {
837 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
838 ALOGD("sample rate is missing, which is required for audio components.");
839 return BAD_VALUE;
840 }
841 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
842 ALOGD("channel count is missing, which is required for audio components.");
843 return BAD_VALUE;
844 }
845 if ((config->mDomain & Config::IS_ENCODER)
846 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
847 && !msg->findInt32(KEY_BIT_RATE, &i32)
848 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
849 ALOGD("bitrate is missing, which is required for audio encoders.");
850 return BAD_VALUE;
851 }
852 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800853 int32_t width = 0;
854 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800855 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800856 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800857 ALOGD("width is missing, which is required for image/video components.");
858 return BAD_VALUE;
859 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800860 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800861 ALOGD("height is missing, which is required for image/video components.");
862 return BAD_VALUE;
863 }
864 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700865 int32_t mode = BITRATE_MODE_VBR;
866 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700867 if (!msg->findInt32(KEY_QUALITY, &i32)) {
868 ALOGD("quality is missing, which is required for video encoders in CQ.");
869 return BAD_VALUE;
870 }
871 } else {
872 if (!msg->findInt32(KEY_BIT_RATE, &i32)
873 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
874 ALOGD("bitrate is missing, which is required for video encoders.");
875 return BAD_VALUE;
876 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800877 }
878 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
879 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
880 ALOGD("I frame interval is missing, which is required for video encoders.");
881 return BAD_VALUE;
882 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700883 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
884 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
885 ALOGD("frame rate is missing, which is required for video encoders.");
886 return BAD_VALUE;
887 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800888 }
889 }
890
Pawin Vongmasa36653902018-11-15 00:10:25 -0800891 /*
892 * Handle input surface configuration
893 */
894 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
895 && (config->mDomain & Config::IS_ENCODER)) {
896 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
897 {
898 config->mISConfig->mMinFps = 0;
899 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800900 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800901 config->mISConfig->mMinFps = 1e6 / value;
902 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700903 if (!msg->findFloat(
904 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
905 config->mISConfig->mMaxFps = -1;
906 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800907 config->mISConfig->mMinAdjustedFps = 0;
908 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800909 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800910 if (value < 0 && value >= INT32_MIN) {
911 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700912 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800913 } else if (value > 0 && value <= INT32_MAX) {
914 config->mISConfig->mMinAdjustedFps = 1e6 / value;
915 }
916 }
917 }
918
919 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700920 bool captureFpsFound = false;
921 double timeLapseFps;
922 float captureRate;
923 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
924 config->mISConfig->mCaptureFps = timeLapseFps;
925 captureFpsFound = true;
926 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
927 config->mISConfig->mCaptureFps = captureRate;
928 captureFpsFound = true;
929 }
930 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800931 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
932 }
933 }
934
935 {
936 config->mISConfig->mSuspended = false;
937 config->mISConfig->mSuspendAtUs = -1;
938 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800939 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800940 config->mISConfig->mSuspended = true;
941 }
942 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700943 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800944 }
945
946 /*
947 * Handle desired color format.
948 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700949 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800950 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700951 int32_t format = 0;
952 // Query vendor format for Flexible YUV
953 std::vector<std::unique_ptr<C2Param>> heapParams;
954 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
955 if (mClient->query(
956 {},
957 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
958 C2_MAY_BLOCK,
959 &heapParams) == C2_OK
960 && heapParams.size() == 1u) {
961 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
962 heapParams[0].get());
963 } else {
964 pixelFormatInfo = nullptr;
965 }
966 std::optional<uint32_t> flexPixelFormat{};
967 std::optional<uint32_t> flexPlanarPixelFormat{};
968 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
969 if (pixelFormatInfo && *pixelFormatInfo) {
970 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
971 const C2FlexiblePixelFormatDescriptorStruct &desc =
972 pixelFormatInfo->m.values[i];
973 if (desc.bitDepth != 8
974 || desc.subsampling != C2Color::YUV_420
975 // TODO(b/180076105): some device report wrong layout
976 // || desc.layout == C2Color::INTERLEAVED_PACKED
977 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
978 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
979 continue;
980 }
981 if (!flexPixelFormat) {
982 flexPixelFormat = desc.pixelFormat;
983 }
984 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
985 flexPlanarPixelFormat = desc.pixelFormat;
986 }
987 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
988 flexSemiPlanarPixelFormat = desc.pixelFormat;
989 }
990 }
991 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800992 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700993 // Also handle default color format (encoders require color format, so this is only
994 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -0800995 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700996 if (surface == nullptr) {
997 format = flexPixelFormat.value_or(COLOR_FormatYUV420Flexible);
998 } else {
999 format = COLOR_FormatSurface;
1000 }
1001 defaultColorFormat = format;
1002 }
1003 } else {
1004 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
1005 switch (format) {
1006 case COLOR_FormatYUV420Flexible:
1007 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
1008 break;
1009 case COLOR_FormatYUV420Planar:
1010 case COLOR_FormatYUV420PackedPlanar:
1011 format = flexPlanarPixelFormat.value_or(
1012 flexPixelFormat.value_or(format));
1013 break;
1014 case COLOR_FormatYUV420SemiPlanar:
1015 case COLOR_FormatYUV420PackedSemiPlanar:
1016 format = flexSemiPlanarPixelFormat.value_or(
1017 flexPixelFormat.value_or(format));
1018 break;
1019 default:
1020 // No-op
1021 break;
1022 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001023 }
1024 }
1025
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001026 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001027 msg->setInt32("android._color-format", format);
1028 }
1029 }
1030
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001031 int32_t subscribeToAllVendorParams;
1032 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1033 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1034 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1035 }
1036 }
1037
Pawin Vongmasa36653902018-11-15 00:10:25 -08001038 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001039 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1040 // the behavior here.
1041 sp<AMessage> sdkParams = msg;
1042 int32_t videoBitrate;
1043 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1044 sdkParams = msg->dup();
1045 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1046 }
ted.sun765db4d2020-06-23 14:03:41 +08001047 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001048 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001049 if (err != OK) {
1050 ALOGW("failed to convert configuration to c2 params");
1051 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001052
1053 int32_t maxBframes = 0;
1054 if ((config->mDomain & Config::IS_ENCODER)
1055 && (config->mDomain & Config::IS_VIDEO)
1056 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1057 && maxBframes > 0) {
1058 std::unique_ptr<C2StreamGopTuning::output> gop =
1059 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1060 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1061 gop->m.values[1] = {
1062 C2Config::picture_type_t(P_FRAME | B_FRAME),
1063 uint32_t(maxBframes)
1064 };
1065 configUpdate.push_back(std::move(gop));
1066 }
1067
Pawin Vongmasa36653902018-11-15 00:10:25 -08001068 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1069 if (err != OK) {
1070 ALOGW("failed to configure c2 params");
1071 return err;
1072 }
1073
1074 std::vector<std::unique_ptr<C2Param>> params;
1075 C2StreamUsageTuning::input usage(0u, 0u);
1076 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001077 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001078
Wonsik Kim58d83332021-02-07 22:19:56 -08001079 C2Param::Index colorAspectsRequestIndex =
1080 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001081 std::initializer_list<C2Param::Index> indices {
Wonsik Kim58d83332021-02-07 22:19:56 -08001082 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001083 };
1084 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001085 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001086 indices,
1087 C2_DONT_BLOCK,
1088 &params);
1089 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1090 ALOGE("Failed to query component interface: %d", c2err);
1091 return UNKNOWN_ERROR;
1092 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001093 if (usage) {
1094 if (usage.value & C2MemoryUsage::CPU_READ) {
1095 config->mInputFormat->setInt32("using-sw-read-often", true);
1096 }
1097 if (config->mISConfig) {
1098 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1099 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1100 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001101 }
1102
1103 // NOTE: we don't blindly use client specified input size if specified as clients
1104 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1105 // client specified size is only used to ask for bigger buffers than component suggested
1106 // size.
1107 int32_t clientInputSize = 0;
1108 bool clientSpecifiedInputSize =
1109 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1110 // TEMP: enforce minimum buffer size of 1MB for video decoders
1111 // and 16K / 4K for audio encoders/decoders
1112 if (maxInputSize.value == 0) {
1113 if (config->mDomain & Config::IS_AUDIO) {
1114 maxInputSize.value = encoder ? 16384 : 4096;
1115 } else if (!encoder) {
1116 maxInputSize.value = 1048576u;
1117 }
1118 }
1119
1120 // verify that CSD fits into this size (if defined)
1121 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1122 sp<ABuffer> csd;
1123 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1124 if (csd && csd->size() > maxInputSize.value) {
1125 maxInputSize.value = csd->size();
1126 }
1127 }
1128 }
1129
1130 // TODO: do this based on component requiring linear allocator for input
1131 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1132 if (clientSpecifiedInputSize) {
1133 // Warn that we're overriding client's max input size if necessary.
1134 if ((uint32_t)clientInputSize < maxInputSize.value) {
1135 ALOGD("client requested max input size %d, which is smaller than "
1136 "what component recommended (%u); overriding with component "
1137 "recommendation.", clientInputSize, maxInputSize.value);
1138 ALOGW("This behavior is subject to change. It is recommended that "
1139 "app developers double check whether the requested "
1140 "max input size is in reasonable range.");
1141 } else {
1142 maxInputSize.value = clientInputSize;
1143 }
1144 }
1145 // Pass max input size on input format to the buffer channel (if supplied by the
1146 // component or by a default)
1147 if (maxInputSize.value) {
1148 config->mInputFormat->setInt32(
1149 KEY_MAX_INPUT_SIZE,
1150 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1151 }
1152 }
1153
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001154 int32_t clientPrepend;
1155 if ((config->mDomain & Config::IS_VIDEO)
1156 && (config->mDomain & Config::IS_ENCODER)
1157 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1158 && clientPrepend
1159 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1160 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1161 return BAD_VALUE;
1162 }
1163
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001164 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001165 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1166 // propagate HDR static info to output format for both encoders and decoders
1167 // if component supports this info, we will update from component, but only the raw port,
1168 // so don't propagate if component already filled it in.
1169 sp<ABuffer> hdrInfo;
1170 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1171 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1172 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1173 }
1174
1175 // Set desired color format from configuration parameter
1176 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001177 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1178 format = defaultColorFormat;
1179 }
1180 if (config->mDomain & Config::IS_ENCODER) {
1181 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001182 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1183 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001184 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001185 } else {
1186 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001187 }
1188 }
1189
1190 // propagate encoder delay and padding to output format
1191 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1192 int delay = 0;
1193 if (msg->findInt32("encoder-delay", &delay)) {
1194 config->mOutputFormat->setInt32("encoder-delay", delay);
1195 }
1196 int padding = 0;
1197 if (msg->findInt32("encoder-padding", &padding)) {
1198 config->mOutputFormat->setInt32("encoder-padding", padding);
1199 }
1200 }
1201
1202 // set channel-mask
1203 if (config->mDomain & Config::IS_AUDIO) {
1204 int32_t mask;
1205 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1206 if (config->mDomain & Config::IS_ENCODER) {
1207 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1208 } else {
1209 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1210 }
1211 }
1212 }
1213
Wonsik Kim58d83332021-02-07 22:19:56 -08001214 std::unique_ptr<C2Param> colorTransferRequestParam;
1215 for (std::unique_ptr<C2Param> &param : params) {
1216 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1217 ALOGI("found color transfer request param");
1218 colorTransferRequestParam = std::move(param);
1219 }
1220 }
1221 int32_t colorTransferRequest = 0;
1222 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1223 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1224 colorTransferRequest = 0;
1225 }
1226
1227 if (colorTransferRequest != 0) {
1228 if (colorTransferRequestParam && *colorTransferRequestParam) {
1229 C2StreamColorAspectsInfo::output *info =
1230 static_cast<C2StreamColorAspectsInfo::output *>(
1231 colorTransferRequestParam.get());
1232 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1233 colorTransferRequest = 0;
1234 }
1235 } else {
1236 colorTransferRequest = 0;
1237 }
1238 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1239 }
1240
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001241 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1242 // Need to get stride/vstride
1243 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1244 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1245 // TODO: retrieve these values without allocating a buffer.
1246 // Currently allocating a buffer is necessary to retrieve the layout.
1247 int64_t blockUsage =
1248 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1249 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1250 width, height, pixelFormat, blockUsage, {comp->getName()});
1251 sp<GraphicBlockBuffer> buffer;
1252 if (block) {
1253 buffer = GraphicBlockBuffer::Allocate(
1254 config->mInputFormat,
1255 block,
1256 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1257 } else {
1258 ALOGD("Failed to allocate a graphic block "
1259 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1260 width, height, pixelFormat, (long long)blockUsage);
1261 // This means that byte buffer mode is not supported in this configuration
1262 // anyway. Skip setting stride/vstride to input format.
1263 }
1264 if (buffer) {
1265 sp<ABuffer> imageData = buffer->getImageData();
1266 MediaImage2 *img = nullptr;
1267 if (imageData && imageData->data()
1268 && imageData->size() >= sizeof(MediaImage2)) {
1269 img = (MediaImage2*)imageData->data();
1270 }
1271 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1272 int32_t stride = img->mPlane[0].mRowInc;
1273 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1274 if (img->mNumPlanes > 1 && stride > 0) {
1275 int64_t offsetDelta =
1276 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1277 if (offsetDelta % stride == 0) {
1278 int32_t vstride = int32_t(offsetDelta / stride);
1279 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1280 } else {
1281 ALOGD("Cannot report accurate slice height: "
1282 "offsetDelta = %lld stride = %d",
1283 (long long)offsetDelta, stride);
1284 }
1285 }
1286 }
1287 }
1288 }
1289 }
1290
1291 ALOGD("setup formats input: %s",
1292 config->mInputFormat->debugString().c_str());
1293 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001294 config->mOutputFormat->debugString().c_str());
1295 return OK;
1296 };
1297 if (tryAndReportOnError(doConfig) != OK) {
1298 return;
1299 }
1300
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001301 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1302 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001303
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001304 config->queryConfiguration(comp);
1305
Pawin Vongmasa36653902018-11-15 00:10:25 -08001306 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1307}
1308
1309void CCodec::initiateCreateInputSurface() {
1310 status_t err = [this] {
1311 Mutexed<State>::Locked state(mState);
1312 if (state->get() != ALLOCATED) {
1313 return UNKNOWN_ERROR;
1314 }
1315 // TODO: read it from intf() properly.
1316 if (state->comp->getName().find("encoder") == std::string::npos) {
1317 return INVALID_OPERATION;
1318 }
1319 return OK;
1320 }();
1321 if (err != OK) {
1322 mCallback->onInputSurfaceCreationFailed(err);
1323 return;
1324 }
1325
1326 (new AMessage(kWhatCreateInputSurface, this))->post();
1327}
1328
Lajos Molnar47118272019-01-31 16:28:04 -08001329sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1330 using namespace android::hardware::media::omx::V1_0;
1331 using namespace android::hardware::media::omx::V1_0::utils;
1332 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1333 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1334 android::sp<IOmx> omx = IOmx::getService();
1335 typedef android::hardware::graphics::bufferqueue::V1_0::
1336 IGraphicBufferProducer HGraphicBufferProducer;
1337 typedef android::hardware::media::omx::V1_0::
1338 IGraphicBufferSource HGraphicBufferSource;
1339 OmxStatus s;
1340 android::sp<HGraphicBufferProducer> gbp;
1341 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001342
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001343 using ::android::hardware::Return;
1344 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001345 [&s, &gbp, &gbs](
1346 OmxStatus status,
1347 const android::sp<HGraphicBufferProducer>& producer,
1348 const android::sp<HGraphicBufferSource>& source) {
1349 s = status;
1350 gbp = producer;
1351 gbs = source;
1352 });
1353 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001354 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001355 }
1356
1357 return nullptr;
1358}
1359
1360sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1361 sp<PersistentSurface> surface(CreateInputSurface());
1362
1363 if (surface == nullptr) {
1364 surface = CreateOmxInputSurface();
1365 }
1366
1367 return surface;
1368}
1369
Pawin Vongmasa36653902018-11-15 00:10:25 -08001370void CCodec::createInputSurface() {
1371 status_t err;
1372 sp<IGraphicBufferProducer> bufferProducer;
1373
1374 sp<AMessage> inputFormat;
1375 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001376 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001377 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001378 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1379 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001380 inputFormat = config->mInputFormat;
1381 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001382 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001383 }
1384
Lajos Molnar47118272019-01-31 16:28:04 -08001385 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001386 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1387 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1388 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001389
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001390 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001391 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1392 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001393 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001394 inputSurface));
1395 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001396 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001397 int32_t width = 0;
1398 (void)outputFormat->findInt32("width", &width);
1399 int32_t height = 0;
1400 (void)outputFormat->findInt32("height", &height);
1401 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001402 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001403 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001404 } else {
1405 ALOGE("Corrupted input surface");
1406 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1407 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001408 }
1409
1410 if (err != OK) {
1411 ALOGE("Failed to set up input surface: %d", err);
1412 mCallback->onInputSurfaceCreationFailed(err);
1413 return;
1414 }
1415
1416 mCallback->onInputSurfaceCreated(
1417 inputFormat,
1418 outputFormat,
1419 new BufferProducerWrapper(bufferProducer));
1420}
1421
1422status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001423 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1424 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001425 config->mUsingSurface = true;
1426
1427 // we are now using surface - apply default color aspects to input format - as well as
1428 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001429 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001430 ALOGD("input format %s to %s",
1431 inputFormatChanged ? "changed" : "unchanged",
1432 config->mInputFormat->debugString().c_str());
1433
1434 // configure dataspace
1435 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1436 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1437 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1438 surface->setDataSpace(dataSpace);
1439
1440 status_t err = mChannel->setInputSurface(surface);
1441 if (err != OK) {
1442 // undo input format update
1443 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001444 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001445 return err;
1446 }
1447 config->mInputSurface = surface;
1448
1449 if (config->mISConfig) {
1450 surface->configure(*config->mISConfig);
1451 } else {
1452 ALOGD("ISConfig: no configuration");
1453 }
1454
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001455 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001456}
1457
1458void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1459 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1460 msg->setObject("surface", surface);
1461 msg->post();
1462}
1463
1464void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1465 sp<AMessage> inputFormat;
1466 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001467 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001468 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001469 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1470 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001471 inputFormat = config->mInputFormat;
1472 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001473 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001474 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001475 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1476 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1477 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1478 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001479 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1480 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1481 if (err != OK) {
1482 ALOGE("Failed to set up input surface: %d", err);
1483 mCallback->onInputSurfaceDeclined(err);
1484 return;
1485 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001486 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001487 int32_t width = 0;
1488 (void)outputFormat->findInt32("width", &width);
1489 int32_t height = 0;
1490 (void)outputFormat->findInt32("height", &height);
1491 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001492 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001493 if (err != OK) {
1494 ALOGE("Failed to set up input surface: %d", err);
1495 mCallback->onInputSurfaceDeclined(err);
1496 return;
1497 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001498 } else {
1499 ALOGE("Failed to set input surface: Corrupted surface.");
1500 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1501 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001502 }
1503 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1504}
1505
1506void CCodec::initiateStart() {
1507 auto setStarting = [this] {
1508 Mutexed<State>::Locked state(mState);
1509 if (state->get() != ALLOCATED) {
1510 return UNKNOWN_ERROR;
1511 }
1512 state->set(STARTING);
1513 return OK;
1514 };
1515 if (tryAndReportOnError(setStarting) != OK) {
1516 return;
1517 }
1518
1519 (new AMessage(kWhatStart, this))->post();
1520}
1521
1522void CCodec::start() {
1523 std::shared_ptr<Codec2Client::Component> comp;
1524 auto checkStarting = [this, &comp] {
1525 Mutexed<State>::Locked state(mState);
1526 if (state->get() != STARTING) {
1527 return UNKNOWN_ERROR;
1528 }
1529 comp = state->comp;
1530 return OK;
1531 };
1532 if (tryAndReportOnError(checkStarting) != OK) {
1533 return;
1534 }
1535
1536 c2_status_t err = comp->start();
1537 if (err != C2_OK) {
1538 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1539 ACTION_CODE_FATAL);
1540 return;
1541 }
1542 sp<AMessage> inputFormat;
1543 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001544 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001545 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001546 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001547 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1548 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001549 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001550 // start triggers format dup
1551 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001552 if (config->mInputSurface) {
1553 err2 = config->mInputSurface->start();
1554 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001555 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001556 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001557 if (err2 != OK) {
1558 mCallback->onError(err2, ACTION_CODE_FATAL);
1559 return;
1560 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001561 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001562 if (err2 != OK) {
1563 mCallback->onError(err2, ACTION_CODE_FATAL);
1564 return;
1565 }
1566
1567 auto setRunning = [this] {
1568 Mutexed<State>::Locked state(mState);
1569 if (state->get() != STARTING) {
1570 return UNKNOWN_ERROR;
1571 }
1572 state->set(RUNNING);
1573 return OK;
1574 };
1575 if (tryAndReportOnError(setRunning) != OK) {
1576 return;
1577 }
1578 mCallback->onStartCompleted();
1579
1580 (void)mChannel->requestInitialInputBuffers();
1581}
1582
1583void CCodec::initiateShutdown(bool keepComponentAllocated) {
1584 if (keepComponentAllocated) {
1585 initiateStop();
1586 } else {
1587 initiateRelease();
1588 }
1589}
1590
1591void CCodec::initiateStop() {
1592 {
1593 Mutexed<State>::Locked state(mState);
1594 if (state->get() == ALLOCATED
1595 || state->get() == RELEASED
1596 || state->get() == STOPPING
1597 || state->get() == RELEASING) {
1598 // We're already stopped, released, or doing it right now.
1599 state.unlock();
1600 mCallback->onStopCompleted();
1601 state.lock();
1602 return;
1603 }
1604 state->set(STOPPING);
1605 }
1606
Wonsik Kim936a89c2020-05-08 16:07:50 -07001607 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001608 (new AMessage(kWhatStop, this))->post();
1609}
1610
1611void CCodec::stop() {
1612 std::shared_ptr<Codec2Client::Component> comp;
1613 {
1614 Mutexed<State>::Locked state(mState);
1615 if (state->get() == RELEASING) {
1616 state.unlock();
1617 // We're already stopped or release is in progress.
1618 mCallback->onStopCompleted();
1619 state.lock();
1620 return;
1621 } else if (state->get() != STOPPING) {
1622 state.unlock();
1623 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1624 state.lock();
1625 return;
1626 }
1627 comp = state->comp;
1628 }
1629 status_t err = comp->stop();
1630 if (err != C2_OK) {
1631 // TODO: convert err into status_t
1632 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1633 }
1634
1635 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001636 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1637 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001638 if (config->mInputSurface) {
1639 config->mInputSurface->disconnect();
1640 config->mInputSurface = nullptr;
1641 }
1642 }
1643 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001644 Mutexed<State>::Locked state(mState);
1645 if (state->get() == STOPPING) {
1646 state->set(ALLOCATED);
1647 }
1648 }
1649 mCallback->onStopCompleted();
1650}
1651
1652void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001653 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001654 {
1655 Mutexed<State>::Locked state(mState);
1656 if (state->get() == RELEASED || state->get() == RELEASING) {
1657 // We're already released or doing it right now.
1658 if (sendCallback) {
1659 state.unlock();
1660 mCallback->onReleaseCompleted();
1661 state.lock();
1662 }
1663 return;
1664 }
1665 if (state->get() == ALLOCATING) {
1666 state->set(RELEASING);
1667 // With the altered state allocate() would fail and clean up.
1668 if (sendCallback) {
1669 state.unlock();
1670 mCallback->onReleaseCompleted();
1671 state.lock();
1672 }
1673 return;
1674 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001675 if (state->get() == STARTING
1676 || state->get() == RUNNING
1677 || state->get() == STOPPING) {
1678 // Input surface may have been started, so clean up is needed.
1679 clearInputSurfaceIfNeeded = true;
1680 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001681 state->set(RELEASING);
1682 }
1683
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001684 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001685 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1686 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001687 if (config->mInputSurface) {
1688 config->mInputSurface->disconnect();
1689 config->mInputSurface = nullptr;
1690 }
1691 }
1692
Wonsik Kim936a89c2020-05-08 16:07:50 -07001693 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001694 // thiz holds strong ref to this while the thread is running.
1695 sp<CCodec> thiz(this);
1696 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1697}
1698
1699void CCodec::release(bool sendCallback) {
1700 std::shared_ptr<Codec2Client::Component> comp;
1701 {
1702 Mutexed<State>::Locked state(mState);
1703 if (state->get() == RELEASED) {
1704 if (sendCallback) {
1705 state.unlock();
1706 mCallback->onReleaseCompleted();
1707 state.lock();
1708 }
1709 return;
1710 }
1711 comp = state->comp;
1712 }
1713 comp->release();
1714
1715 {
1716 Mutexed<State>::Locked state(mState);
1717 state->set(RELEASED);
1718 state->comp.reset();
1719 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001720 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001721 if (sendCallback) {
1722 mCallback->onReleaseCompleted();
1723 }
1724}
1725
1726status_t CCodec::setSurface(const sp<Surface> &surface) {
ted.sun765db4d2020-06-23 14:03:41 +08001727 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1728 const std::unique_ptr<Config> &config = *configLocked;
1729 if (config->mTunneled && config->mSidebandHandle != nullptr) {
1730 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
1731 status_t err = native_window_set_sideband_stream(
1732 nativeWindow.get(),
1733 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
1734 if (err != OK) {
1735 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
1736 nativeWindow.get(), config->mSidebandHandle->handle(), err);
1737 return err;
1738 }
1739 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001740 return mChannel->setSurface(surface);
1741}
1742
1743void CCodec::signalFlush() {
1744 status_t err = [this] {
1745 Mutexed<State>::Locked state(mState);
1746 if (state->get() == FLUSHED) {
1747 return ALREADY_EXISTS;
1748 }
1749 if (state->get() != RUNNING) {
1750 return UNKNOWN_ERROR;
1751 }
1752 state->set(FLUSHING);
1753 return OK;
1754 }();
1755 switch (err) {
1756 case ALREADY_EXISTS:
1757 mCallback->onFlushCompleted();
1758 return;
1759 case OK:
1760 break;
1761 default:
1762 mCallback->onError(err, ACTION_CODE_FATAL);
1763 return;
1764 }
1765
1766 mChannel->stop();
1767 (new AMessage(kWhatFlush, this))->post();
1768}
1769
1770void CCodec::flush() {
1771 std::shared_ptr<Codec2Client::Component> comp;
1772 auto checkFlushing = [this, &comp] {
1773 Mutexed<State>::Locked state(mState);
1774 if (state->get() != FLUSHING) {
1775 return UNKNOWN_ERROR;
1776 }
1777 comp = state->comp;
1778 return OK;
1779 };
1780 if (tryAndReportOnError(checkFlushing) != OK) {
1781 return;
1782 }
1783
1784 std::list<std::unique_ptr<C2Work>> flushedWork;
1785 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1786 {
1787 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1788 flushedWork.splice(flushedWork.end(), *queue);
1789 }
1790 if (err != C2_OK) {
1791 // TODO: convert err into status_t
1792 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1793 }
1794
1795 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001796
1797 {
1798 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001799 if (state->get() == FLUSHING) {
1800 state->set(FLUSHED);
1801 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001802 }
1803 mCallback->onFlushCompleted();
1804}
1805
1806void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001807 std::shared_ptr<Codec2Client::Component> comp;
1808 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001809 Mutexed<State>::Locked state(mState);
1810 if (state->get() != FLUSHED) {
1811 return UNKNOWN_ERROR;
1812 }
1813 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001814 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001815 return OK;
1816 };
1817 if (tryAndReportOnError(setResuming) != OK) {
1818 return;
1819 }
1820
Wonsik Kime75a5da2020-02-14 17:29:03 -08001821 {
1822 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1823 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001824 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001825 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001826 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001827 }
1828
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001829 (void)mChannel->start(nullptr, nullptr, [&]{
1830 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1831 const std::unique_ptr<Config> &config = *configLocked;
1832 return config->mBuffersBoundToCodec;
1833 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001834
1835 {
1836 Mutexed<State>::Locked state(mState);
1837 if (state->get() != RESUMING) {
1838 state.unlock();
1839 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1840 state.lock();
1841 return;
1842 }
1843 state->set(RUNNING);
1844 }
1845
1846 (void)mChannel->requestInitialInputBuffers();
1847}
1848
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001849void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001850 std::shared_ptr<Codec2Client::Component> comp;
1851 auto checkState = [this, &comp] {
1852 Mutexed<State>::Locked state(mState);
1853 if (state->get() == RELEASED) {
1854 return INVALID_OPERATION;
1855 }
1856 comp = state->comp;
1857 return OK;
1858 };
1859 if (tryAndReportOnError(checkState) != OK) {
1860 return;
1861 }
1862
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001863 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1864 // the behavior here.
1865 sp<AMessage> params = msg;
1866 int32_t bitrate;
1867 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1868 params = msg->dup();
1869 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1870 }
1871
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001872 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1873 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001874
1875 /**
1876 * Handle input surface parameters
1877 */
1878 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001879 && (config->mDomain & Config::IS_ENCODER)
1880 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001881 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001882
1883 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1884 config->mISConfig->mStopped = false;
1885 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1886 config->mISConfig->mStopped = true;
1887 }
1888
1889 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001890 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001891 config->mISConfig->mSuspended = value;
1892 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001893 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001894 }
1895
1896 (void)config->mInputSurface->configure(*config->mISConfig);
1897 if (config->mISConfig->mStopped) {
1898 config->mInputFormat->setInt64(
1899 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1900 }
1901 }
1902
1903 std::vector<std::unique_ptr<C2Param>> configUpdate;
1904 (void)config->getConfigUpdateFromSdkParams(
1905 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1906 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1907 // Parameter synchronization is not defined when using input surface. For now, route
1908 // these directly to the component.
1909 if (config->mInputSurface == nullptr
1910 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1911 || comp->getName().find("c2.android.") == 0)) {
1912 mChannel->setParameters(configUpdate);
1913 } else {
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001914 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001915 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001916 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001917 }
1918}
1919
1920void CCodec::signalEndOfInputStream() {
1921 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1922}
1923
1924void CCodec::signalRequestIDRFrame() {
1925 std::shared_ptr<Codec2Client::Component> comp;
1926 {
1927 Mutexed<State>::Locked state(mState);
1928 if (state->get() == RELEASED) {
1929 ALOGD("no IDR request sent since component is released");
1930 return;
1931 }
1932 comp = state->comp;
1933 }
1934 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001935 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1936 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001937 std::vector<std::unique_ptr<C2Param>> params;
1938 params.push_back(
1939 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1940 config->setParameters(comp, params, C2_MAY_BLOCK);
1941}
1942
Wonsik Kimab34ed62019-01-31 15:28:46 -08001943void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001944 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001945 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1946 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001947 }
1948 (new AMessage(kWhatWorkDone, this))->post();
1949}
1950
Wonsik Kimab34ed62019-01-31 15:28:46 -08001951void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1952 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001953 if (arrayIndex == 0) {
1954 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001955 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1956 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001957 if (config->mInputSurface) {
1958 config->mInputSurface->onInputBufferDone(frameIndex);
1959 }
1960 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001961}
1962
1963void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1964 TimePoint now = std::chrono::steady_clock::now();
1965 CCodecWatchdog::getInstance()->watch(this);
1966 switch (msg->what()) {
1967 case kWhatAllocate: {
1968 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001969 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001970 sp<RefBase> obj;
1971 CHECK(msg->findObject("codecInfo", &obj));
1972 allocate((MediaCodecInfo *)obj.get());
1973 break;
1974 }
1975 case kWhatConfigure: {
1976 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001977 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001978 sp<AMessage> format;
1979 CHECK(msg->findMessage("format", &format));
1980 configure(format);
1981 break;
1982 }
1983 case kWhatStart: {
1984 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001985 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001986 start();
1987 break;
1988 }
1989 case kWhatStop: {
1990 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001991 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001992 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001993 break;
1994 }
1995 case kWhatFlush: {
1996 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001997 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001998 flush();
1999 break;
2000 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002001 case kWhatRelease: {
2002 mChannel->release();
2003 mClient.reset();
2004 mClientListener.reset();
2005 break;
2006 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002007 case kWhatCreateInputSurface: {
2008 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002009 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002010 createInputSurface();
2011 break;
2012 }
2013 case kWhatSetInputSurface: {
2014 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002015 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002016 sp<RefBase> obj;
2017 CHECK(msg->findObject("surface", &obj));
2018 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2019 setInputSurface(surface);
2020 break;
2021 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002022 case kWhatWorkDone: {
2023 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002024 bool shouldPost = false;
2025 {
2026 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2027 if (queue->empty()) {
2028 break;
2029 }
2030 work.swap(queue->front());
2031 queue->pop_front();
2032 shouldPost = !queue->empty();
2033 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002034 if (shouldPost) {
2035 (new AMessage(kWhatWorkDone, this))->post();
2036 }
2037
Pawin Vongmasa36653902018-11-15 00:10:25 -08002038 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002039 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2040 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002041 Config::Watcher<C2StreamInitDataInfo::output> initData =
2042 config->watch<C2StreamInitDataInfo::output>();
2043 if (!work->worklets.empty()
2044 && (work->worklets.front()->output.flags
2045 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
2046
2047 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002048 std::vector<std::unique_ptr<C2Param>> updates;
2049 for (const std::unique_ptr<C2Param> &param
2050 : work->worklets.front()->output.configUpdate) {
2051 updates.push_back(C2Param::Copy(*param));
2052 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002053 unsigned stream = 0;
2054 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2055 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2056 // move all info into output-stream #0 domain
2057 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
2058 }
George Burgess IVc813a592020-02-22 22:54:44 -08002059
2060 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2061 // for now only do the first block
2062 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002063 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2064 // block.crop().left, block.crop().top,
2065 // block.crop().width, block.crop().height,
2066 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08002067 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08002068 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
2069 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07002070 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002071 }
2072 ++stream;
2073 }
2074
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002075 sp<AMessage> outputFormat = config->mOutputFormat;
2076 config->updateConfiguration(updates, config->mOutputDomain);
2077 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002078
2079 // copy standard infos to graphic buffers if not already present (otherwise, we
2080 // may overwrite the actual intermediate value with a final value)
2081 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07002082 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002083 C2StreamRotationInfo::output::PARAM_TYPE,
2084 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2085 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2086 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08002087 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08002088 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2089 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2090 };
2091 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2092 if (buf->data().graphicBlocks().size()) {
2093 for (C2Param::Index ix : stdGfxInfos) {
2094 if (!buf->hasInfo(ix)) {
2095 const C2Param *param =
2096 config->getConfigParameterValue(ix.withStream(stream));
2097 if (param) {
2098 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2099 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2100 }
2101 }
2102 }
2103 }
2104 ++stream;
2105 }
2106 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002107 if (config->mInputSurface) {
2108 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2109 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002110 mChannel->onWorkDone(
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002111 std::move(work), config->mOutputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002112 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002113 break;
2114 }
2115 case kWhatWatch: {
2116 // watch message already posted; no-op.
2117 break;
2118 }
2119 default: {
2120 ALOGE("unrecognized message");
2121 break;
2122 }
2123 }
2124 setDeadline(TimePoint::max(), 0ms, "none");
2125}
2126
2127void CCodec::setDeadline(
2128 const TimePoint &now,
2129 const std::chrono::milliseconds &timeout,
2130 const char *name) {
2131 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2132 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2133 deadline->set(now + (timeout * mult), name);
2134}
2135
ted.sun765db4d2020-06-23 14:03:41 +08002136status_t CCodec::configureTunneledVideoPlayback(
2137 std::shared_ptr<Codec2Client::Component> comp,
2138 sp<NativeHandle> *sidebandHandle,
2139 const sp<AMessage> &msg) {
2140 std::vector<std::unique_ptr<C2SettingResult>> failures;
2141
2142 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2143 C2PortTunneledModeTuning::output::AllocUnique(
2144 1,
2145 C2PortTunneledModeTuning::Struct::SIDEBAND,
2146 C2PortTunneledModeTuning::Struct::REALTIME,
2147 0);
2148 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2149 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2150 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2151 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2152 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2153 } else {
2154 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2155 tunneledPlayback->setFlexCount(0);
2156 }
2157 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2158 if (c2err != C2_OK) {
2159 return UNKNOWN_ERROR;
2160 }
2161
2162 std::vector<std::unique_ptr<C2Param>> params;
2163 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2164 if (c2err == C2_OK && params.size() == 1u) {
2165 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2166 C2PortTunnelHandleTuning::output::From(params[0].get());
2167 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2168 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2169 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2170 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2171 memcpy(handle->data, videoTunnelSideband->m.values,
2172 sizeof(int32_t) * videoTunnelSideband->flexCount());
2173 return OK;
2174 } else {
2175 return NO_MEMORY;
2176 }
2177 }
2178 return UNKNOWN_ERROR;
2179}
2180
Pawin Vongmasa36653902018-11-15 00:10:25 -08002181void CCodec::initiateReleaseIfStuck() {
2182 std::string name;
2183 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002184 {
2185 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002186 if (deadline->get() < std::chrono::steady_clock::now()) {
2187 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002188 }
2189 if (deadline->get() != TimePoint::max()) {
2190 pendingDeadline = true;
2191 }
2192 }
ted.sun765db4d2020-06-23 14:03:41 +08002193 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2194 const std::unique_ptr<Config> &config = *configLocked;
2195 if (config->mTunneled == false && name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002196 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2197 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2198 if (elapsed >= kWorkDurationThreshold) {
2199 name = "queue";
2200 }
2201 if (elapsed > 0s) {
2202 pendingDeadline = true;
2203 }
2204 }
2205 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002206 // We're not stuck.
2207 if (pendingDeadline) {
2208 // If we are not stuck yet but still has deadline coming up,
2209 // post watch message to check back later.
2210 (new AMessage(kWhatWatch, this))->post();
2211 }
2212 return;
2213 }
2214
2215 ALOGW("previous call to %s exceeded timeout", name.c_str());
2216 initiateRelease(false);
2217 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2218}
2219
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002220// static
2221PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002222 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002223 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002224 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002225 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2226 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002227 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002228 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2229 sp<IGraphicBufferProducer> gbp;
2230 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2231 status_t err = gbs->initCheck();
2232 if (err != OK) {
2233 ALOGE("Failed to create persistent input surface: error %d", err);
2234 return nullptr;
2235 }
2236 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002237 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002238 } else {
2239 return nullptr;
2240 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002241 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002242 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002243 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002244 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002245 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002246}
2247
Wonsik Kimffb889a2020-05-28 11:32:25 -07002248class IntfCache {
2249public:
2250 IntfCache() = default;
2251
2252 status_t init(const std::string &name) {
2253 std::shared_ptr<Codec2Client::Interface> intf{
2254 Codec2Client::CreateInterfaceByName(name.c_str())};
2255 if (!intf) {
2256 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2257 mInitStatus = NO_INIT;
2258 return NO_INIT;
2259 }
2260 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2261 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2262 C2ParamField{&sUsage, &sUsage.value}));
2263 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2264 if (err != C2_OK) {
2265 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2266 name.c_str(), err);
2267 mFields[0].status = err;
2268 }
2269 std::vector<std::unique_ptr<C2Param>> params;
2270 err = intf->query(
2271 {&mApiFeatures},
2272 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2273 C2_MAY_BLOCK,
2274 &params);
2275 if (err != C2_OK && err != C2_BAD_INDEX) {
2276 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2277 name.c_str(), err);
2278 }
2279 while (!params.empty()) {
2280 C2Param *param = params.back().release();
2281 params.pop_back();
2282 if (!param) {
2283 continue;
2284 }
2285 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2286 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002287 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002288 }
2289 }
2290 mInitStatus = OK;
2291 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002292 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002293
2294 status_t initCheck() const { return mInitStatus; }
2295
2296 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2297 CHECK_EQ(1u, mFields.size());
2298 return mFields[0];
2299 }
2300
2301 const C2ApiFeaturesSetting &getApiFeatures() const {
2302 return mApiFeatures;
2303 }
2304
2305 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2306 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2307 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2308 C2PortAllocatorsTuning::input::AllocUnique(0);
2309 param->invalidate();
2310 return param;
2311 }();
2312 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2313 }
2314
2315private:
2316 status_t mInitStatus{NO_INIT};
2317
2318 std::vector<C2FieldSupportedValuesQuery> mFields;
2319 C2ApiFeaturesSetting mApiFeatures;
2320 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2321};
2322
2323static const IntfCache &GetIntfCache(const std::string &name) {
2324 static IntfCache sNullIntfCache;
2325 static std::mutex sMutex;
2326 static std::map<std::string, IntfCache> sCache;
2327 std::unique_lock<std::mutex> lock{sMutex};
2328 auto it = sCache.find(name);
2329 if (it == sCache.end()) {
2330 lock.unlock();
2331 IntfCache intfCache;
2332 status_t err = intfCache.init(name);
2333 if (err != OK) {
2334 return sNullIntfCache;
2335 }
2336 lock.lock();
2337 it = sCache.insert({name, std::move(intfCache)}).first;
2338 }
2339 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002340}
2341
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002342static status_t GetCommonAllocatorIds(
2343 const std::vector<std::string> &names,
2344 C2Allocator::type_t type,
2345 std::set<C2Allocator::id_t> *ids) {
2346 int poolMask = GetCodec2PoolMask();
2347 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2348 C2Allocator::id_t defaultAllocatorId =
2349 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2350
2351 ids->clear();
2352 if (names.empty()) {
2353 return OK;
2354 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002355 bool firstIteration = true;
2356 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002357 const IntfCache &intfCache = GetIntfCache(name);
2358 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002359 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002360 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002361 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002362 if (firstIteration) {
2363 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002364 if (allocators && allocators.flexCount() > 0) {
2365 ids->insert(allocators.m.values,
2366 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002367 }
2368 if (ids->empty()) {
2369 // The component does not advertise allocators. Use default.
2370 ids->insert(defaultAllocatorId);
2371 }
2372 continue;
2373 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002374 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002375 if (allocators && allocators.flexCount() > 0) {
2376 filtered = true;
2377 for (auto it = ids->begin(); it != ids->end(); ) {
2378 bool found = false;
2379 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2380 if (allocators.m.values[j] == *it) {
2381 found = true;
2382 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002383 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002384 }
2385 if (found) {
2386 ++it;
2387 } else {
2388 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002389 }
2390 }
2391 }
2392 if (!filtered) {
2393 // The component does not advertise supported allocators. Use default.
2394 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2395 if (ids->size() != (containsDefault ? 1 : 0)) {
2396 ids->clear();
2397 if (containsDefault) {
2398 ids->insert(defaultAllocatorId);
2399 }
2400 }
2401 }
2402 }
2403 // Finally, filter with pool masks
2404 for (auto it = ids->begin(); it != ids->end(); ) {
2405 if ((poolMask >> *it) & 1) {
2406 ++it;
2407 } else {
2408 it = ids->erase(it);
2409 }
2410 }
2411 return OK;
2412}
2413
2414static status_t CalculateMinMaxUsage(
2415 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2416 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2417 *minUsage = 0;
2418 *maxUsage = ~0ull;
2419 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002420 const IntfCache &intfCache = GetIntfCache(name);
2421 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002422 continue;
2423 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002424 const C2FieldSupportedValuesQuery &usageSupportedValues =
2425 intfCache.getUsageSupportedValues();
2426 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002427 continue;
2428 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002429 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002430 if (supported.type != C2FieldSupportedValues::FLAGS) {
2431 continue;
2432 }
2433 if (supported.values.empty()) {
2434 *maxUsage = 0;
2435 continue;
2436 }
2437 *minUsage |= supported.values[0].u64;
2438 int64_t currentMaxUsage = 0;
2439 for (const C2Value::Primitive &flags : supported.values) {
2440 currentMaxUsage |= flags.u64;
2441 }
2442 *maxUsage &= currentMaxUsage;
2443 }
2444 return OK;
2445}
2446
2447// static
2448status_t CCodec::CanFetchLinearBlock(
2449 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002450 for (const std::string &name : names) {
2451 const IntfCache &intfCache = GetIntfCache(name);
2452 if (intfCache.initCheck() != OK) {
2453 continue;
2454 }
2455 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2456 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2457 *isCompatible = false;
2458 return OK;
2459 }
2460 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002461 uint64_t minUsage = usage.expected;
2462 uint64_t maxUsage = ~0ull;
2463 std::set<C2Allocator::id_t> allocators;
2464 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2465 if (allocators.empty()) {
2466 *isCompatible = false;
2467 return OK;
2468 }
2469 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2470 *isCompatible = ((maxUsage & minUsage) == minUsage);
2471 return OK;
2472}
2473
2474static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2475 static std::mutex sMutex{};
2476 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2477 std::unique_lock<std::mutex> lock{sMutex};
2478 std::shared_ptr<C2BlockPool> pool;
2479 auto it = sPools.find(allocId);
2480 if (it == sPools.end()) {
2481 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2482 if (err == OK) {
2483 sPools.emplace(allocId, pool);
2484 } else {
2485 pool.reset();
2486 }
2487 } else {
2488 pool = it->second;
2489 }
2490 return pool;
2491}
2492
2493// static
2494std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2495 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
2496 uint64_t minUsage = usage.expected;
2497 uint64_t maxUsage = ~0ull;
2498 std::set<C2Allocator::id_t> allocators;
2499 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2500 if (allocators.empty()) {
2501 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2502 }
2503 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2504 if ((maxUsage & minUsage) != minUsage) {
2505 allocators.clear();
2506 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2507 }
2508 std::shared_ptr<C2LinearBlock> block;
2509 for (C2Allocator::id_t allocId : allocators) {
2510 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2511 if (!pool) {
2512 continue;
2513 }
2514 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2515 if (err != C2_OK || !block) {
2516 block.reset();
2517 continue;
2518 }
2519 break;
2520 }
2521 return block;
2522}
2523
2524// static
2525status_t CCodec::CanFetchGraphicBlock(
2526 const std::vector<std::string> &names, bool *isCompatible) {
2527 uint64_t minUsage = 0;
2528 uint64_t maxUsage = ~0ull;
2529 std::set<C2Allocator::id_t> allocators;
2530 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2531 if (allocators.empty()) {
2532 *isCompatible = false;
2533 return OK;
2534 }
2535 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2536 *isCompatible = ((maxUsage & minUsage) == minUsage);
2537 return OK;
2538}
2539
2540// static
2541std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2542 int32_t width,
2543 int32_t height,
2544 int32_t format,
2545 uint64_t usage,
2546 const std::vector<std::string> &names) {
2547 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2548 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2549 ALOGD("Unrecognized pixel format: %d", format);
2550 return nullptr;
2551 }
2552 uint64_t minUsage = 0;
2553 uint64_t maxUsage = ~0ull;
2554 std::set<C2Allocator::id_t> allocators;
2555 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2556 if (allocators.empty()) {
2557 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2558 }
2559 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2560 minUsage |= usage;
2561 if ((maxUsage & minUsage) != minUsage) {
2562 allocators.clear();
2563 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2564 }
2565 std::shared_ptr<C2GraphicBlock> block;
2566 for (C2Allocator::id_t allocId : allocators) {
2567 std::shared_ptr<C2BlockPool> pool;
2568 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2569 if (err != C2_OK || !pool) {
2570 continue;
2571 }
2572 err = pool->fetchGraphicBlock(
2573 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2574 if (err != C2_OK || !block) {
2575 block.reset();
2576 continue;
2577 }
2578 break;
2579 }
2580 return block;
2581}
2582
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002583} // namespace android