blob: af115928b244957fc142a6fcc5fc8a0d0734894b [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
Wonsik Kim4f13d112021-03-17 04:37:46 +0000214 // 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 Kim3b4349a2020-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 Kim3b4349a2020-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 Kim3b4349a2020-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
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900694 std::shared_ptr<Codec2Client::Component> comp;
695 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800696 componentName.c_str(),
697 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900698 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800699 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900700 if (status != C2_OK) {
701 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800702 Mutexed<State>::Locked state(mState);
703 state->set(RELEASED);
704 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900705 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800706 state.lock();
707 return;
708 }
709 ALOGI("Created component [%s]", componentName.c_str());
710 mChannel->setComponent(comp);
711 auto setAllocated = [this, comp, client] {
712 Mutexed<State>::Locked state(mState);
713 if (state->get() != ALLOCATING) {
714 state->set(RELEASED);
715 return UNKNOWN_ERROR;
716 }
717 state->set(ALLOCATED);
718 state->comp = comp;
719 mClient = client;
720 return OK;
721 };
722 if (tryAndReportOnError(setAllocated) != OK) {
723 return;
724 }
725
726 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700727 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
728 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800729 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800730 if (err != OK) {
731 ALOGW("Failed to initialize configuration support");
732 // TODO: report error once we complete implementation.
733 }
734 config->queryConfiguration(comp);
735
736 mCallback->onComponentAllocated(componentName.c_str());
737}
738
739void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
740 auto checkAllocated = [this] {
741 Mutexed<State>::Locked state(mState);
742 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
743 };
744 if (tryAndReportOnError(checkAllocated) != OK) {
745 return;
746 }
747
748 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
749 msg->setMessage("format", format);
750 msg->post();
751}
752
753void CCodec::configure(const sp<AMessage> &msg) {
754 std::shared_ptr<Codec2Client::Component> comp;
755 auto checkAllocated = [this, &comp] {
756 Mutexed<State>::Locked state(mState);
757 if (state->get() != ALLOCATED) {
758 state->set(RELEASED);
759 return UNKNOWN_ERROR;
760 }
761 comp = state->comp;
762 return OK;
763 };
764 if (tryAndReportOnError(checkAllocated) != OK) {
765 return;
766 }
767
768 auto doConfig = [msg, comp, this]() -> status_t {
769 AString mime;
770 if (!msg->findString("mime", &mime)) {
771 return BAD_VALUE;
772 }
773
774 int32_t encoder;
775 if (!msg->findInt32("encoder", &encoder)) {
776 encoder = false;
777 }
778
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800779 int32_t flags;
780 if (!msg->findInt32("flags", &flags)) {
781 return BAD_VALUE;
782 }
783
Pawin Vongmasa36653902018-11-15 00:10:25 -0800784 // TODO: read from intf()
785 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
786 return UNKNOWN_ERROR;
787 }
788
789 int32_t storeMeta;
790 if (encoder
791 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
792 && storeMeta != kMetadataBufferTypeInvalid) {
793 if (storeMeta != kMetadataBufferTypeANWBuffer) {
794 ALOGD("Only ANW buffers are supported for legacy metadata mode");
795 return BAD_VALUE;
796 }
797 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
798 }
799
ted.sun765db4d2020-06-23 14:03:41 +0800800 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800801 sp<RefBase> obj;
802 sp<Surface> surface;
803 if (msg->findObject("native-window", &obj)) {
804 surface = static_cast<Surface *>(obj.get());
ted.sun765db4d2020-06-23 14:03:41 +0800805 // setup tunneled playback
806 if (surface != nullptr) {
807 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
808 const std::unique_ptr<Config> &config = *configLocked;
809 if ((config->mDomain & Config::IS_DECODER)
810 && (config->mDomain & Config::IS_VIDEO)) {
811 int32_t tunneled;
812 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
813 ALOGI("Configuring TUNNELED video playback.");
814
815 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
816 if (err != OK) {
817 ALOGE("configureTunneledVideoPlayback failed!");
818 return err;
819 }
820 config->mTunneled = true;
821 }
822 }
823 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800824 setSurface(surface);
825 }
826
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700827 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
828 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800829 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800830 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
831 ALOGD("[%s] buffers are %sbound to CCodec for this session",
832 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800833
Wonsik Kim1114eea2019-02-25 14:35:24 -0800834 // Enforce required parameters
835 int32_t i32;
836 float flt;
837 if (config->mDomain & Config::IS_AUDIO) {
838 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
839 ALOGD("sample rate is missing, which is required for audio components.");
840 return BAD_VALUE;
841 }
842 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
843 ALOGD("channel count is missing, which is required for audio components.");
844 return BAD_VALUE;
845 }
846 if ((config->mDomain & Config::IS_ENCODER)
847 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
848 && !msg->findInt32(KEY_BIT_RATE, &i32)
849 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
850 ALOGD("bitrate is missing, which is required for audio encoders.");
851 return BAD_VALUE;
852 }
853 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800854 int32_t width = 0;
855 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800856 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800857 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800858 ALOGD("width is missing, which is required for image/video components.");
859 return BAD_VALUE;
860 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800861 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800862 ALOGD("height is missing, which is required for image/video components.");
863 return BAD_VALUE;
864 }
865 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700866 int32_t mode = BITRATE_MODE_VBR;
867 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700868 if (!msg->findInt32(KEY_QUALITY, &i32)) {
869 ALOGD("quality is missing, which is required for video encoders in CQ.");
870 return BAD_VALUE;
871 }
872 } else {
873 if (!msg->findInt32(KEY_BIT_RATE, &i32)
874 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
875 ALOGD("bitrate is missing, which is required for video encoders.");
876 return BAD_VALUE;
877 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800878 }
879 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
880 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
881 ALOGD("I frame interval is missing, which is required for video encoders.");
882 return BAD_VALUE;
883 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700884 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
885 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
886 ALOGD("frame rate is missing, which is required for video encoders.");
887 return BAD_VALUE;
888 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800889 }
890 }
891
Pawin Vongmasa36653902018-11-15 00:10:25 -0800892 /*
893 * Handle input surface configuration
894 */
895 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
896 && (config->mDomain & Config::IS_ENCODER)) {
897 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
898 {
899 config->mISConfig->mMinFps = 0;
900 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800901 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800902 config->mISConfig->mMinFps = 1e6 / value;
903 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700904 if (!msg->findFloat(
905 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
906 config->mISConfig->mMaxFps = -1;
907 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800908 config->mISConfig->mMinAdjustedFps = 0;
909 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800910 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800911 if (value < 0 && value >= INT32_MIN) {
912 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700913 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800914 } else if (value > 0 && value <= INT32_MAX) {
915 config->mISConfig->mMinAdjustedFps = 1e6 / value;
916 }
917 }
918 }
919
920 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700921 bool captureFpsFound = false;
922 double timeLapseFps;
923 float captureRate;
924 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
925 config->mISConfig->mCaptureFps = timeLapseFps;
926 captureFpsFound = true;
927 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
928 config->mISConfig->mCaptureFps = captureRate;
929 captureFpsFound = true;
930 }
931 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800932 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
933 }
934 }
935
936 {
937 config->mISConfig->mSuspended = false;
938 config->mISConfig->mSuspendAtUs = -1;
939 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800940 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800941 config->mISConfig->mSuspended = true;
942 }
943 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700944 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800945 }
946
947 /*
948 * Handle desired color format.
949 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700950 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800951 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700952 int32_t format = 0;
953 // Query vendor format for Flexible YUV
954 std::vector<std::unique_ptr<C2Param>> heapParams;
955 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
956 if (mClient->query(
957 {},
958 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
959 C2_MAY_BLOCK,
960 &heapParams) == C2_OK
961 && heapParams.size() == 1u) {
962 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
963 heapParams[0].get());
964 } else {
965 pixelFormatInfo = nullptr;
966 }
967 std::optional<uint32_t> flexPixelFormat{};
968 std::optional<uint32_t> flexPlanarPixelFormat{};
969 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
970 if (pixelFormatInfo && *pixelFormatInfo) {
971 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
972 const C2FlexiblePixelFormatDescriptorStruct &desc =
973 pixelFormatInfo->m.values[i];
974 if (desc.bitDepth != 8
975 || desc.subsampling != C2Color::YUV_420
976 // TODO(b/180076105): some device report wrong layout
977 // || desc.layout == C2Color::INTERLEAVED_PACKED
978 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
979 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
980 continue;
981 }
982 if (!flexPixelFormat) {
983 flexPixelFormat = desc.pixelFormat;
984 }
985 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
986 flexPlanarPixelFormat = desc.pixelFormat;
987 }
988 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
989 flexSemiPlanarPixelFormat = desc.pixelFormat;
990 }
991 }
992 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800993 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700994 // Also handle default color format (encoders require color format, so this is only
995 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -0800996 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700997 if (surface == nullptr) {
998 format = flexPixelFormat.value_or(COLOR_FormatYUV420Flexible);
999 } else {
1000 format = COLOR_FormatSurface;
1001 }
1002 defaultColorFormat = format;
1003 }
1004 } else {
1005 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
1006 switch (format) {
1007 case COLOR_FormatYUV420Flexible:
1008 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
1009 break;
1010 case COLOR_FormatYUV420Planar:
1011 case COLOR_FormatYUV420PackedPlanar:
1012 format = flexPlanarPixelFormat.value_or(
1013 flexPixelFormat.value_or(format));
1014 break;
1015 case COLOR_FormatYUV420SemiPlanar:
1016 case COLOR_FormatYUV420PackedSemiPlanar:
1017 format = flexSemiPlanarPixelFormat.value_or(
1018 flexPixelFormat.value_or(format));
1019 break;
1020 default:
1021 // No-op
1022 break;
1023 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001024 }
1025 }
1026
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001027 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001028 msg->setInt32("android._color-format", format);
1029 }
1030 }
1031
Wonsik Kim77e97c72021-01-20 10:33:22 -08001032 /*
1033 * Handle dataspace
1034 */
1035 int32_t usingRecorder;
1036 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1037 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1038 int32_t width, height;
1039 if (msg->findInt32("width", &width)
1040 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001041 ColorAspects aspects;
1042 getColorAspectsFromFormat(msg, aspects);
1043 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001044 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001045 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1046 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001047 }
1048 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1049 ALOGD("setting dataspace to %x", dataSpace);
1050 }
1051
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001052 int32_t subscribeToAllVendorParams;
1053 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1054 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1055 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1056 }
1057 }
1058
Pawin Vongmasa36653902018-11-15 00:10:25 -08001059 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001060 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1061 // the behavior here.
1062 sp<AMessage> sdkParams = msg;
1063 int32_t videoBitrate;
1064 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1065 sdkParams = msg->dup();
1066 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1067 }
ted.sun765db4d2020-06-23 14:03:41 +08001068 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001069 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001070 if (err != OK) {
1071 ALOGW("failed to convert configuration to c2 params");
1072 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001073
1074 int32_t maxBframes = 0;
1075 if ((config->mDomain & Config::IS_ENCODER)
1076 && (config->mDomain & Config::IS_VIDEO)
1077 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1078 && maxBframes > 0) {
1079 std::unique_ptr<C2StreamGopTuning::output> gop =
1080 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1081 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1082 gop->m.values[1] = {
1083 C2Config::picture_type_t(P_FRAME | B_FRAME),
1084 uint32_t(maxBframes)
1085 };
1086 configUpdate.push_back(std::move(gop));
1087 }
1088
Pawin Vongmasa36653902018-11-15 00:10:25 -08001089 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1090 if (err != OK) {
1091 ALOGW("failed to configure c2 params");
1092 return err;
1093 }
1094
1095 std::vector<std::unique_ptr<C2Param>> params;
1096 C2StreamUsageTuning::input usage(0u, 0u);
1097 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001098 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001099
Wonsik Kim3baecda2021-02-07 22:19:56 -08001100 C2Param::Index colorAspectsRequestIndex =
1101 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001102 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001103 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001104 };
1105 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001106 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001107 indices,
1108 C2_DONT_BLOCK,
1109 &params);
1110 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1111 ALOGE("Failed to query component interface: %d", c2err);
1112 return UNKNOWN_ERROR;
1113 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001114 if (usage) {
1115 if (usage.value & C2MemoryUsage::CPU_READ) {
1116 config->mInputFormat->setInt32("using-sw-read-often", true);
1117 }
1118 if (config->mISConfig) {
1119 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1120 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1121 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001122 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001123 }
1124
1125 // NOTE: we don't blindly use client specified input size if specified as clients
1126 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1127 // client specified size is only used to ask for bigger buffers than component suggested
1128 // size.
1129 int32_t clientInputSize = 0;
1130 bool clientSpecifiedInputSize =
1131 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1132 // TEMP: enforce minimum buffer size of 1MB for video decoders
1133 // and 16K / 4K for audio encoders/decoders
1134 if (maxInputSize.value == 0) {
1135 if (config->mDomain & Config::IS_AUDIO) {
1136 maxInputSize.value = encoder ? 16384 : 4096;
1137 } else if (!encoder) {
1138 maxInputSize.value = 1048576u;
1139 }
1140 }
1141
1142 // verify that CSD fits into this size (if defined)
1143 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1144 sp<ABuffer> csd;
1145 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1146 if (csd && csd->size() > maxInputSize.value) {
1147 maxInputSize.value = csd->size();
1148 }
1149 }
1150 }
1151
1152 // TODO: do this based on component requiring linear allocator for input
1153 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1154 if (clientSpecifiedInputSize) {
1155 // Warn that we're overriding client's max input size if necessary.
1156 if ((uint32_t)clientInputSize < maxInputSize.value) {
1157 ALOGD("client requested max input size %d, which is smaller than "
1158 "what component recommended (%u); overriding with component "
1159 "recommendation.", clientInputSize, maxInputSize.value);
1160 ALOGW("This behavior is subject to change. It is recommended that "
1161 "app developers double check whether the requested "
1162 "max input size is in reasonable range.");
1163 } else {
1164 maxInputSize.value = clientInputSize;
1165 }
1166 }
1167 // Pass max input size on input format to the buffer channel (if supplied by the
1168 // component or by a default)
1169 if (maxInputSize.value) {
1170 config->mInputFormat->setInt32(
1171 KEY_MAX_INPUT_SIZE,
1172 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1173 }
1174 }
1175
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001176 int32_t clientPrepend;
1177 if ((config->mDomain & Config::IS_VIDEO)
1178 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001179 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001180 && clientPrepend
1181 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001182 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001183 return BAD_VALUE;
1184 }
1185
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001186 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001187 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1188 // propagate HDR static info to output format for both encoders and decoders
1189 // if component supports this info, we will update from component, but only the raw port,
1190 // so don't propagate if component already filled it in.
1191 sp<ABuffer> hdrInfo;
1192 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1193 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1194 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1195 }
1196
1197 // Set desired color format from configuration parameter
1198 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001199 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1200 format = defaultColorFormat;
1201 }
1202 if (config->mDomain & Config::IS_ENCODER) {
1203 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001204 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1205 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001206 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001207 } else {
1208 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001209 }
1210 }
1211
1212 // propagate encoder delay and padding to output format
1213 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1214 int delay = 0;
1215 if (msg->findInt32("encoder-delay", &delay)) {
1216 config->mOutputFormat->setInt32("encoder-delay", delay);
1217 }
1218 int padding = 0;
1219 if (msg->findInt32("encoder-padding", &padding)) {
1220 config->mOutputFormat->setInt32("encoder-padding", padding);
1221 }
1222 }
1223
1224 // set channel-mask
1225 if (config->mDomain & Config::IS_AUDIO) {
1226 int32_t mask;
1227 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1228 if (config->mDomain & Config::IS_ENCODER) {
1229 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1230 } else {
1231 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1232 }
1233 }
1234 }
1235
Wonsik Kim3baecda2021-02-07 22:19:56 -08001236 std::unique_ptr<C2Param> colorTransferRequestParam;
1237 for (std::unique_ptr<C2Param> &param : params) {
1238 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1239 ALOGI("found color transfer request param");
1240 colorTransferRequestParam = std::move(param);
1241 }
1242 }
1243 int32_t colorTransferRequest = 0;
1244 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1245 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1246 colorTransferRequest = 0;
1247 }
1248
1249 if (colorTransferRequest != 0) {
1250 if (colorTransferRequestParam && *colorTransferRequestParam) {
1251 C2StreamColorAspectsInfo::output *info =
1252 static_cast<C2StreamColorAspectsInfo::output *>(
1253 colorTransferRequestParam.get());
1254 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1255 colorTransferRequest = 0;
1256 }
1257 } else {
1258 colorTransferRequest = 0;
1259 }
1260 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1261 }
1262
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001263 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1264 // Need to get stride/vstride
1265 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1266 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1267 // TODO: retrieve these values without allocating a buffer.
1268 // Currently allocating a buffer is necessary to retrieve the layout.
1269 int64_t blockUsage =
1270 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1271 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1272 width, height, pixelFormat, blockUsage, {comp->getName()});
1273 sp<GraphicBlockBuffer> buffer;
1274 if (block) {
1275 buffer = GraphicBlockBuffer::Allocate(
1276 config->mInputFormat,
1277 block,
1278 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1279 } else {
1280 ALOGD("Failed to allocate a graphic block "
1281 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1282 width, height, pixelFormat, (long long)blockUsage);
1283 // This means that byte buffer mode is not supported in this configuration
1284 // anyway. Skip setting stride/vstride to input format.
1285 }
1286 if (buffer) {
1287 sp<ABuffer> imageData = buffer->getImageData();
1288 MediaImage2 *img = nullptr;
1289 if (imageData && imageData->data()
1290 && imageData->size() >= sizeof(MediaImage2)) {
1291 img = (MediaImage2*)imageData->data();
1292 }
1293 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1294 int32_t stride = img->mPlane[0].mRowInc;
1295 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1296 if (img->mNumPlanes > 1 && stride > 0) {
1297 int64_t offsetDelta =
1298 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1299 if (offsetDelta % stride == 0) {
1300 int32_t vstride = int32_t(offsetDelta / stride);
1301 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1302 } else {
1303 ALOGD("Cannot report accurate slice height: "
1304 "offsetDelta = %lld stride = %d",
1305 (long long)offsetDelta, stride);
1306 }
1307 }
1308 }
1309 }
1310 }
1311 }
1312
1313 ALOGD("setup formats input: %s",
1314 config->mInputFormat->debugString().c_str());
1315 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001316 config->mOutputFormat->debugString().c_str());
1317 return OK;
1318 };
1319 if (tryAndReportOnError(doConfig) != OK) {
1320 return;
1321 }
1322
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001323 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1324 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001325
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001326 config->queryConfiguration(comp);
1327
Pawin Vongmasa36653902018-11-15 00:10:25 -08001328 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1329}
1330
1331void CCodec::initiateCreateInputSurface() {
1332 status_t err = [this] {
1333 Mutexed<State>::Locked state(mState);
1334 if (state->get() != ALLOCATED) {
1335 return UNKNOWN_ERROR;
1336 }
1337 // TODO: read it from intf() properly.
1338 if (state->comp->getName().find("encoder") == std::string::npos) {
1339 return INVALID_OPERATION;
1340 }
1341 return OK;
1342 }();
1343 if (err != OK) {
1344 mCallback->onInputSurfaceCreationFailed(err);
1345 return;
1346 }
1347
1348 (new AMessage(kWhatCreateInputSurface, this))->post();
1349}
1350
Lajos Molnar47118272019-01-31 16:28:04 -08001351sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1352 using namespace android::hardware::media::omx::V1_0;
1353 using namespace android::hardware::media::omx::V1_0::utils;
1354 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1355 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1356 android::sp<IOmx> omx = IOmx::getService();
1357 typedef android::hardware::graphics::bufferqueue::V1_0::
1358 IGraphicBufferProducer HGraphicBufferProducer;
1359 typedef android::hardware::media::omx::V1_0::
1360 IGraphicBufferSource HGraphicBufferSource;
1361 OmxStatus s;
1362 android::sp<HGraphicBufferProducer> gbp;
1363 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001364
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001365 using ::android::hardware::Return;
1366 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001367 [&s, &gbp, &gbs](
1368 OmxStatus status,
1369 const android::sp<HGraphicBufferProducer>& producer,
1370 const android::sp<HGraphicBufferSource>& source) {
1371 s = status;
1372 gbp = producer;
1373 gbs = source;
1374 });
1375 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001376 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001377 }
1378
1379 return nullptr;
1380}
1381
1382sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1383 sp<PersistentSurface> surface(CreateInputSurface());
1384
1385 if (surface == nullptr) {
1386 surface = CreateOmxInputSurface();
1387 }
1388
1389 return surface;
1390}
1391
Pawin Vongmasa36653902018-11-15 00:10:25 -08001392void CCodec::createInputSurface() {
1393 status_t err;
1394 sp<IGraphicBufferProducer> bufferProducer;
1395
1396 sp<AMessage> inputFormat;
1397 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001398 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001399 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001400 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1401 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001402 inputFormat = config->mInputFormat;
1403 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001404 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001405 }
1406
Lajos Molnar47118272019-01-31 16:28:04 -08001407 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001408 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1409 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1410 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001411
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001412 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001413 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1414 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001415 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001416 inputSurface));
1417 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001418 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001419 int32_t width = 0;
1420 (void)outputFormat->findInt32("width", &width);
1421 int32_t height = 0;
1422 (void)outputFormat->findInt32("height", &height);
1423 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001424 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001425 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001426 } else {
1427 ALOGE("Corrupted input surface");
1428 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1429 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001430 }
1431
1432 if (err != OK) {
1433 ALOGE("Failed to set up input surface: %d", err);
1434 mCallback->onInputSurfaceCreationFailed(err);
1435 return;
1436 }
1437
1438 mCallback->onInputSurfaceCreated(
1439 inputFormat,
1440 outputFormat,
1441 new BufferProducerWrapper(bufferProducer));
1442}
1443
1444status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001445 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1446 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001447 config->mUsingSurface = true;
1448
1449 // we are now using surface - apply default color aspects to input format - as well as
1450 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001451 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001452 ALOGD("input format %s to %s",
1453 inputFormatChanged ? "changed" : "unchanged",
1454 config->mInputFormat->debugString().c_str());
1455
1456 // configure dataspace
1457 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1458 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1459 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1460 surface->setDataSpace(dataSpace);
1461
1462 status_t err = mChannel->setInputSurface(surface);
1463 if (err != OK) {
1464 // undo input format update
1465 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001466 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001467 return err;
1468 }
1469 config->mInputSurface = surface;
1470
1471 if (config->mISConfig) {
1472 surface->configure(*config->mISConfig);
1473 } else {
1474 ALOGD("ISConfig: no configuration");
1475 }
1476
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001477 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001478}
1479
1480void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1481 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1482 msg->setObject("surface", surface);
1483 msg->post();
1484}
1485
1486void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1487 sp<AMessage> inputFormat;
1488 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001489 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001490 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001491 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1492 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001493 inputFormat = config->mInputFormat;
1494 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001495 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001496 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001497 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1498 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1499 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1500 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001501 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1502 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1503 if (err != OK) {
1504 ALOGE("Failed to set up input surface: %d", err);
1505 mCallback->onInputSurfaceDeclined(err);
1506 return;
1507 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001508 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001509 int32_t width = 0;
1510 (void)outputFormat->findInt32("width", &width);
1511 int32_t height = 0;
1512 (void)outputFormat->findInt32("height", &height);
1513 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001514 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001515 if (err != OK) {
1516 ALOGE("Failed to set up input surface: %d", err);
1517 mCallback->onInputSurfaceDeclined(err);
1518 return;
1519 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001520 } else {
1521 ALOGE("Failed to set input surface: Corrupted surface.");
1522 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1523 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001524 }
1525 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1526}
1527
1528void CCodec::initiateStart() {
1529 auto setStarting = [this] {
1530 Mutexed<State>::Locked state(mState);
1531 if (state->get() != ALLOCATED) {
1532 return UNKNOWN_ERROR;
1533 }
1534 state->set(STARTING);
1535 return OK;
1536 };
1537 if (tryAndReportOnError(setStarting) != OK) {
1538 return;
1539 }
1540
1541 (new AMessage(kWhatStart, this))->post();
1542}
1543
1544void CCodec::start() {
1545 std::shared_ptr<Codec2Client::Component> comp;
1546 auto checkStarting = [this, &comp] {
1547 Mutexed<State>::Locked state(mState);
1548 if (state->get() != STARTING) {
1549 return UNKNOWN_ERROR;
1550 }
1551 comp = state->comp;
1552 return OK;
1553 };
1554 if (tryAndReportOnError(checkStarting) != OK) {
1555 return;
1556 }
1557
1558 c2_status_t err = comp->start();
1559 if (err != C2_OK) {
1560 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1561 ACTION_CODE_FATAL);
1562 return;
1563 }
1564 sp<AMessage> inputFormat;
1565 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001566 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001567 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001568 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001569 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1570 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001571 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001572 // start triggers format dup
1573 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001574 if (config->mInputSurface) {
1575 err2 = config->mInputSurface->start();
1576 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001577 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001578 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001579 if (err2 != OK) {
1580 mCallback->onError(err2, ACTION_CODE_FATAL);
1581 return;
1582 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001583 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001584 if (err2 != OK) {
1585 mCallback->onError(err2, ACTION_CODE_FATAL);
1586 return;
1587 }
1588
1589 auto setRunning = [this] {
1590 Mutexed<State>::Locked state(mState);
1591 if (state->get() != STARTING) {
1592 return UNKNOWN_ERROR;
1593 }
1594 state->set(RUNNING);
1595 return OK;
1596 };
1597 if (tryAndReportOnError(setRunning) != OK) {
1598 return;
1599 }
1600 mCallback->onStartCompleted();
1601
1602 (void)mChannel->requestInitialInputBuffers();
1603}
1604
1605void CCodec::initiateShutdown(bool keepComponentAllocated) {
1606 if (keepComponentAllocated) {
1607 initiateStop();
1608 } else {
1609 initiateRelease();
1610 }
1611}
1612
1613void CCodec::initiateStop() {
1614 {
1615 Mutexed<State>::Locked state(mState);
1616 if (state->get() == ALLOCATED
1617 || state->get() == RELEASED
1618 || state->get() == STOPPING
1619 || state->get() == RELEASING) {
1620 // We're already stopped, released, or doing it right now.
1621 state.unlock();
1622 mCallback->onStopCompleted();
1623 state.lock();
1624 return;
1625 }
1626 state->set(STOPPING);
1627 }
1628
Wonsik Kim936a89c2020-05-08 16:07:50 -07001629 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001630 (new AMessage(kWhatStop, this))->post();
1631}
1632
1633void CCodec::stop() {
1634 std::shared_ptr<Codec2Client::Component> comp;
1635 {
1636 Mutexed<State>::Locked state(mState);
1637 if (state->get() == RELEASING) {
1638 state.unlock();
1639 // We're already stopped or release is in progress.
1640 mCallback->onStopCompleted();
1641 state.lock();
1642 return;
1643 } else if (state->get() != STOPPING) {
1644 state.unlock();
1645 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1646 state.lock();
1647 return;
1648 }
1649 comp = state->comp;
1650 }
1651 status_t err = comp->stop();
1652 if (err != C2_OK) {
1653 // TODO: convert err into status_t
1654 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1655 }
1656
1657 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001658 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1659 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001660 if (config->mInputSurface) {
1661 config->mInputSurface->disconnect();
1662 config->mInputSurface = nullptr;
1663 }
1664 }
1665 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001666 Mutexed<State>::Locked state(mState);
1667 if (state->get() == STOPPING) {
1668 state->set(ALLOCATED);
1669 }
1670 }
1671 mCallback->onStopCompleted();
1672}
1673
1674void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001675 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001676 {
1677 Mutexed<State>::Locked state(mState);
1678 if (state->get() == RELEASED || state->get() == RELEASING) {
1679 // We're already released or doing it right now.
1680 if (sendCallback) {
1681 state.unlock();
1682 mCallback->onReleaseCompleted();
1683 state.lock();
1684 }
1685 return;
1686 }
1687 if (state->get() == ALLOCATING) {
1688 state->set(RELEASING);
1689 // With the altered state allocate() would fail and clean up.
1690 if (sendCallback) {
1691 state.unlock();
1692 mCallback->onReleaseCompleted();
1693 state.lock();
1694 }
1695 return;
1696 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001697 if (state->get() == STARTING
1698 || state->get() == RUNNING
1699 || state->get() == STOPPING) {
1700 // Input surface may have been started, so clean up is needed.
1701 clearInputSurfaceIfNeeded = true;
1702 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001703 state->set(RELEASING);
1704 }
1705
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001706 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001707 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1708 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001709 if (config->mInputSurface) {
1710 config->mInputSurface->disconnect();
1711 config->mInputSurface = nullptr;
1712 }
1713 }
1714
Wonsik Kim936a89c2020-05-08 16:07:50 -07001715 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001716 // thiz holds strong ref to this while the thread is running.
1717 sp<CCodec> thiz(this);
1718 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1719}
1720
1721void CCodec::release(bool sendCallback) {
1722 std::shared_ptr<Codec2Client::Component> comp;
1723 {
1724 Mutexed<State>::Locked state(mState);
1725 if (state->get() == RELEASED) {
1726 if (sendCallback) {
1727 state.unlock();
1728 mCallback->onReleaseCompleted();
1729 state.lock();
1730 }
1731 return;
1732 }
1733 comp = state->comp;
1734 }
1735 comp->release();
1736
1737 {
1738 Mutexed<State>::Locked state(mState);
1739 state->set(RELEASED);
1740 state->comp.reset();
1741 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001742 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001743 if (sendCallback) {
1744 mCallback->onReleaseCompleted();
1745 }
1746}
1747
1748status_t CCodec::setSurface(const sp<Surface> &surface) {
ted.sun765db4d2020-06-23 14:03:41 +08001749 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1750 const std::unique_ptr<Config> &config = *configLocked;
1751 if (config->mTunneled && config->mSidebandHandle != nullptr) {
1752 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
1753 status_t err = native_window_set_sideband_stream(
1754 nativeWindow.get(),
1755 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
1756 if (err != OK) {
1757 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
1758 nativeWindow.get(), config->mSidebandHandle->handle(), err);
1759 return err;
1760 }
1761 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001762 return mChannel->setSurface(surface);
1763}
1764
1765void CCodec::signalFlush() {
1766 status_t err = [this] {
1767 Mutexed<State>::Locked state(mState);
1768 if (state->get() == FLUSHED) {
1769 return ALREADY_EXISTS;
1770 }
1771 if (state->get() != RUNNING) {
1772 return UNKNOWN_ERROR;
1773 }
1774 state->set(FLUSHING);
1775 return OK;
1776 }();
1777 switch (err) {
1778 case ALREADY_EXISTS:
1779 mCallback->onFlushCompleted();
1780 return;
1781 case OK:
1782 break;
1783 default:
1784 mCallback->onError(err, ACTION_CODE_FATAL);
1785 return;
1786 }
1787
1788 mChannel->stop();
1789 (new AMessage(kWhatFlush, this))->post();
1790}
1791
1792void CCodec::flush() {
1793 std::shared_ptr<Codec2Client::Component> comp;
1794 auto checkFlushing = [this, &comp] {
1795 Mutexed<State>::Locked state(mState);
1796 if (state->get() != FLUSHING) {
1797 return UNKNOWN_ERROR;
1798 }
1799 comp = state->comp;
1800 return OK;
1801 };
1802 if (tryAndReportOnError(checkFlushing) != OK) {
1803 return;
1804 }
1805
1806 std::list<std::unique_ptr<C2Work>> flushedWork;
1807 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1808 {
1809 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1810 flushedWork.splice(flushedWork.end(), *queue);
1811 }
1812 if (err != C2_OK) {
1813 // TODO: convert err into status_t
1814 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1815 }
1816
1817 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001818
1819 {
1820 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001821 if (state->get() == FLUSHING) {
1822 state->set(FLUSHED);
1823 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001824 }
1825 mCallback->onFlushCompleted();
1826}
1827
1828void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001829 std::shared_ptr<Codec2Client::Component> comp;
1830 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001831 Mutexed<State>::Locked state(mState);
1832 if (state->get() != FLUSHED) {
1833 return UNKNOWN_ERROR;
1834 }
1835 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001836 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001837 return OK;
1838 };
1839 if (tryAndReportOnError(setResuming) != OK) {
1840 return;
1841 }
1842
Wonsik Kime75a5da2020-02-14 17:29:03 -08001843 {
1844 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1845 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001846 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001847 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001848 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001849 }
1850
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001851 (void)mChannel->start(nullptr, nullptr, [&]{
1852 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1853 const std::unique_ptr<Config> &config = *configLocked;
1854 return config->mBuffersBoundToCodec;
1855 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001856
1857 {
1858 Mutexed<State>::Locked state(mState);
1859 if (state->get() != RESUMING) {
1860 state.unlock();
1861 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1862 state.lock();
1863 return;
1864 }
1865 state->set(RUNNING);
1866 }
1867
1868 (void)mChannel->requestInitialInputBuffers();
1869}
1870
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001871void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001872 std::shared_ptr<Codec2Client::Component> comp;
1873 auto checkState = [this, &comp] {
1874 Mutexed<State>::Locked state(mState);
1875 if (state->get() == RELEASED) {
1876 return INVALID_OPERATION;
1877 }
1878 comp = state->comp;
1879 return OK;
1880 };
1881 if (tryAndReportOnError(checkState) != OK) {
1882 return;
1883 }
1884
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001885 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1886 // the behavior here.
1887 sp<AMessage> params = msg;
1888 int32_t bitrate;
1889 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1890 params = msg->dup();
1891 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1892 }
1893
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001894 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1895 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001896
1897 /**
1898 * Handle input surface parameters
1899 */
1900 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001901 && (config->mDomain & Config::IS_ENCODER)
1902 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001903 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001904
1905 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1906 config->mISConfig->mStopped = false;
1907 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1908 config->mISConfig->mStopped = true;
1909 }
1910
1911 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001912 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001913 config->mISConfig->mSuspended = value;
1914 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001915 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001916 }
1917
1918 (void)config->mInputSurface->configure(*config->mISConfig);
1919 if (config->mISConfig->mStopped) {
1920 config->mInputFormat->setInt64(
1921 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1922 }
1923 }
1924
1925 std::vector<std::unique_ptr<C2Param>> configUpdate;
1926 (void)config->getConfigUpdateFromSdkParams(
1927 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1928 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1929 // Parameter synchronization is not defined when using input surface. For now, route
1930 // these directly to the component.
1931 if (config->mInputSurface == nullptr
1932 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1933 || comp->getName().find("c2.android.") == 0)) {
1934 mChannel->setParameters(configUpdate);
1935 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08001936 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001937 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08001938 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001939 }
1940}
1941
1942void CCodec::signalEndOfInputStream() {
1943 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1944}
1945
1946void CCodec::signalRequestIDRFrame() {
1947 std::shared_ptr<Codec2Client::Component> comp;
1948 {
1949 Mutexed<State>::Locked state(mState);
1950 if (state->get() == RELEASED) {
1951 ALOGD("no IDR request sent since component is released");
1952 return;
1953 }
1954 comp = state->comp;
1955 }
1956 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001957 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1958 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001959 std::vector<std::unique_ptr<C2Param>> params;
1960 params.push_back(
1961 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1962 config->setParameters(comp, params, C2_MAY_BLOCK);
1963}
1964
Wonsik Kimab34ed62019-01-31 15:28:46 -08001965void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001966 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001967 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1968 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001969 }
1970 (new AMessage(kWhatWorkDone, this))->post();
1971}
1972
Wonsik Kimab34ed62019-01-31 15:28:46 -08001973void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1974 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001975 if (arrayIndex == 0) {
1976 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001977 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1978 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001979 if (config->mInputSurface) {
1980 config->mInputSurface->onInputBufferDone(frameIndex);
1981 }
1982 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001983}
1984
1985void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1986 TimePoint now = std::chrono::steady_clock::now();
1987 CCodecWatchdog::getInstance()->watch(this);
1988 switch (msg->what()) {
1989 case kWhatAllocate: {
1990 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001991 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001992 sp<RefBase> obj;
1993 CHECK(msg->findObject("codecInfo", &obj));
1994 allocate((MediaCodecInfo *)obj.get());
1995 break;
1996 }
1997 case kWhatConfigure: {
1998 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001999 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002000 sp<AMessage> format;
2001 CHECK(msg->findMessage("format", &format));
2002 configure(format);
2003 break;
2004 }
2005 case kWhatStart: {
2006 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002007 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002008 start();
2009 break;
2010 }
2011 case kWhatStop: {
2012 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002013 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002014 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002015 break;
2016 }
2017 case kWhatFlush: {
2018 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002019 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002020 flush();
2021 break;
2022 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002023 case kWhatRelease: {
2024 mChannel->release();
2025 mClient.reset();
2026 mClientListener.reset();
2027 break;
2028 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002029 case kWhatCreateInputSurface: {
2030 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002031 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002032 createInputSurface();
2033 break;
2034 }
2035 case kWhatSetInputSurface: {
2036 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002037 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002038 sp<RefBase> obj;
2039 CHECK(msg->findObject("surface", &obj));
2040 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2041 setInputSurface(surface);
2042 break;
2043 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002044 case kWhatWorkDone: {
2045 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002046 bool shouldPost = false;
2047 {
2048 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2049 if (queue->empty()) {
2050 break;
2051 }
2052 work.swap(queue->front());
2053 queue->pop_front();
2054 shouldPost = !queue->empty();
2055 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002056 if (shouldPost) {
2057 (new AMessage(kWhatWorkDone, this))->post();
2058 }
2059
Pawin Vongmasa36653902018-11-15 00:10:25 -08002060 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002061 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2062 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002063 Config::Watcher<C2StreamInitDataInfo::output> initData =
2064 config->watch<C2StreamInitDataInfo::output>();
2065 if (!work->worklets.empty()
2066 && (work->worklets.front()->output.flags
2067 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
2068
2069 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07002070 std::vector<std::unique_ptr<C2Param>> updates;
2071 for (const std::unique_ptr<C2Param> &param
2072 : work->worklets.front()->output.configUpdate) {
2073 updates.push_back(C2Param::Copy(*param));
2074 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002075 unsigned stream = 0;
2076 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2077 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2078 // move all info into output-stream #0 domain
2079 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
2080 }
George Burgess IVc813a592020-02-22 22:54:44 -08002081
2082 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2083 // for now only do the first block
2084 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002085 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2086 // block.crop().left, block.crop().top,
2087 // block.crop().width, block.crop().height,
2088 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08002089 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08002090 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
2091 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07002092 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002093 }
2094 ++stream;
2095 }
2096
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002097 sp<AMessage> outputFormat = config->mOutputFormat;
2098 config->updateConfiguration(updates, config->mOutputDomain);
2099 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002100
2101 // copy standard infos to graphic buffers if not already present (otherwise, we
2102 // may overwrite the actual intermediate value with a final value)
2103 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07002104 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002105 C2StreamRotationInfo::output::PARAM_TYPE,
2106 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2107 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2108 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08002109 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08002110 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2111 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2112 };
2113 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2114 if (buf->data().graphicBlocks().size()) {
2115 for (C2Param::Index ix : stdGfxInfos) {
2116 if (!buf->hasInfo(ix)) {
2117 const C2Param *param =
2118 config->getConfigParameterValue(ix.withStream(stream));
2119 if (param) {
2120 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2121 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2122 }
2123 }
2124 }
2125 }
2126 ++stream;
2127 }
2128 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002129 if (config->mInputSurface) {
2130 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2131 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002132 mChannel->onWorkDone(
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002133 std::move(work), config->mOutputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002134 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002135 break;
2136 }
2137 case kWhatWatch: {
2138 // watch message already posted; no-op.
2139 break;
2140 }
2141 default: {
2142 ALOGE("unrecognized message");
2143 break;
2144 }
2145 }
2146 setDeadline(TimePoint::max(), 0ms, "none");
2147}
2148
2149void CCodec::setDeadline(
2150 const TimePoint &now,
2151 const std::chrono::milliseconds &timeout,
2152 const char *name) {
2153 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2154 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2155 deadline->set(now + (timeout * mult), name);
2156}
2157
ted.sun765db4d2020-06-23 14:03:41 +08002158status_t CCodec::configureTunneledVideoPlayback(
2159 std::shared_ptr<Codec2Client::Component> comp,
2160 sp<NativeHandle> *sidebandHandle,
2161 const sp<AMessage> &msg) {
2162 std::vector<std::unique_ptr<C2SettingResult>> failures;
2163
2164 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2165 C2PortTunneledModeTuning::output::AllocUnique(
2166 1,
2167 C2PortTunneledModeTuning::Struct::SIDEBAND,
2168 C2PortTunneledModeTuning::Struct::REALTIME,
2169 0);
2170 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2171 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2172 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2173 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2174 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2175 } else {
2176 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2177 tunneledPlayback->setFlexCount(0);
2178 }
2179 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2180 if (c2err != C2_OK) {
2181 return UNKNOWN_ERROR;
2182 }
2183
2184 std::vector<std::unique_ptr<C2Param>> params;
2185 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2186 if (c2err == C2_OK && params.size() == 1u) {
2187 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2188 C2PortTunnelHandleTuning::output::From(params[0].get());
2189 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2190 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2191 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2192 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2193 memcpy(handle->data, videoTunnelSideband->m.values,
2194 sizeof(int32_t) * videoTunnelSideband->flexCount());
2195 return OK;
2196 } else {
2197 return NO_MEMORY;
2198 }
2199 }
2200 return UNKNOWN_ERROR;
2201}
2202
Pawin Vongmasa36653902018-11-15 00:10:25 -08002203void CCodec::initiateReleaseIfStuck() {
2204 std::string name;
2205 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002206 {
2207 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002208 if (deadline->get() < std::chrono::steady_clock::now()) {
2209 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002210 }
2211 if (deadline->get() != TimePoint::max()) {
2212 pendingDeadline = true;
2213 }
2214 }
ted.sun765db4d2020-06-23 14:03:41 +08002215 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2216 const std::unique_ptr<Config> &config = *configLocked;
2217 if (config->mTunneled == false && name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002218 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2219 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2220 if (elapsed >= kWorkDurationThreshold) {
2221 name = "queue";
2222 }
2223 if (elapsed > 0s) {
2224 pendingDeadline = true;
2225 }
2226 }
2227 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002228 // We're not stuck.
2229 if (pendingDeadline) {
2230 // If we are not stuck yet but still has deadline coming up,
2231 // post watch message to check back later.
2232 (new AMessage(kWhatWatch, this))->post();
2233 }
2234 return;
2235 }
2236
2237 ALOGW("previous call to %s exceeded timeout", name.c_str());
2238 initiateRelease(false);
2239 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2240}
2241
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002242// static
2243PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002244 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002245 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002246 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002247 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2248 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002249 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002250 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2251 sp<IGraphicBufferProducer> gbp;
2252 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2253 status_t err = gbs->initCheck();
2254 if (err != OK) {
2255 ALOGE("Failed to create persistent input surface: error %d", err);
2256 return nullptr;
2257 }
2258 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002259 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002260 } else {
2261 return nullptr;
2262 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002263 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002264 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002265 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002266 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002267 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002268}
2269
Wonsik Kimffb889a2020-05-28 11:32:25 -07002270class IntfCache {
2271public:
2272 IntfCache() = default;
2273
2274 status_t init(const std::string &name) {
2275 std::shared_ptr<Codec2Client::Interface> intf{
2276 Codec2Client::CreateInterfaceByName(name.c_str())};
2277 if (!intf) {
2278 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2279 mInitStatus = NO_INIT;
2280 return NO_INIT;
2281 }
2282 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2283 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2284 C2ParamField{&sUsage, &sUsage.value}));
2285 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2286 if (err != C2_OK) {
2287 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2288 name.c_str(), err);
2289 mFields[0].status = err;
2290 }
2291 std::vector<std::unique_ptr<C2Param>> params;
2292 err = intf->query(
2293 {&mApiFeatures},
2294 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2295 C2_MAY_BLOCK,
2296 &params);
2297 if (err != C2_OK && err != C2_BAD_INDEX) {
2298 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2299 name.c_str(), err);
2300 }
2301 while (!params.empty()) {
2302 C2Param *param = params.back().release();
2303 params.pop_back();
2304 if (!param) {
2305 continue;
2306 }
2307 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2308 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002309 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002310 }
2311 }
2312 mInitStatus = OK;
2313 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002314 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002315
2316 status_t initCheck() const { return mInitStatus; }
2317
2318 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2319 CHECK_EQ(1u, mFields.size());
2320 return mFields[0];
2321 }
2322
2323 const C2ApiFeaturesSetting &getApiFeatures() const {
2324 return mApiFeatures;
2325 }
2326
2327 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2328 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2329 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2330 C2PortAllocatorsTuning::input::AllocUnique(0);
2331 param->invalidate();
2332 return param;
2333 }();
2334 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2335 }
2336
2337private:
2338 status_t mInitStatus{NO_INIT};
2339
2340 std::vector<C2FieldSupportedValuesQuery> mFields;
2341 C2ApiFeaturesSetting mApiFeatures;
2342 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2343};
2344
2345static const IntfCache &GetIntfCache(const std::string &name) {
2346 static IntfCache sNullIntfCache;
2347 static std::mutex sMutex;
2348 static std::map<std::string, IntfCache> sCache;
2349 std::unique_lock<std::mutex> lock{sMutex};
2350 auto it = sCache.find(name);
2351 if (it == sCache.end()) {
2352 lock.unlock();
2353 IntfCache intfCache;
2354 status_t err = intfCache.init(name);
2355 if (err != OK) {
2356 return sNullIntfCache;
2357 }
2358 lock.lock();
2359 it = sCache.insert({name, std::move(intfCache)}).first;
2360 }
2361 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002362}
2363
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002364static status_t GetCommonAllocatorIds(
2365 const std::vector<std::string> &names,
2366 C2Allocator::type_t type,
2367 std::set<C2Allocator::id_t> *ids) {
2368 int poolMask = GetCodec2PoolMask();
2369 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2370 C2Allocator::id_t defaultAllocatorId =
2371 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2372
2373 ids->clear();
2374 if (names.empty()) {
2375 return OK;
2376 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002377 bool firstIteration = true;
2378 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002379 const IntfCache &intfCache = GetIntfCache(name);
2380 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002381 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002382 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002383 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002384 if (firstIteration) {
2385 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002386 if (allocators && allocators.flexCount() > 0) {
2387 ids->insert(allocators.m.values,
2388 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002389 }
2390 if (ids->empty()) {
2391 // The component does not advertise allocators. Use default.
2392 ids->insert(defaultAllocatorId);
2393 }
2394 continue;
2395 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002396 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002397 if (allocators && allocators.flexCount() > 0) {
2398 filtered = true;
2399 for (auto it = ids->begin(); it != ids->end(); ) {
2400 bool found = false;
2401 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2402 if (allocators.m.values[j] == *it) {
2403 found = true;
2404 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002405 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002406 }
2407 if (found) {
2408 ++it;
2409 } else {
2410 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002411 }
2412 }
2413 }
2414 if (!filtered) {
2415 // The component does not advertise supported allocators. Use default.
2416 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2417 if (ids->size() != (containsDefault ? 1 : 0)) {
2418 ids->clear();
2419 if (containsDefault) {
2420 ids->insert(defaultAllocatorId);
2421 }
2422 }
2423 }
2424 }
2425 // Finally, filter with pool masks
2426 for (auto it = ids->begin(); it != ids->end(); ) {
2427 if ((poolMask >> *it) & 1) {
2428 ++it;
2429 } else {
2430 it = ids->erase(it);
2431 }
2432 }
2433 return OK;
2434}
2435
2436static status_t CalculateMinMaxUsage(
2437 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2438 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2439 *minUsage = 0;
2440 *maxUsage = ~0ull;
2441 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002442 const IntfCache &intfCache = GetIntfCache(name);
2443 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002444 continue;
2445 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002446 const C2FieldSupportedValuesQuery &usageSupportedValues =
2447 intfCache.getUsageSupportedValues();
2448 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002449 continue;
2450 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002451 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002452 if (supported.type != C2FieldSupportedValues::FLAGS) {
2453 continue;
2454 }
2455 if (supported.values.empty()) {
2456 *maxUsage = 0;
2457 continue;
2458 }
2459 *minUsage |= supported.values[0].u64;
2460 int64_t currentMaxUsage = 0;
2461 for (const C2Value::Primitive &flags : supported.values) {
2462 currentMaxUsage |= flags.u64;
2463 }
2464 *maxUsage &= currentMaxUsage;
2465 }
2466 return OK;
2467}
2468
2469// static
2470status_t CCodec::CanFetchLinearBlock(
2471 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002472 for (const std::string &name : names) {
2473 const IntfCache &intfCache = GetIntfCache(name);
2474 if (intfCache.initCheck() != OK) {
2475 continue;
2476 }
2477 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2478 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2479 *isCompatible = false;
2480 return OK;
2481 }
2482 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002483 std::set<C2Allocator::id_t> allocators;
2484 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2485 if (allocators.empty()) {
2486 *isCompatible = false;
2487 return OK;
2488 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002489
2490 uint64_t minUsage = 0;
2491 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002492 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002493 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002494 *isCompatible = ((maxUsage & minUsage) == minUsage);
2495 return OK;
2496}
2497
2498static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2499 static std::mutex sMutex{};
2500 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2501 std::unique_lock<std::mutex> lock{sMutex};
2502 std::shared_ptr<C2BlockPool> pool;
2503 auto it = sPools.find(allocId);
2504 if (it == sPools.end()) {
2505 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2506 if (err == OK) {
2507 sPools.emplace(allocId, pool);
2508 } else {
2509 pool.reset();
2510 }
2511 } else {
2512 pool = it->second;
2513 }
2514 return pool;
2515}
2516
2517// static
2518std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2519 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002520 std::set<C2Allocator::id_t> allocators;
2521 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2522 if (allocators.empty()) {
2523 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2524 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002525
2526 uint64_t minUsage = 0;
2527 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002528 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002529 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002530 if ((maxUsage & minUsage) != minUsage) {
2531 allocators.clear();
2532 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2533 }
2534 std::shared_ptr<C2LinearBlock> block;
2535 for (C2Allocator::id_t allocId : allocators) {
2536 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2537 if (!pool) {
2538 continue;
2539 }
2540 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2541 if (err != C2_OK || !block) {
2542 block.reset();
2543 continue;
2544 }
2545 break;
2546 }
2547 return block;
2548}
2549
2550// static
2551status_t CCodec::CanFetchGraphicBlock(
2552 const std::vector<std::string> &names, bool *isCompatible) {
2553 uint64_t minUsage = 0;
2554 uint64_t maxUsage = ~0ull;
2555 std::set<C2Allocator::id_t> allocators;
2556 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2557 if (allocators.empty()) {
2558 *isCompatible = false;
2559 return OK;
2560 }
2561 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2562 *isCompatible = ((maxUsage & minUsage) == minUsage);
2563 return OK;
2564}
2565
2566// static
2567std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2568 int32_t width,
2569 int32_t height,
2570 int32_t format,
2571 uint64_t usage,
2572 const std::vector<std::string> &names) {
2573 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2574 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2575 ALOGD("Unrecognized pixel format: %d", format);
2576 return nullptr;
2577 }
2578 uint64_t minUsage = 0;
2579 uint64_t maxUsage = ~0ull;
2580 std::set<C2Allocator::id_t> allocators;
2581 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2582 if (allocators.empty()) {
2583 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2584 }
2585 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2586 minUsage |= usage;
2587 if ((maxUsage & minUsage) != minUsage) {
2588 allocators.clear();
2589 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2590 }
2591 std::shared_ptr<C2GraphicBlock> block;
2592 for (C2Allocator::id_t allocId : allocators) {
2593 std::shared_ptr<C2BlockPool> pool;
2594 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2595 if (err != C2_OK || !pool) {
2596 continue;
2597 }
2598 err = pool->fetchGraphicBlock(
2599 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2600 if (err != C2_OK || !block) {
2601 block.reset();
2602 continue;
2603 }
2604 break;
2605 }
2606 return block;
2607}
2608
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002609} // namespace android