blob: 0b1bbe8ccb886b705194e3447c2792ab1a8dde43 [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodec"
19#include <utils/Log.h>
20
21#include <sstream>
22#include <thread>
23
24#include <C2Config.h>
25#include <C2Debug.h>
26#include <C2ParamInternal.h>
27#include <C2PlatformSupport.h>
28
Pawin Vongmasa36653902018-11-15 00:10:25 -080029#include <android/IOMXBufferSource.h>
Pawin Vongmasabf69de92019-10-29 06:21:27 -070030#include <android/hardware/media/c2/1.0/IInputSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080031#include <android/hardware/media/omx/1.0/IGraphicBufferSource.h>
32#include <android/hardware/media/omx/1.0/IOmx.h>
33#include <android-base/stringprintf.h>
34#include <cutils/properties.h>
35#include <gui/IGraphicBufferProducer.h>
36#include <gui/Surface.h>
37#include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070038#include <media/omx/1.0/WOmxNode.h>
39#include <media/openmax/OMX_Core.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080040#include <media/openmax/OMX_IndexExt.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070041#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
42#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070043#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080044#include <media/stagefright/BufferProducerWrapper.h>
45#include <media/stagefright/MediaCodecConstants.h>
46#include <media/stagefright/PersistentSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080047
48#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080049#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070050#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080051#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080052#include "InputSurfaceWrapper.h"
53
54extern "C" android::PersistentSurface *CreateInputSurface();
55
56namespace android {
57
58using namespace std::chrono_literals;
59using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
60using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080061using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080062
Wonsik Kim9917d4a2019-10-24 12:56:38 -070063typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070064typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070065
Pawin Vongmasa36653902018-11-15 00:10:25 -080066namespace {
67
68class CCodecWatchdog : public AHandler {
69private:
70 enum {
71 kWhatWatch,
72 };
73 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
74
75public:
76 static sp<CCodecWatchdog> getInstance() {
77 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
78 static std::once_flag flag;
79 // Call Init() only once.
80 std::call_once(flag, Init, instance);
81 return instance;
82 }
83
84 ~CCodecWatchdog() = default;
85
86 void watch(sp<CCodec> codec) {
87 bool shouldPost = false;
88 {
89 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
90 // If a watch message is in flight, piggy-back this instance as well.
91 // Otherwise, post a new watch message.
92 shouldPost = codecs->empty();
93 codecs->emplace(codec);
94 }
95 if (shouldPost) {
96 ALOGV("posting watch message");
97 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
98 }
99 }
100
101protected:
102 void onMessageReceived(const sp<AMessage> &msg) {
103 switch (msg->what()) {
104 case kWhatWatch: {
105 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
106 ALOGV("watch for %zu codecs", codecs->size());
107 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
108 sp<CCodec> codec = it->promote();
109 if (codec == nullptr) {
110 continue;
111 }
112 codec->initiateReleaseIfStuck();
113 }
114 codecs->clear();
115 break;
116 }
117
118 default: {
119 TRESPASS("CCodecWatchdog: unrecognized message");
120 }
121 }
122 }
123
124private:
125 CCodecWatchdog() : mLooper(new ALooper) {}
126
127 static void Init(const sp<CCodecWatchdog> &thiz) {
128 ALOGV("Init");
129 thiz->mLooper->setName("CCodecWatchdog");
130 thiz->mLooper->registerHandler(thiz);
131 thiz->mLooper->start();
132 }
133
134 sp<ALooper> mLooper;
135
136 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
137};
138
139class C2InputSurfaceWrapper : public InputSurfaceWrapper {
140public:
141 explicit C2InputSurfaceWrapper(
142 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
143 mSurface(surface) {
144 }
145
146 ~C2InputSurfaceWrapper() override = default;
147
148 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
149 if (mConnection != nullptr) {
150 return ALREADY_EXISTS;
151 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800152 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800153 }
154
155 void disconnect() override {
156 if (mConnection != nullptr) {
157 mConnection->disconnect();
158 mConnection = nullptr;
159 }
160 }
161
162 status_t start() override {
163 // InputSurface does not distinguish started state
164 return OK;
165 }
166
167 status_t signalEndOfInputStream() override {
168 C2InputSurfaceEosTuning eos(true);
169 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800170 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800171 if (err != C2_OK) {
172 return UNKNOWN_ERROR;
173 }
174 return OK;
175 }
176
177 status_t configure(Config &config __unused) {
178 // TODO
179 return OK;
180 }
181
182private:
183 std::shared_ptr<Codec2Client::InputSurface> mSurface;
184 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
185};
186
187class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
188public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700189 typedef hardware::media::omx::V1_0::Status OmxStatus;
190
Pawin Vongmasa36653902018-11-15 00:10:25 -0800191 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700192 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800193 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700194 uint32_t height,
195 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800196 : mSource(source), mWidth(width), mHeight(height) {
197 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700198 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800199 }
200 ~GraphicBufferSourceWrapper() override = default;
201
202 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
203 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700204 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800205 mNode->setFrameSize(mWidth, mHeight);
206
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700207 // Usage is queried during configure(), so setting it beforehand.
208 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
209 (void)mNode->setParameter(
210 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
211 &usage, sizeof(usage));
212
Pawin Vongmasa36653902018-11-15 00:10:25 -0800213 // NOTE: we do not use/pass through color aspects from GraphicBufferSource as we
214 // communicate that directly to the component.
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700215 mSource->configure(
216 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800217 return OK;
218 }
219
220 void disconnect() override {
221 if (mNode == nullptr) {
222 return;
223 }
224 sp<IOMXBufferSource> source = mNode->getSource();
225 if (source == nullptr) {
226 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
227 return;
228 }
229 source->onOmxIdle();
230 source->onOmxLoaded();
231 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700232 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800233 }
234
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700235 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
236 if (status.isOk()) {
237 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
238 } else if (status.isDeadObject()) {
239 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800240 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700241 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800242 }
243
244 status_t start() override {
245 sp<IOMXBufferSource> source = mNode->getSource();
246 if (source == nullptr) {
247 return NO_INIT;
248 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900249
250 size_t numSlots = 4;
251 constexpr OMX_U32 kPortIndexInput = 0;
252
253 OMX_PARAM_PORTDEFINITIONTYPE param;
254 param.nPortIndex = kPortIndexInput;
255 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
256 &param, sizeof(param));
257 if (err == OK) {
258 numSlots = param.nBufferCountActual;
259 }
260
261 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800262 source->onInputBufferAdded(i);
263 }
264
265 source->onOmxExecuting();
266 return OK;
267 }
268
269 status_t signalEndOfInputStream() override {
270 return GetStatus(mSource->signalEndOfInputStream());
271 }
272
273 status_t configure(Config &config) {
274 std::stringstream status;
275 status_t err = OK;
276
277 // handle each configuration granually, in case we need to handle part of the configuration
278 // elsewhere
279
280 // TRICKY: we do not unset frame delay repeating
281 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
282 int64_t us = 1e6 / config.mMinFps + 0.5;
283 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
284 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
285 if (res != OK) {
286 status << " (=> " << asString(res) << ")";
287 err = res;
288 }
289 mConfig.mMinFps = config.mMinFps;
290 }
291
292 // pts gap
293 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
294 if (mNode != nullptr) {
295 OMX_PARAM_U32TYPE ptrGapParam = {};
296 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700297 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800298 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
299 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700300 // float -> uint32_t is undefined if the value is negative.
301 // First convert to int32_t to ensure the expected behavior.
302 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800303 (void)mNode->setParameter(
304 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
305 &ptrGapParam, sizeof(ptrGapParam));
306 }
307 }
308
309 // max fps
310 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700311 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800312 && config.mMaxFps != mConfig.mMaxFps) {
313 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
314 status << " maxFps=" << config.mMaxFps;
315 if (res != OK) {
316 status << " (=> " << asString(res) << ")";
317 err = res;
318 }
319 mConfig.mMaxFps = config.mMaxFps;
320 }
321
322 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
323 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
324 status << " timeOffset " << config.mTimeOffsetUs << "us";
325 if (res != OK) {
326 status << " (=> " << asString(res) << ")";
327 err = res;
328 }
329 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
330 }
331
332 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
333 status_t res =
334 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
335 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
336 if (res != OK) {
337 status << " (=> " << asString(res) << ")";
338 err = res;
339 }
340 mConfig.mCaptureFps = config.mCaptureFps;
341 mConfig.mCodedFps = config.mCodedFps;
342 }
343
344 if (config.mStartAtUs != mConfig.mStartAtUs
345 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
346 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
347 status << " start at " << config.mStartAtUs << "us";
348 if (res != OK) {
349 status << " (=> " << asString(res) << ")";
350 err = res;
351 }
352 mConfig.mStartAtUs = config.mStartAtUs;
353 mConfig.mStopped = config.mStopped;
354 }
355
356 // suspend-resume
357 if (config.mSuspended != mConfig.mSuspended) {
358 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
359 status << " " << (config.mSuspended ? "suspend" : "resume")
360 << " at " << config.mSuspendAtUs << "us";
361 if (res != OK) {
362 status << " (=> " << asString(res) << ")";
363 err = res;
364 }
365 mConfig.mSuspended = config.mSuspended;
366 mConfig.mSuspendAtUs = config.mSuspendAtUs;
367 }
368
369 if (config.mStopped != mConfig.mStopped && config.mStopped) {
370 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
371 status << " stop at " << config.mStopAtUs << "us";
372 if (res != OK) {
373 status << " (=> " << asString(res) << ")";
374 err = res;
375 } else {
376 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700377 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
378 [&res, &delayUs = config.mInputDelayUs](
379 auto status, auto stopTimeOffsetUs) {
380 res = static_cast<status_t>(status);
381 delayUs = stopTimeOffsetUs;
382 });
383 if (!trans.isOk()) {
384 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
385 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800386 if (res != OK) {
387 status << " (=> " << asString(res) << ")";
388 } else {
389 status << "=" << config.mInputDelayUs << "us";
390 }
391 mConfig.mInputDelayUs = config.mInputDelayUs;
392 }
393 mConfig.mStopAtUs = config.mStopAtUs;
394 mConfig.mStopped = config.mStopped;
395 }
396
397 // color aspects (android._color-aspects)
398
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700399 // consumer usage is queried earlier.
400
Wonsik Kimbd557932019-07-02 15:51:20 -0700401 if (status.str().empty()) {
402 ALOGD("ISConfig not changed");
403 } else {
404 ALOGD("ISConfig%s", status.str().c_str());
405 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800406 return err;
407 }
408
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700409 void onInputBufferDone(c2_cntr64_t index) override {
410 mNode->onInputBufferDone(index);
411 }
412
Pawin Vongmasa36653902018-11-15 00:10:25 -0800413private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700414 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800415 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700416 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800417 uint32_t mWidth;
418 uint32_t mHeight;
419 Config mConfig;
420};
421
422class Codec2ClientInterfaceWrapper : public C2ComponentStore {
423 std::shared_ptr<Codec2Client> mClient;
424
425public:
426 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
427 : mClient(client) { }
428
429 virtual ~Codec2ClientInterfaceWrapper() = default;
430
431 virtual c2_status_t config_sm(
432 const std::vector<C2Param *> &params,
433 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
434 return mClient->config(params, C2_MAY_BLOCK, failures);
435 };
436
437 virtual c2_status_t copyBuffer(
438 std::shared_ptr<C2GraphicBuffer>,
439 std::shared_ptr<C2GraphicBuffer>) {
440 return C2_OMITTED;
441 }
442
443 virtual c2_status_t createComponent(
444 C2String, std::shared_ptr<C2Component> *const component) {
445 component->reset();
446 return C2_OMITTED;
447 }
448
449 virtual c2_status_t createInterface(
450 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
451 interface->reset();
452 return C2_OMITTED;
453 }
454
455 virtual c2_status_t query_sm(
456 const std::vector<C2Param *> &stackParams,
457 const std::vector<C2Param::Index> &heapParamIndices,
458 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
459 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
460 }
461
462 virtual c2_status_t querySupportedParams_nb(
463 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
464 return mClient->querySupportedParams(params);
465 }
466
467 virtual c2_status_t querySupportedValues_sm(
468 std::vector<C2FieldSupportedValuesQuery> &fields) const {
469 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
470 }
471
472 virtual C2String getName() const {
473 return mClient->getName();
474 }
475
476 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
477 return mClient->getParamReflector();
478 }
479
480 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
481 return std::vector<std::shared_ptr<const C2Component::Traits>>();
482 }
483};
484
485} // namespace
486
487// CCodec::ClientListener
488
489struct CCodec::ClientListener : public Codec2Client::Listener {
490
491 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
492
493 virtual void onWorkDone(
494 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800495 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800496 (void)component;
497 sp<CCodec> codec(mCodec.promote());
498 if (!codec) {
499 return;
500 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800501 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800502 }
503
504 virtual void onTripped(
505 const std::weak_ptr<Codec2Client::Component>& component,
506 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
507 ) override {
508 // TODO
509 (void)component;
510 (void)settingResult;
511 }
512
513 virtual void onError(
514 const std::weak_ptr<Codec2Client::Component>& component,
515 uint32_t errorCode) override {
516 // TODO
517 (void)component;
518 (void)errorCode;
519 }
520
521 virtual void onDeath(
522 const std::weak_ptr<Codec2Client::Component>& component) override {
523 { // Log the death of the component.
524 std::shared_ptr<Codec2Client::Component> comp = component.lock();
525 if (!comp) {
526 ALOGE("Codec2 component died.");
527 } else {
528 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
529 }
530 }
531
532 // Report to MediaCodec.
533 sp<CCodec> codec(mCodec.promote());
534 if (!codec || !codec->mCallback) {
535 return;
536 }
537 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
538 }
539
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800540 virtual void onFrameRendered(uint64_t bufferQueueId,
541 int32_t slotId,
542 int64_t timestampNs) override {
543 // TODO: implement
544 (void)bufferQueueId;
545 (void)slotId;
546 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800547 }
548
549 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800550 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800551 sp<CCodec> codec(mCodec.promote());
552 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800553 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800554 }
555 }
556
557private:
558 wp<CCodec> mCodec;
559};
560
561// CCodecCallbackImpl
562
563class CCodecCallbackImpl : public CCodecCallback {
564public:
565 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
566 ~CCodecCallbackImpl() override = default;
567
568 void onError(status_t err, enum ActionCode actionCode) override {
569 mCodec->mCallback->onError(err, actionCode);
570 }
571
572 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
573 mCodec->mCallback->onOutputFramesRendered(
574 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
575 }
576
Pawin Vongmasa36653902018-11-15 00:10:25 -0800577 void onOutputBuffersChanged() override {
578 mCodec->mCallback->onOutputBuffersChanged();
579 }
580
581private:
582 CCodec *mCodec;
583};
584
585// CCodec
586
587CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700588 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
589 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800590}
591
592CCodec::~CCodec() {
593}
594
595std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
596 return mChannel;
597}
598
599status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
600 status_t err = job();
601 if (err != C2_OK) {
602 mCallback->onError(err, ACTION_CODE_FATAL);
603 }
604 return err;
605}
606
607void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
608 auto setAllocating = [this] {
609 Mutexed<State>::Locked state(mState);
610 if (state->get() != RELEASED) {
611 return INVALID_OPERATION;
612 }
613 state->set(ALLOCATING);
614 return OK;
615 };
616 if (tryAndReportOnError(setAllocating) != OK) {
617 return;
618 }
619
620 sp<RefBase> codecInfo;
621 CHECK(msg->findObject("codecInfo", &codecInfo));
622 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
623
624 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
625 allocMsg->setObject("codecInfo", codecInfo);
626 allocMsg->post();
627}
628
629void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
630 if (codecInfo == nullptr) {
631 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
632 return;
633 }
634 ALOGD("allocate(%s)", codecInfo->getCodecName());
635 mClientListener.reset(new ClientListener(this));
636
637 AString componentName = codecInfo->getCodecName();
638 std::shared_ptr<Codec2Client> client;
639
640 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700641 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800642 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800643 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800644 SetPreferredCodec2ComponentStore(
645 std::make_shared<Codec2ClientInterfaceWrapper>(client));
646 }
647
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900648 std::shared_ptr<Codec2Client::Component> comp;
649 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800650 componentName.c_str(),
651 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900652 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800653 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900654 if (status != C2_OK) {
655 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800656 Mutexed<State>::Locked state(mState);
657 state->set(RELEASED);
658 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900659 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800660 state.lock();
661 return;
662 }
663 ALOGI("Created component [%s]", componentName.c_str());
664 mChannel->setComponent(comp);
665 auto setAllocated = [this, comp, client] {
666 Mutexed<State>::Locked state(mState);
667 if (state->get() != ALLOCATING) {
668 state->set(RELEASED);
669 return UNKNOWN_ERROR;
670 }
671 state->set(ALLOCATED);
672 state->comp = comp;
673 mClient = client;
674 return OK;
675 };
676 if (tryAndReportOnError(setAllocated) != OK) {
677 return;
678 }
679
680 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700681 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
682 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800683 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800684 if (err != OK) {
685 ALOGW("Failed to initialize configuration support");
686 // TODO: report error once we complete implementation.
687 }
688 config->queryConfiguration(comp);
689
690 mCallback->onComponentAllocated(componentName.c_str());
691}
692
693void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
694 auto checkAllocated = [this] {
695 Mutexed<State>::Locked state(mState);
696 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
697 };
698 if (tryAndReportOnError(checkAllocated) != OK) {
699 return;
700 }
701
702 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
703 msg->setMessage("format", format);
704 msg->post();
705}
706
707void CCodec::configure(const sp<AMessage> &msg) {
708 std::shared_ptr<Codec2Client::Component> comp;
709 auto checkAllocated = [this, &comp] {
710 Mutexed<State>::Locked state(mState);
711 if (state->get() != ALLOCATED) {
712 state->set(RELEASED);
713 return UNKNOWN_ERROR;
714 }
715 comp = state->comp;
716 return OK;
717 };
718 if (tryAndReportOnError(checkAllocated) != OK) {
719 return;
720 }
721
722 auto doConfig = [msg, comp, this]() -> status_t {
723 AString mime;
724 if (!msg->findString("mime", &mime)) {
725 return BAD_VALUE;
726 }
727
728 int32_t encoder;
729 if (!msg->findInt32("encoder", &encoder)) {
730 encoder = false;
731 }
732
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800733 int32_t flags;
734 if (!msg->findInt32("flags", &flags)) {
735 return BAD_VALUE;
736 }
737
Pawin Vongmasa36653902018-11-15 00:10:25 -0800738 // TODO: read from intf()
739 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
740 return UNKNOWN_ERROR;
741 }
742
743 int32_t storeMeta;
744 if (encoder
745 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
746 && storeMeta != kMetadataBufferTypeInvalid) {
747 if (storeMeta != kMetadataBufferTypeANWBuffer) {
748 ALOGD("Only ANW buffers are supported for legacy metadata mode");
749 return BAD_VALUE;
750 }
751 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
752 }
753
754 sp<RefBase> obj;
755 sp<Surface> surface;
756 if (msg->findObject("native-window", &obj)) {
757 surface = static_cast<Surface *>(obj.get());
758 setSurface(surface);
759 }
760
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700761 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
762 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800763 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800764 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
765 ALOGD("[%s] buffers are %sbound to CCodec for this session",
766 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800767
Wonsik Kim1114eea2019-02-25 14:35:24 -0800768 // Enforce required parameters
769 int32_t i32;
770 float flt;
771 if (config->mDomain & Config::IS_AUDIO) {
772 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
773 ALOGD("sample rate is missing, which is required for audio components.");
774 return BAD_VALUE;
775 }
776 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
777 ALOGD("channel count is missing, which is required for audio components.");
778 return BAD_VALUE;
779 }
780 if ((config->mDomain & Config::IS_ENCODER)
781 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
782 && !msg->findInt32(KEY_BIT_RATE, &i32)
783 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
784 ALOGD("bitrate is missing, which is required for audio encoders.");
785 return BAD_VALUE;
786 }
787 }
788 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
789 if (!msg->findInt32(KEY_WIDTH, &i32)) {
790 ALOGD("width is missing, which is required for image/video components.");
791 return BAD_VALUE;
792 }
793 if (!msg->findInt32(KEY_HEIGHT, &i32)) {
794 ALOGD("height is missing, which is required for image/video components.");
795 return BAD_VALUE;
796 }
797 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700798 int32_t mode = BITRATE_MODE_VBR;
799 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700800 if (!msg->findInt32(KEY_QUALITY, &i32)) {
801 ALOGD("quality is missing, which is required for video encoders in CQ.");
802 return BAD_VALUE;
803 }
804 } else {
805 if (!msg->findInt32(KEY_BIT_RATE, &i32)
806 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
807 ALOGD("bitrate is missing, which is required for video encoders.");
808 return BAD_VALUE;
809 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800810 }
811 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
812 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
813 ALOGD("I frame interval is missing, which is required for video encoders.");
814 return BAD_VALUE;
815 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700816 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
817 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
818 ALOGD("frame rate is missing, which is required for video encoders.");
819 return BAD_VALUE;
820 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800821 }
822 }
823
Pawin Vongmasa36653902018-11-15 00:10:25 -0800824 /*
825 * Handle input surface configuration
826 */
827 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
828 && (config->mDomain & Config::IS_ENCODER)) {
829 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
830 {
831 config->mISConfig->mMinFps = 0;
832 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800833 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800834 config->mISConfig->mMinFps = 1e6 / value;
835 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700836 if (!msg->findFloat(
837 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
838 config->mISConfig->mMaxFps = -1;
839 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800840 config->mISConfig->mMinAdjustedFps = 0;
841 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800842 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800843 if (value < 0 && value >= INT32_MIN) {
844 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700845 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800846 } else if (value > 0 && value <= INT32_MAX) {
847 config->mISConfig->mMinAdjustedFps = 1e6 / value;
848 }
849 }
850 }
851
852 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700853 bool captureFpsFound = false;
854 double timeLapseFps;
855 float captureRate;
856 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
857 config->mISConfig->mCaptureFps = timeLapseFps;
858 captureFpsFound = true;
859 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
860 config->mISConfig->mCaptureFps = captureRate;
861 captureFpsFound = true;
862 }
863 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800864 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
865 }
866 }
867
868 {
869 config->mISConfig->mSuspended = false;
870 config->mISConfig->mSuspendAtUs = -1;
871 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800872 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800873 config->mISConfig->mSuspended = true;
874 }
875 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700876 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800877 }
878
879 /*
880 * Handle desired color format.
881 */
882 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
883 int32_t format = -1;
884 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
885 /*
886 * Also handle default color format (encoders require color format, so this is only
887 * needed for decoders.
888 */
889 if (!(config->mDomain & Config::IS_ENCODER)) {
890 format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
891 }
892 }
893
894 if (format >= 0) {
895 msg->setInt32("android._color-format", format);
896 }
897 }
898
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800899 int32_t subscribeToAllVendorParams;
900 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
901 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
902 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
903 }
904 }
905
Pawin Vongmasa36653902018-11-15 00:10:25 -0800906 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800907 // NOTE: We used to ignore "video-bitrate" at configure; replicate
908 // the behavior here.
909 sp<AMessage> sdkParams = msg;
910 int32_t videoBitrate;
911 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
912 sdkParams = msg->dup();
913 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
914 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800915 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800916 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800917 if (err != OK) {
918 ALOGW("failed to convert configuration to c2 params");
919 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700920
921 int32_t maxBframes = 0;
922 if ((config->mDomain & Config::IS_ENCODER)
923 && (config->mDomain & Config::IS_VIDEO)
924 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
925 && maxBframes > 0) {
926 std::unique_ptr<C2StreamGopTuning::output> gop =
927 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
928 gop->m.values[0] = { P_FRAME, UINT32_MAX };
929 gop->m.values[1] = {
930 C2Config::picture_type_t(P_FRAME | B_FRAME),
931 uint32_t(maxBframes)
932 };
933 configUpdate.push_back(std::move(gop));
934 }
935
Pawin Vongmasa36653902018-11-15 00:10:25 -0800936 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
937 if (err != OK) {
938 ALOGW("failed to configure c2 params");
939 return err;
940 }
941
942 std::vector<std::unique_ptr<C2Param>> params;
943 C2StreamUsageTuning::input usage(0u, 0u);
944 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700945 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800946
947 std::initializer_list<C2Param::Index> indices {
948 };
949 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700950 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -0800951 indices,
952 C2_DONT_BLOCK,
953 &params);
954 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
955 ALOGE("Failed to query component interface: %d", c2err);
956 return UNKNOWN_ERROR;
957 }
958 if (params.size() != indices.size()) {
959 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
960 indices.size(), params.size());
961 return UNKNOWN_ERROR;
962 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700963 if (usage) {
964 if (usage.value & C2MemoryUsage::CPU_READ) {
965 config->mInputFormat->setInt32("using-sw-read-often", true);
966 }
967 if (config->mISConfig) {
968 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
969 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
970 }
Wonsik Kim666604a2020-05-14 16:57:49 -0700971 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800972 }
973
974 // NOTE: we don't blindly use client specified input size if specified as clients
975 // at times specify too small size. Instead, mimic the behavior from OMX, where the
976 // client specified size is only used to ask for bigger buffers than component suggested
977 // size.
978 int32_t clientInputSize = 0;
979 bool clientSpecifiedInputSize =
980 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
981 // TEMP: enforce minimum buffer size of 1MB for video decoders
982 // and 16K / 4K for audio encoders/decoders
983 if (maxInputSize.value == 0) {
984 if (config->mDomain & Config::IS_AUDIO) {
985 maxInputSize.value = encoder ? 16384 : 4096;
986 } else if (!encoder) {
987 maxInputSize.value = 1048576u;
988 }
989 }
990
991 // verify that CSD fits into this size (if defined)
992 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
993 sp<ABuffer> csd;
994 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
995 if (csd && csd->size() > maxInputSize.value) {
996 maxInputSize.value = csd->size();
997 }
998 }
999 }
1000
1001 // TODO: do this based on component requiring linear allocator for input
1002 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1003 if (clientSpecifiedInputSize) {
1004 // Warn that we're overriding client's max input size if necessary.
1005 if ((uint32_t)clientInputSize < maxInputSize.value) {
1006 ALOGD("client requested max input size %d, which is smaller than "
1007 "what component recommended (%u); overriding with component "
1008 "recommendation.", clientInputSize, maxInputSize.value);
1009 ALOGW("This behavior is subject to change. It is recommended that "
1010 "app developers double check whether the requested "
1011 "max input size is in reasonable range.");
1012 } else {
1013 maxInputSize.value = clientInputSize;
1014 }
1015 }
1016 // Pass max input size on input format to the buffer channel (if supplied by the
1017 // component or by a default)
1018 if (maxInputSize.value) {
1019 config->mInputFormat->setInt32(
1020 KEY_MAX_INPUT_SIZE,
1021 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1022 }
1023 }
1024
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001025 int32_t clientPrepend;
1026 if ((config->mDomain & Config::IS_VIDEO)
1027 && (config->mDomain & Config::IS_ENCODER)
1028 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1029 && clientPrepend
1030 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1031 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1032 return BAD_VALUE;
1033 }
1034
Pawin Vongmasa36653902018-11-15 00:10:25 -08001035 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1036 // propagate HDR static info to output format for both encoders and decoders
1037 // if component supports this info, we will update from component, but only the raw port,
1038 // so don't propagate if component already filled it in.
1039 sp<ABuffer> hdrInfo;
1040 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1041 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1042 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1043 }
1044
1045 // Set desired color format from configuration parameter
1046 int32_t format;
1047 if (msg->findInt32("android._color-format", &format)) {
1048 if (config->mDomain & Config::IS_ENCODER) {
1049 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
1050 } else {
1051 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
1052 }
1053 }
1054 }
1055
1056 // propagate encoder delay and padding to output format
1057 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1058 int delay = 0;
1059 if (msg->findInt32("encoder-delay", &delay)) {
1060 config->mOutputFormat->setInt32("encoder-delay", delay);
1061 }
1062 int padding = 0;
1063 if (msg->findInt32("encoder-padding", &padding)) {
1064 config->mOutputFormat->setInt32("encoder-padding", padding);
1065 }
1066 }
1067
1068 // set channel-mask
1069 if (config->mDomain & Config::IS_AUDIO) {
1070 int32_t mask;
1071 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1072 if (config->mDomain & Config::IS_ENCODER) {
1073 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1074 } else {
1075 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1076 }
1077 }
1078 }
1079
1080 ALOGD("setup formats input: %s and output: %s",
1081 config->mInputFormat->debugString().c_str(),
1082 config->mOutputFormat->debugString().c_str());
1083 return OK;
1084 };
1085 if (tryAndReportOnError(doConfig) != OK) {
1086 return;
1087 }
1088
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001089 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1090 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001091
1092 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1093}
1094
1095void CCodec::initiateCreateInputSurface() {
1096 status_t err = [this] {
1097 Mutexed<State>::Locked state(mState);
1098 if (state->get() != ALLOCATED) {
1099 return UNKNOWN_ERROR;
1100 }
1101 // TODO: read it from intf() properly.
1102 if (state->comp->getName().find("encoder") == std::string::npos) {
1103 return INVALID_OPERATION;
1104 }
1105 return OK;
1106 }();
1107 if (err != OK) {
1108 mCallback->onInputSurfaceCreationFailed(err);
1109 return;
1110 }
1111
1112 (new AMessage(kWhatCreateInputSurface, this))->post();
1113}
1114
Lajos Molnar47118272019-01-31 16:28:04 -08001115sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1116 using namespace android::hardware::media::omx::V1_0;
1117 using namespace android::hardware::media::omx::V1_0::utils;
1118 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1119 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1120 android::sp<IOmx> omx = IOmx::getService();
1121 typedef android::hardware::graphics::bufferqueue::V1_0::
1122 IGraphicBufferProducer HGraphicBufferProducer;
1123 typedef android::hardware::media::omx::V1_0::
1124 IGraphicBufferSource HGraphicBufferSource;
1125 OmxStatus s;
1126 android::sp<HGraphicBufferProducer> gbp;
1127 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001128
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001129 using ::android::hardware::Return;
1130 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001131 [&s, &gbp, &gbs](
1132 OmxStatus status,
1133 const android::sp<HGraphicBufferProducer>& producer,
1134 const android::sp<HGraphicBufferSource>& source) {
1135 s = status;
1136 gbp = producer;
1137 gbs = source;
1138 });
1139 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001140 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001141 }
1142
1143 return nullptr;
1144}
1145
1146sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1147 sp<PersistentSurface> surface(CreateInputSurface());
1148
1149 if (surface == nullptr) {
1150 surface = CreateOmxInputSurface();
1151 }
1152
1153 return surface;
1154}
1155
Pawin Vongmasa36653902018-11-15 00:10:25 -08001156void CCodec::createInputSurface() {
1157 status_t err;
1158 sp<IGraphicBufferProducer> bufferProducer;
1159
1160 sp<AMessage> inputFormat;
1161 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001162 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001163 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001164 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1165 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001166 inputFormat = config->mInputFormat;
1167 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001168 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001169 }
1170
Lajos Molnar47118272019-01-31 16:28:04 -08001171 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001172 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1173 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1174 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001175
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001176 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001177 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1178 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001179 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001180 inputSurface));
1181 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001182 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001183 int32_t width = 0;
1184 (void)outputFormat->findInt32("width", &width);
1185 int32_t height = 0;
1186 (void)outputFormat->findInt32("height", &height);
1187 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001188 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001189 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001190 } else {
1191 ALOGE("Corrupted input surface");
1192 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1193 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001194 }
1195
1196 if (err != OK) {
1197 ALOGE("Failed to set up input surface: %d", err);
1198 mCallback->onInputSurfaceCreationFailed(err);
1199 return;
1200 }
1201
1202 mCallback->onInputSurfaceCreated(
1203 inputFormat,
1204 outputFormat,
1205 new BufferProducerWrapper(bufferProducer));
1206}
1207
1208status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001209 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1210 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001211 config->mUsingSurface = true;
1212
1213 // we are now using surface - apply default color aspects to input format - as well as
1214 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001215 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001216 ALOGD("input format %s to %s",
1217 inputFormatChanged ? "changed" : "unchanged",
1218 config->mInputFormat->debugString().c_str());
1219
1220 // configure dataspace
1221 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1222 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1223 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1224 surface->setDataSpace(dataSpace);
1225
1226 status_t err = mChannel->setInputSurface(surface);
1227 if (err != OK) {
1228 // undo input format update
1229 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001230 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001231 return err;
1232 }
1233 config->mInputSurface = surface;
1234
1235 if (config->mISConfig) {
1236 surface->configure(*config->mISConfig);
1237 } else {
1238 ALOGD("ISConfig: no configuration");
1239 }
1240
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001241 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001242}
1243
1244void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1245 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1246 msg->setObject("surface", surface);
1247 msg->post();
1248}
1249
1250void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1251 sp<AMessage> inputFormat;
1252 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001253 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001254 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001255 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1256 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001257 inputFormat = config->mInputFormat;
1258 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001259 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001260 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001261 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1262 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1263 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1264 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001265 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1266 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1267 if (err != OK) {
1268 ALOGE("Failed to set up input surface: %d", err);
1269 mCallback->onInputSurfaceDeclined(err);
1270 return;
1271 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001272 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001273 int32_t width = 0;
1274 (void)outputFormat->findInt32("width", &width);
1275 int32_t height = 0;
1276 (void)outputFormat->findInt32("height", &height);
1277 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001278 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001279 if (err != OK) {
1280 ALOGE("Failed to set up input surface: %d", err);
1281 mCallback->onInputSurfaceDeclined(err);
1282 return;
1283 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001284 } else {
1285 ALOGE("Failed to set input surface: Corrupted surface.");
1286 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1287 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001288 }
1289 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1290}
1291
1292void CCodec::initiateStart() {
1293 auto setStarting = [this] {
1294 Mutexed<State>::Locked state(mState);
1295 if (state->get() != ALLOCATED) {
1296 return UNKNOWN_ERROR;
1297 }
1298 state->set(STARTING);
1299 return OK;
1300 };
1301 if (tryAndReportOnError(setStarting) != OK) {
1302 return;
1303 }
1304
1305 (new AMessage(kWhatStart, this))->post();
1306}
1307
1308void CCodec::start() {
1309 std::shared_ptr<Codec2Client::Component> comp;
1310 auto checkStarting = [this, &comp] {
1311 Mutexed<State>::Locked state(mState);
1312 if (state->get() != STARTING) {
1313 return UNKNOWN_ERROR;
1314 }
1315 comp = state->comp;
1316 return OK;
1317 };
1318 if (tryAndReportOnError(checkStarting) != OK) {
1319 return;
1320 }
1321
1322 c2_status_t err = comp->start();
1323 if (err != C2_OK) {
1324 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1325 ACTION_CODE_FATAL);
1326 return;
1327 }
1328 sp<AMessage> inputFormat;
1329 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001330 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001331 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001332 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001333 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1334 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001335 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001336 // start triggers format dup
1337 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001338 if (config->mInputSurface) {
1339 err2 = config->mInputSurface->start();
1340 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001341 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001342 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001343 if (err2 != OK) {
1344 mCallback->onError(err2, ACTION_CODE_FATAL);
1345 return;
1346 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001347 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001348 if (err2 != OK) {
1349 mCallback->onError(err2, ACTION_CODE_FATAL);
1350 return;
1351 }
1352
1353 auto setRunning = [this] {
1354 Mutexed<State>::Locked state(mState);
1355 if (state->get() != STARTING) {
1356 return UNKNOWN_ERROR;
1357 }
1358 state->set(RUNNING);
1359 return OK;
1360 };
1361 if (tryAndReportOnError(setRunning) != OK) {
1362 return;
1363 }
1364 mCallback->onStartCompleted();
1365
1366 (void)mChannel->requestInitialInputBuffers();
1367}
1368
1369void CCodec::initiateShutdown(bool keepComponentAllocated) {
1370 if (keepComponentAllocated) {
1371 initiateStop();
1372 } else {
1373 initiateRelease();
1374 }
1375}
1376
1377void CCodec::initiateStop() {
1378 {
1379 Mutexed<State>::Locked state(mState);
1380 if (state->get() == ALLOCATED
1381 || state->get() == RELEASED
1382 || state->get() == STOPPING
1383 || state->get() == RELEASING) {
1384 // We're already stopped, released, or doing it right now.
1385 state.unlock();
1386 mCallback->onStopCompleted();
1387 state.lock();
1388 return;
1389 }
1390 state->set(STOPPING);
1391 }
1392
Wonsik Kim936a89c2020-05-08 16:07:50 -07001393 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 (new AMessage(kWhatStop, this))->post();
1395}
1396
1397void CCodec::stop() {
1398 std::shared_ptr<Codec2Client::Component> comp;
1399 {
1400 Mutexed<State>::Locked state(mState);
1401 if (state->get() == RELEASING) {
1402 state.unlock();
1403 // We're already stopped or release is in progress.
1404 mCallback->onStopCompleted();
1405 state.lock();
1406 return;
1407 } else if (state->get() != STOPPING) {
1408 state.unlock();
1409 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1410 state.lock();
1411 return;
1412 }
1413 comp = state->comp;
1414 }
1415 status_t err = comp->stop();
1416 if (err != C2_OK) {
1417 // TODO: convert err into status_t
1418 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1419 }
1420
1421 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001422 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1423 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001424 if (config->mInputSurface) {
1425 config->mInputSurface->disconnect();
1426 config->mInputSurface = nullptr;
1427 }
1428 }
1429 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001430 Mutexed<State>::Locked state(mState);
1431 if (state->get() == STOPPING) {
1432 state->set(ALLOCATED);
1433 }
1434 }
1435 mCallback->onStopCompleted();
1436}
1437
1438void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001439 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001440 {
1441 Mutexed<State>::Locked state(mState);
1442 if (state->get() == RELEASED || state->get() == RELEASING) {
1443 // We're already released or doing it right now.
1444 if (sendCallback) {
1445 state.unlock();
1446 mCallback->onReleaseCompleted();
1447 state.lock();
1448 }
1449 return;
1450 }
1451 if (state->get() == ALLOCATING) {
1452 state->set(RELEASING);
1453 // With the altered state allocate() would fail and clean up.
1454 if (sendCallback) {
1455 state.unlock();
1456 mCallback->onReleaseCompleted();
1457 state.lock();
1458 }
1459 return;
1460 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001461 if (state->get() == STARTING
1462 || state->get() == RUNNING
1463 || state->get() == STOPPING) {
1464 // Input surface may have been started, so clean up is needed.
1465 clearInputSurfaceIfNeeded = true;
1466 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001467 state->set(RELEASING);
1468 }
1469
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001470 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001471 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1472 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001473 if (config->mInputSurface) {
1474 config->mInputSurface->disconnect();
1475 config->mInputSurface = nullptr;
1476 }
1477 }
1478
Wonsik Kim936a89c2020-05-08 16:07:50 -07001479 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001480 // thiz holds strong ref to this while the thread is running.
1481 sp<CCodec> thiz(this);
1482 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1483}
1484
1485void CCodec::release(bool sendCallback) {
1486 std::shared_ptr<Codec2Client::Component> comp;
1487 {
1488 Mutexed<State>::Locked state(mState);
1489 if (state->get() == RELEASED) {
1490 if (sendCallback) {
1491 state.unlock();
1492 mCallback->onReleaseCompleted();
1493 state.lock();
1494 }
1495 return;
1496 }
1497 comp = state->comp;
1498 }
1499 comp->release();
1500
1501 {
1502 Mutexed<State>::Locked state(mState);
1503 state->set(RELEASED);
1504 state->comp.reset();
1505 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001506 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001507 if (sendCallback) {
1508 mCallback->onReleaseCompleted();
1509 }
1510}
1511
1512status_t CCodec::setSurface(const sp<Surface> &surface) {
1513 return mChannel->setSurface(surface);
1514}
1515
1516void CCodec::signalFlush() {
1517 status_t err = [this] {
1518 Mutexed<State>::Locked state(mState);
1519 if (state->get() == FLUSHED) {
1520 return ALREADY_EXISTS;
1521 }
1522 if (state->get() != RUNNING) {
1523 return UNKNOWN_ERROR;
1524 }
1525 state->set(FLUSHING);
1526 return OK;
1527 }();
1528 switch (err) {
1529 case ALREADY_EXISTS:
1530 mCallback->onFlushCompleted();
1531 return;
1532 case OK:
1533 break;
1534 default:
1535 mCallback->onError(err, ACTION_CODE_FATAL);
1536 return;
1537 }
1538
1539 mChannel->stop();
1540 (new AMessage(kWhatFlush, this))->post();
1541}
1542
1543void CCodec::flush() {
1544 std::shared_ptr<Codec2Client::Component> comp;
1545 auto checkFlushing = [this, &comp] {
1546 Mutexed<State>::Locked state(mState);
1547 if (state->get() != FLUSHING) {
1548 return UNKNOWN_ERROR;
1549 }
1550 comp = state->comp;
1551 return OK;
1552 };
1553 if (tryAndReportOnError(checkFlushing) != OK) {
1554 return;
1555 }
1556
1557 std::list<std::unique_ptr<C2Work>> flushedWork;
1558 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1559 {
1560 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1561 flushedWork.splice(flushedWork.end(), *queue);
1562 }
1563 if (err != C2_OK) {
1564 // TODO: convert err into status_t
1565 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1566 }
1567
1568 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001569
1570 {
1571 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001572 if (state->get() == FLUSHING) {
1573 state->set(FLUSHED);
1574 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001575 }
1576 mCallback->onFlushCompleted();
1577}
1578
1579void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001580 std::shared_ptr<Codec2Client::Component> comp;
1581 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001582 Mutexed<State>::Locked state(mState);
1583 if (state->get() != FLUSHED) {
1584 return UNKNOWN_ERROR;
1585 }
1586 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001587 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001588 return OK;
1589 };
1590 if (tryAndReportOnError(setResuming) != OK) {
1591 return;
1592 }
1593
Wonsik Kime75a5da2020-02-14 17:29:03 -08001594 {
1595 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1596 const std::unique_ptr<Config> &config = *configLocked;
1597 config->queryConfiguration(comp);
1598 }
1599
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001600 (void)mChannel->start(nullptr, nullptr, [&]{
1601 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1602 const std::unique_ptr<Config> &config = *configLocked;
1603 return config->mBuffersBoundToCodec;
1604 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001605
1606 {
1607 Mutexed<State>::Locked state(mState);
1608 if (state->get() != RESUMING) {
1609 state.unlock();
1610 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1611 state.lock();
1612 return;
1613 }
1614 state->set(RUNNING);
1615 }
1616
1617 (void)mChannel->requestInitialInputBuffers();
1618}
1619
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001620void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001621 std::shared_ptr<Codec2Client::Component> comp;
1622 auto checkState = [this, &comp] {
1623 Mutexed<State>::Locked state(mState);
1624 if (state->get() == RELEASED) {
1625 return INVALID_OPERATION;
1626 }
1627 comp = state->comp;
1628 return OK;
1629 };
1630 if (tryAndReportOnError(checkState) != OK) {
1631 return;
1632 }
1633
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001634 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1635 // the behavior here.
1636 sp<AMessage> params = msg;
1637 int32_t bitrate;
1638 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1639 params = msg->dup();
1640 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1641 }
1642
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001643 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1644 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001645
1646 /**
1647 * Handle input surface parameters
1648 */
1649 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001650 && (config->mDomain & Config::IS_ENCODER)
1651 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001652 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001653
1654 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1655 config->mISConfig->mStopped = false;
1656 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1657 config->mISConfig->mStopped = true;
1658 }
1659
1660 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001661 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001662 config->mISConfig->mSuspended = value;
1663 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001664 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001665 }
1666
1667 (void)config->mInputSurface->configure(*config->mISConfig);
1668 if (config->mISConfig->mStopped) {
1669 config->mInputFormat->setInt64(
1670 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1671 }
1672 }
1673
1674 std::vector<std::unique_ptr<C2Param>> configUpdate;
1675 (void)config->getConfigUpdateFromSdkParams(
1676 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1677 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1678 // Parameter synchronization is not defined when using input surface. For now, route
1679 // these directly to the component.
1680 if (config->mInputSurface == nullptr
1681 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1682 || comp->getName().find("c2.android.") == 0)) {
1683 mChannel->setParameters(configUpdate);
1684 } else {
1685 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1686 }
1687}
1688
1689void CCodec::signalEndOfInputStream() {
1690 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1691}
1692
1693void CCodec::signalRequestIDRFrame() {
1694 std::shared_ptr<Codec2Client::Component> comp;
1695 {
1696 Mutexed<State>::Locked state(mState);
1697 if (state->get() == RELEASED) {
1698 ALOGD("no IDR request sent since component is released");
1699 return;
1700 }
1701 comp = state->comp;
1702 }
1703 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001704 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1705 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001706 std::vector<std::unique_ptr<C2Param>> params;
1707 params.push_back(
1708 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1709 config->setParameters(comp, params, C2_MAY_BLOCK);
1710}
1711
Wonsik Kimab34ed62019-01-31 15:28:46 -08001712void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001713 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001714 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1715 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001716 }
1717 (new AMessage(kWhatWorkDone, this))->post();
1718}
1719
Wonsik Kimab34ed62019-01-31 15:28:46 -08001720void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1721 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001722 if (arrayIndex == 0) {
1723 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001724 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1725 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001726 if (config->mInputSurface) {
1727 config->mInputSurface->onInputBufferDone(frameIndex);
1728 }
1729 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001730}
1731
1732void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1733 TimePoint now = std::chrono::steady_clock::now();
1734 CCodecWatchdog::getInstance()->watch(this);
1735 switch (msg->what()) {
1736 case kWhatAllocate: {
1737 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001738 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001739 sp<RefBase> obj;
1740 CHECK(msg->findObject("codecInfo", &obj));
1741 allocate((MediaCodecInfo *)obj.get());
1742 break;
1743 }
1744 case kWhatConfigure: {
1745 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001746 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001747 sp<AMessage> format;
1748 CHECK(msg->findMessage("format", &format));
1749 configure(format);
1750 break;
1751 }
1752 case kWhatStart: {
1753 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001754 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001755 start();
1756 break;
1757 }
1758 case kWhatStop: {
1759 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001760 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001761 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001762 break;
1763 }
1764 case kWhatFlush: {
1765 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001766 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001767 flush();
1768 break;
1769 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001770 case kWhatRelease: {
1771 mChannel->release();
1772 mClient.reset();
1773 mClientListener.reset();
1774 break;
1775 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001776 case kWhatCreateInputSurface: {
1777 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001778 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001779 createInputSurface();
1780 break;
1781 }
1782 case kWhatSetInputSurface: {
1783 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001784 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001785 sp<RefBase> obj;
1786 CHECK(msg->findObject("surface", &obj));
1787 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1788 setInputSurface(surface);
1789 break;
1790 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001791 case kWhatWorkDone: {
1792 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001793 bool shouldPost = false;
1794 {
1795 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1796 if (queue->empty()) {
1797 break;
1798 }
1799 work.swap(queue->front());
1800 queue->pop_front();
1801 shouldPost = !queue->empty();
1802 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001803 if (shouldPost) {
1804 (new AMessage(kWhatWorkDone, this))->post();
1805 }
1806
Pawin Vongmasa36653902018-11-15 00:10:25 -08001807 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001808 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1809 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8ec93ab2020-11-13 16:17:04 -08001810 bool changed = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001811 Config::Watcher<C2StreamInitDataInfo::output> initData =
1812 config->watch<C2StreamInitDataInfo::output>();
1813 if (!work->worklets.empty()
1814 && (work->worklets.front()->output.flags
1815 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1816
1817 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001818 std::vector<std::unique_ptr<C2Param>> updates;
1819 for (const std::unique_ptr<C2Param> &param
1820 : work->worklets.front()->output.configUpdate) {
1821 updates.push_back(C2Param::Copy(*param));
1822 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001823 unsigned stream = 0;
1824 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1825 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1826 // move all info into output-stream #0 domain
1827 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1828 }
George Burgess IVc813a592020-02-22 22:54:44 -08001829
1830 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
1831 // for now only do the first block
1832 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001833 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1834 // block.crop().left, block.crop().top,
1835 // block.crop().width, block.crop().height,
1836 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08001837 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08001838 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1839 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07001840 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001841 }
1842 ++stream;
1843 }
1844
Wonsik Kim8ec93ab2020-11-13 16:17:04 -08001845 if (config->updateConfiguration(updates, config->mOutputDomain)) {
1846 changed = true;
1847 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001848
1849 // copy standard infos to graphic buffers if not already present (otherwise, we
1850 // may overwrite the actual intermediate value with a final value)
1851 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07001852 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001853 C2StreamRotationInfo::output::PARAM_TYPE,
1854 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1855 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1856 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001857 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001858 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1859 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1860 };
1861 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1862 if (buf->data().graphicBlocks().size()) {
1863 for (C2Param::Index ix : stdGfxInfos) {
1864 if (!buf->hasInfo(ix)) {
1865 const C2Param *param =
1866 config->getConfigParameterValue(ix.withStream(stream));
1867 if (param) {
1868 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1869 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1870 }
1871 }
1872 }
1873 }
1874 ++stream;
1875 }
1876 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001877 if (config->mInputSurface) {
1878 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
1879 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001880 mChannel->onWorkDone(
Wonsik Kim8ec93ab2020-11-13 16:17:04 -08001881 std::move(work), changed ? config->mOutputFormat->dup() : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001882 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001883 break;
1884 }
1885 case kWhatWatch: {
1886 // watch message already posted; no-op.
1887 break;
1888 }
1889 default: {
1890 ALOGE("unrecognized message");
1891 break;
1892 }
1893 }
1894 setDeadline(TimePoint::max(), 0ms, "none");
1895}
1896
1897void CCodec::setDeadline(
1898 const TimePoint &now,
1899 const std::chrono::milliseconds &timeout,
1900 const char *name) {
1901 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1902 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1903 deadline->set(now + (timeout * mult), name);
1904}
1905
1906void CCodec::initiateReleaseIfStuck() {
1907 std::string name;
1908 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001909 {
1910 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001911 if (deadline->get() < std::chrono::steady_clock::now()) {
1912 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001913 }
1914 if (deadline->get() != TimePoint::max()) {
1915 pendingDeadline = true;
1916 }
1917 }
1918 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001919 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1920 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1921 if (elapsed >= kWorkDurationThreshold) {
1922 name = "queue";
1923 }
1924 if (elapsed > 0s) {
1925 pendingDeadline = true;
1926 }
1927 }
1928 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001929 // We're not stuck.
1930 if (pendingDeadline) {
1931 // If we are not stuck yet but still has deadline coming up,
1932 // post watch message to check back later.
1933 (new AMessage(kWhatWatch, this))->post();
1934 }
1935 return;
1936 }
1937
1938 ALOGW("previous call to %s exceeded timeout", name.c_str());
1939 initiateRelease(false);
1940 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1941}
1942
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001943// static
1944PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07001945 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001946 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001947 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07001948 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1949 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001950 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07001951 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
1952 sp<IGraphicBufferProducer> gbp;
1953 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
1954 status_t err = gbs->initCheck();
1955 if (err != OK) {
1956 ALOGE("Failed to create persistent input surface: error %d", err);
1957 return nullptr;
1958 }
1959 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001960 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07001961 } else {
1962 return nullptr;
1963 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001964 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07001965 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001966 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07001967 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08001968 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001969}
1970
Wonsik Kimffb889a2020-05-28 11:32:25 -07001971class IntfCache {
1972public:
1973 IntfCache() = default;
1974
1975 status_t init(const std::string &name) {
1976 std::shared_ptr<Codec2Client::Interface> intf{
1977 Codec2Client::CreateInterfaceByName(name.c_str())};
1978 if (!intf) {
1979 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
1980 mInitStatus = NO_INIT;
1981 return NO_INIT;
1982 }
1983 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
1984 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
1985 C2ParamField{&sUsage, &sUsage.value}));
1986 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
1987 if (err != C2_OK) {
1988 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
1989 name.c_str(), err);
1990 mFields[0].status = err;
1991 }
1992 std::vector<std::unique_ptr<C2Param>> params;
1993 err = intf->query(
1994 {&mApiFeatures},
1995 {C2PortAllocatorsTuning::input::PARAM_TYPE},
1996 C2_MAY_BLOCK,
1997 &params);
1998 if (err != C2_OK && err != C2_BAD_INDEX) {
1999 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2000 name.c_str(), err);
2001 }
2002 while (!params.empty()) {
2003 C2Param *param = params.back().release();
2004 params.pop_back();
2005 if (!param) {
2006 continue;
2007 }
2008 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2009 mInputAllocators.reset(
2010 C2PortAllocatorsTuning::input::From(params[0].get()));
2011 }
2012 }
2013 mInitStatus = OK;
2014 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002015 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002016
2017 status_t initCheck() const { return mInitStatus; }
2018
2019 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2020 CHECK_EQ(1u, mFields.size());
2021 return mFields[0];
2022 }
2023
2024 const C2ApiFeaturesSetting &getApiFeatures() const {
2025 return mApiFeatures;
2026 }
2027
2028 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2029 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2030 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2031 C2PortAllocatorsTuning::input::AllocUnique(0);
2032 param->invalidate();
2033 return param;
2034 }();
2035 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2036 }
2037
2038private:
2039 status_t mInitStatus{NO_INIT};
2040
2041 std::vector<C2FieldSupportedValuesQuery> mFields;
2042 C2ApiFeaturesSetting mApiFeatures;
2043 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2044};
2045
2046static const IntfCache &GetIntfCache(const std::string &name) {
2047 static IntfCache sNullIntfCache;
2048 static std::mutex sMutex;
2049 static std::map<std::string, IntfCache> sCache;
2050 std::unique_lock<std::mutex> lock{sMutex};
2051 auto it = sCache.find(name);
2052 if (it == sCache.end()) {
2053 lock.unlock();
2054 IntfCache intfCache;
2055 status_t err = intfCache.init(name);
2056 if (err != OK) {
2057 return sNullIntfCache;
2058 }
2059 lock.lock();
2060 it = sCache.insert({name, std::move(intfCache)}).first;
2061 }
2062 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002063}
2064
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002065static status_t GetCommonAllocatorIds(
2066 const std::vector<std::string> &names,
2067 C2Allocator::type_t type,
2068 std::set<C2Allocator::id_t> *ids) {
2069 int poolMask = GetCodec2PoolMask();
2070 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2071 C2Allocator::id_t defaultAllocatorId =
2072 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2073
2074 ids->clear();
2075 if (names.empty()) {
2076 return OK;
2077 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002078 bool firstIteration = true;
2079 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002080 const IntfCache &intfCache = GetIntfCache(name);
2081 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002082 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002083 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002084 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002085 if (firstIteration) {
2086 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002087 if (allocators && allocators.flexCount() > 0) {
2088 ids->insert(allocators.m.values,
2089 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002090 }
2091 if (ids->empty()) {
2092 // The component does not advertise allocators. Use default.
2093 ids->insert(defaultAllocatorId);
2094 }
2095 continue;
2096 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002097 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002098 if (allocators && allocators.flexCount() > 0) {
2099 filtered = true;
2100 for (auto it = ids->begin(); it != ids->end(); ) {
2101 bool found = false;
2102 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2103 if (allocators.m.values[j] == *it) {
2104 found = true;
2105 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002106 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002107 }
2108 if (found) {
2109 ++it;
2110 } else {
2111 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002112 }
2113 }
2114 }
2115 if (!filtered) {
2116 // The component does not advertise supported allocators. Use default.
2117 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2118 if (ids->size() != (containsDefault ? 1 : 0)) {
2119 ids->clear();
2120 if (containsDefault) {
2121 ids->insert(defaultAllocatorId);
2122 }
2123 }
2124 }
2125 }
2126 // Finally, filter with pool masks
2127 for (auto it = ids->begin(); it != ids->end(); ) {
2128 if ((poolMask >> *it) & 1) {
2129 ++it;
2130 } else {
2131 it = ids->erase(it);
2132 }
2133 }
2134 return OK;
2135}
2136
2137static status_t CalculateMinMaxUsage(
2138 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2139 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2140 *minUsage = 0;
2141 *maxUsage = ~0ull;
2142 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002143 const IntfCache &intfCache = GetIntfCache(name);
2144 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002145 continue;
2146 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002147 const C2FieldSupportedValuesQuery &usageSupportedValues =
2148 intfCache.getUsageSupportedValues();
2149 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002150 continue;
2151 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002152 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002153 if (supported.type != C2FieldSupportedValues::FLAGS) {
2154 continue;
2155 }
2156 if (supported.values.empty()) {
2157 *maxUsage = 0;
2158 continue;
2159 }
2160 *minUsage |= supported.values[0].u64;
2161 int64_t currentMaxUsage = 0;
2162 for (const C2Value::Primitive &flags : supported.values) {
2163 currentMaxUsage |= flags.u64;
2164 }
2165 *maxUsage &= currentMaxUsage;
2166 }
2167 return OK;
2168}
2169
2170// static
2171status_t CCodec::CanFetchLinearBlock(
2172 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002173 for (const std::string &name : names) {
2174 const IntfCache &intfCache = GetIntfCache(name);
2175 if (intfCache.initCheck() != OK) {
2176 continue;
2177 }
2178 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2179 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2180 *isCompatible = false;
2181 return OK;
2182 }
2183 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002184 std::set<C2Allocator::id_t> allocators;
2185 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2186 if (allocators.empty()) {
2187 *isCompatible = false;
2188 return OK;
2189 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002190
2191 uint64_t minUsage = 0;
2192 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002193 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002194 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002195 *isCompatible = ((maxUsage & minUsage) == minUsage);
2196 return OK;
2197}
2198
2199static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2200 static std::mutex sMutex{};
2201 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2202 std::unique_lock<std::mutex> lock{sMutex};
2203 std::shared_ptr<C2BlockPool> pool;
2204 auto it = sPools.find(allocId);
2205 if (it == sPools.end()) {
2206 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2207 if (err == OK) {
2208 sPools.emplace(allocId, pool);
2209 } else {
2210 pool.reset();
2211 }
2212 } else {
2213 pool = it->second;
2214 }
2215 return pool;
2216}
2217
2218// static
2219std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2220 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002221 std::set<C2Allocator::id_t> allocators;
2222 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2223 if (allocators.empty()) {
2224 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2225 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002226
2227 uint64_t minUsage = 0;
2228 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002229 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002230 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002231 if ((maxUsage & minUsage) != minUsage) {
2232 allocators.clear();
2233 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2234 }
2235 std::shared_ptr<C2LinearBlock> block;
2236 for (C2Allocator::id_t allocId : allocators) {
2237 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2238 if (!pool) {
2239 continue;
2240 }
2241 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2242 if (err != C2_OK || !block) {
2243 block.reset();
2244 continue;
2245 }
2246 break;
2247 }
2248 return block;
2249}
2250
2251// static
2252status_t CCodec::CanFetchGraphicBlock(
2253 const std::vector<std::string> &names, bool *isCompatible) {
2254 uint64_t minUsage = 0;
2255 uint64_t maxUsage = ~0ull;
2256 std::set<C2Allocator::id_t> allocators;
2257 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2258 if (allocators.empty()) {
2259 *isCompatible = false;
2260 return OK;
2261 }
2262 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2263 *isCompatible = ((maxUsage & minUsage) == minUsage);
2264 return OK;
2265}
2266
2267// static
2268std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2269 int32_t width,
2270 int32_t height,
2271 int32_t format,
2272 uint64_t usage,
2273 const std::vector<std::string> &names) {
2274 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2275 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2276 ALOGD("Unrecognized pixel format: %d", format);
2277 return nullptr;
2278 }
2279 uint64_t minUsage = 0;
2280 uint64_t maxUsage = ~0ull;
2281 std::set<C2Allocator::id_t> allocators;
2282 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2283 if (allocators.empty()) {
2284 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2285 }
2286 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2287 minUsage |= usage;
2288 if ((maxUsage & minUsage) != minUsage) {
2289 allocators.clear();
2290 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2291 }
2292 std::shared_ptr<C2GraphicBlock> block;
2293 for (C2Allocator::id_t allocId : allocators) {
2294 std::shared_ptr<C2BlockPool> pool;
2295 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2296 if (err != C2_OK || !pool) {
2297 continue;
2298 }
2299 err = pool->fetchGraphicBlock(
2300 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2301 if (err != C2_OK || !block) {
2302 block.reset();
2303 continue;
2304 }
2305 break;
2306 }
2307 return block;
2308}
2309
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002310} // namespace android
2311