blob: 57252b28a0ddca25f3b45367d7c08e85b874c053 [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
648 std::shared_ptr<Codec2Client::Component> comp =
649 Codec2Client::CreateComponentByName(
650 componentName.c_str(),
651 mClientListener,
652 &client);
653 if (!comp) {
654 ALOGE("Failed Create component: %s", componentName.c_str());
655 Mutexed<State>::Locked state(mState);
656 state->set(RELEASED);
657 state.unlock();
658 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
659 state.lock();
660 return;
661 }
662 ALOGI("Created component [%s]", componentName.c_str());
663 mChannel->setComponent(comp);
664 auto setAllocated = [this, comp, client] {
665 Mutexed<State>::Locked state(mState);
666 if (state->get() != ALLOCATING) {
667 state->set(RELEASED);
668 return UNKNOWN_ERROR;
669 }
670 state->set(ALLOCATED);
671 state->comp = comp;
672 mClient = client;
673 return OK;
674 };
675 if (tryAndReportOnError(setAllocated) != OK) {
676 return;
677 }
678
679 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700680 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
681 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800682 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800683 if (err != OK) {
684 ALOGW("Failed to initialize configuration support");
685 // TODO: report error once we complete implementation.
686 }
687 config->queryConfiguration(comp);
688
689 mCallback->onComponentAllocated(componentName.c_str());
690}
691
692void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
693 auto checkAllocated = [this] {
694 Mutexed<State>::Locked state(mState);
695 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
696 };
697 if (tryAndReportOnError(checkAllocated) != OK) {
698 return;
699 }
700
701 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
702 msg->setMessage("format", format);
703 msg->post();
704}
705
706void CCodec::configure(const sp<AMessage> &msg) {
707 std::shared_ptr<Codec2Client::Component> comp;
708 auto checkAllocated = [this, &comp] {
709 Mutexed<State>::Locked state(mState);
710 if (state->get() != ALLOCATED) {
711 state->set(RELEASED);
712 return UNKNOWN_ERROR;
713 }
714 comp = state->comp;
715 return OK;
716 };
717 if (tryAndReportOnError(checkAllocated) != OK) {
718 return;
719 }
720
721 auto doConfig = [msg, comp, this]() -> status_t {
722 AString mime;
723 if (!msg->findString("mime", &mime)) {
724 return BAD_VALUE;
725 }
726
727 int32_t encoder;
728 if (!msg->findInt32("encoder", &encoder)) {
729 encoder = false;
730 }
731
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800732 int32_t flags;
733 if (!msg->findInt32("flags", &flags)) {
734 return BAD_VALUE;
735 }
736
Pawin Vongmasa36653902018-11-15 00:10:25 -0800737 // TODO: read from intf()
738 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
739 return UNKNOWN_ERROR;
740 }
741
742 int32_t storeMeta;
743 if (encoder
744 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
745 && storeMeta != kMetadataBufferTypeInvalid) {
746 if (storeMeta != kMetadataBufferTypeANWBuffer) {
747 ALOGD("Only ANW buffers are supported for legacy metadata mode");
748 return BAD_VALUE;
749 }
750 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
751 }
752
753 sp<RefBase> obj;
754 sp<Surface> surface;
755 if (msg->findObject("native-window", &obj)) {
756 surface = static_cast<Surface *>(obj.get());
757 setSurface(surface);
758 }
759
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700760 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
761 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800762 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800763 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
764 ALOGD("[%s] buffers are %sbound to CCodec for this session",
765 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800766
Wonsik Kim1114eea2019-02-25 14:35:24 -0800767 // Enforce required parameters
768 int32_t i32;
769 float flt;
770 if (config->mDomain & Config::IS_AUDIO) {
771 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
772 ALOGD("sample rate is missing, which is required for audio components.");
773 return BAD_VALUE;
774 }
775 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
776 ALOGD("channel count is missing, which is required for audio components.");
777 return BAD_VALUE;
778 }
779 if ((config->mDomain & Config::IS_ENCODER)
780 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
781 && !msg->findInt32(KEY_BIT_RATE, &i32)
782 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
783 ALOGD("bitrate is missing, which is required for audio encoders.");
784 return BAD_VALUE;
785 }
786 }
787 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
788 if (!msg->findInt32(KEY_WIDTH, &i32)) {
789 ALOGD("width is missing, which is required for image/video components.");
790 return BAD_VALUE;
791 }
792 if (!msg->findInt32(KEY_HEIGHT, &i32)) {
793 ALOGD("height is missing, which is required for image/video components.");
794 return BAD_VALUE;
795 }
796 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700797 int32_t mode = BITRATE_MODE_VBR;
798 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700799 if (!msg->findInt32(KEY_QUALITY, &i32)) {
800 ALOGD("quality is missing, which is required for video encoders in CQ.");
801 return BAD_VALUE;
802 }
803 } else {
804 if (!msg->findInt32(KEY_BIT_RATE, &i32)
805 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
806 ALOGD("bitrate is missing, which is required for video encoders.");
807 return BAD_VALUE;
808 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800809 }
810 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
811 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
812 ALOGD("I frame interval is missing, which is required for video encoders.");
813 return BAD_VALUE;
814 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700815 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
816 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
817 ALOGD("frame rate is missing, which is required for video encoders.");
818 return BAD_VALUE;
819 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800820 }
821 }
822
Pawin Vongmasa36653902018-11-15 00:10:25 -0800823 /*
824 * Handle input surface configuration
825 */
826 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
827 && (config->mDomain & Config::IS_ENCODER)) {
828 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
829 {
830 config->mISConfig->mMinFps = 0;
831 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800832 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800833 config->mISConfig->mMinFps = 1e6 / value;
834 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700835 if (!msg->findFloat(
836 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
837 config->mISConfig->mMaxFps = -1;
838 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800839 config->mISConfig->mMinAdjustedFps = 0;
840 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800841 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800842 if (value < 0 && value >= INT32_MIN) {
843 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700844 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800845 } else if (value > 0 && value <= INT32_MAX) {
846 config->mISConfig->mMinAdjustedFps = 1e6 / value;
847 }
848 }
849 }
850
851 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700852 bool captureFpsFound = false;
853 double timeLapseFps;
854 float captureRate;
855 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
856 config->mISConfig->mCaptureFps = timeLapseFps;
857 captureFpsFound = true;
858 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
859 config->mISConfig->mCaptureFps = captureRate;
860 captureFpsFound = true;
861 }
862 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800863 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
864 }
865 }
866
867 {
868 config->mISConfig->mSuspended = false;
869 config->mISConfig->mSuspendAtUs = -1;
870 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800871 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800872 config->mISConfig->mSuspended = true;
873 }
874 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700875 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800876 }
877
878 /*
879 * Handle desired color format.
880 */
881 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
882 int32_t format = -1;
883 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
884 /*
885 * Also handle default color format (encoders require color format, so this is only
886 * needed for decoders.
887 */
888 if (!(config->mDomain & Config::IS_ENCODER)) {
889 format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
890 }
891 }
892
893 if (format >= 0) {
894 msg->setInt32("android._color-format", format);
895 }
896 }
897
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800898 int32_t subscribeToAllVendorParams;
899 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
900 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
901 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
902 }
903 }
904
Pawin Vongmasa36653902018-11-15 00:10:25 -0800905 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800906 // NOTE: We used to ignore "video-bitrate" at configure; replicate
907 // the behavior here.
908 sp<AMessage> sdkParams = msg;
909 int32_t videoBitrate;
910 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
911 sdkParams = msg->dup();
912 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
913 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800914 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800915 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800916 if (err != OK) {
917 ALOGW("failed to convert configuration to c2 params");
918 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700919
920 int32_t maxBframes = 0;
921 if ((config->mDomain & Config::IS_ENCODER)
922 && (config->mDomain & Config::IS_VIDEO)
923 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
924 && maxBframes > 0) {
925 std::unique_ptr<C2StreamGopTuning::output> gop =
926 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
927 gop->m.values[0] = { P_FRAME, UINT32_MAX };
928 gop->m.values[1] = {
929 C2Config::picture_type_t(P_FRAME | B_FRAME),
930 uint32_t(maxBframes)
931 };
932 configUpdate.push_back(std::move(gop));
933 }
934
Pawin Vongmasa36653902018-11-15 00:10:25 -0800935 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
936 if (err != OK) {
937 ALOGW("failed to configure c2 params");
938 return err;
939 }
940
941 std::vector<std::unique_ptr<C2Param>> params;
942 C2StreamUsageTuning::input usage(0u, 0u);
943 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700944 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800945
946 std::initializer_list<C2Param::Index> indices {
947 };
948 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700949 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -0800950 indices,
951 C2_DONT_BLOCK,
952 &params);
953 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
954 ALOGE("Failed to query component interface: %d", c2err);
955 return UNKNOWN_ERROR;
956 }
957 if (params.size() != indices.size()) {
958 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
959 indices.size(), params.size());
960 return UNKNOWN_ERROR;
961 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700962 if (usage) {
963 if (usage.value & C2MemoryUsage::CPU_READ) {
964 config->mInputFormat->setInt32("using-sw-read-often", true);
965 }
966 if (config->mISConfig) {
967 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
968 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
969 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800970 }
971
972 // NOTE: we don't blindly use client specified input size if specified as clients
973 // at times specify too small size. Instead, mimic the behavior from OMX, where the
974 // client specified size is only used to ask for bigger buffers than component suggested
975 // size.
976 int32_t clientInputSize = 0;
977 bool clientSpecifiedInputSize =
978 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
979 // TEMP: enforce minimum buffer size of 1MB for video decoders
980 // and 16K / 4K for audio encoders/decoders
981 if (maxInputSize.value == 0) {
982 if (config->mDomain & Config::IS_AUDIO) {
983 maxInputSize.value = encoder ? 16384 : 4096;
984 } else if (!encoder) {
985 maxInputSize.value = 1048576u;
986 }
987 }
988
989 // verify that CSD fits into this size (if defined)
990 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
991 sp<ABuffer> csd;
992 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
993 if (csd && csd->size() > maxInputSize.value) {
994 maxInputSize.value = csd->size();
995 }
996 }
997 }
998
999 // TODO: do this based on component requiring linear allocator for input
1000 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1001 if (clientSpecifiedInputSize) {
1002 // Warn that we're overriding client's max input size if necessary.
1003 if ((uint32_t)clientInputSize < maxInputSize.value) {
1004 ALOGD("client requested max input size %d, which is smaller than "
1005 "what component recommended (%u); overriding with component "
1006 "recommendation.", clientInputSize, maxInputSize.value);
1007 ALOGW("This behavior is subject to change. It is recommended that "
1008 "app developers double check whether the requested "
1009 "max input size is in reasonable range.");
1010 } else {
1011 maxInputSize.value = clientInputSize;
1012 }
1013 }
1014 // Pass max input size on input format to the buffer channel (if supplied by the
1015 // component or by a default)
1016 if (maxInputSize.value) {
1017 config->mInputFormat->setInt32(
1018 KEY_MAX_INPUT_SIZE,
1019 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1020 }
1021 }
1022
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001023 int32_t clientPrepend;
1024 if ((config->mDomain & Config::IS_VIDEO)
1025 && (config->mDomain & Config::IS_ENCODER)
1026 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1027 && clientPrepend
1028 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1029 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1030 return BAD_VALUE;
1031 }
1032
Pawin Vongmasa36653902018-11-15 00:10:25 -08001033 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1034 // propagate HDR static info to output format for both encoders and decoders
1035 // if component supports this info, we will update from component, but only the raw port,
1036 // so don't propagate if component already filled it in.
1037 sp<ABuffer> hdrInfo;
1038 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1039 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1040 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1041 }
1042
1043 // Set desired color format from configuration parameter
1044 int32_t format;
1045 if (msg->findInt32("android._color-format", &format)) {
1046 if (config->mDomain & Config::IS_ENCODER) {
1047 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
1048 } else {
1049 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
1050 }
1051 }
1052 }
1053
1054 // propagate encoder delay and padding to output format
1055 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1056 int delay = 0;
1057 if (msg->findInt32("encoder-delay", &delay)) {
1058 config->mOutputFormat->setInt32("encoder-delay", delay);
1059 }
1060 int padding = 0;
1061 if (msg->findInt32("encoder-padding", &padding)) {
1062 config->mOutputFormat->setInt32("encoder-padding", padding);
1063 }
1064 }
1065
1066 // set channel-mask
1067 if (config->mDomain & Config::IS_AUDIO) {
1068 int32_t mask;
1069 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1070 if (config->mDomain & Config::IS_ENCODER) {
1071 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1072 } else {
1073 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1074 }
1075 }
1076 }
1077
1078 ALOGD("setup formats input: %s and output: %s",
1079 config->mInputFormat->debugString().c_str(),
1080 config->mOutputFormat->debugString().c_str());
1081 return OK;
1082 };
1083 if (tryAndReportOnError(doConfig) != OK) {
1084 return;
1085 }
1086
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001087 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1088 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001089
1090 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1091}
1092
1093void CCodec::initiateCreateInputSurface() {
1094 status_t err = [this] {
1095 Mutexed<State>::Locked state(mState);
1096 if (state->get() != ALLOCATED) {
1097 return UNKNOWN_ERROR;
1098 }
1099 // TODO: read it from intf() properly.
1100 if (state->comp->getName().find("encoder") == std::string::npos) {
1101 return INVALID_OPERATION;
1102 }
1103 return OK;
1104 }();
1105 if (err != OK) {
1106 mCallback->onInputSurfaceCreationFailed(err);
1107 return;
1108 }
1109
1110 (new AMessage(kWhatCreateInputSurface, this))->post();
1111}
1112
Lajos Molnar47118272019-01-31 16:28:04 -08001113sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1114 using namespace android::hardware::media::omx::V1_0;
1115 using namespace android::hardware::media::omx::V1_0::utils;
1116 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1117 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1118 android::sp<IOmx> omx = IOmx::getService();
1119 typedef android::hardware::graphics::bufferqueue::V1_0::
1120 IGraphicBufferProducer HGraphicBufferProducer;
1121 typedef android::hardware::media::omx::V1_0::
1122 IGraphicBufferSource HGraphicBufferSource;
1123 OmxStatus s;
1124 android::sp<HGraphicBufferProducer> gbp;
1125 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001126
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001127 using ::android::hardware::Return;
1128 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001129 [&s, &gbp, &gbs](
1130 OmxStatus status,
1131 const android::sp<HGraphicBufferProducer>& producer,
1132 const android::sp<HGraphicBufferSource>& source) {
1133 s = status;
1134 gbp = producer;
1135 gbs = source;
1136 });
1137 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001138 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001139 }
1140
1141 return nullptr;
1142}
1143
1144sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1145 sp<PersistentSurface> surface(CreateInputSurface());
1146
1147 if (surface == nullptr) {
1148 surface = CreateOmxInputSurface();
1149 }
1150
1151 return surface;
1152}
1153
Pawin Vongmasa36653902018-11-15 00:10:25 -08001154void CCodec::createInputSurface() {
1155 status_t err;
1156 sp<IGraphicBufferProducer> bufferProducer;
1157
1158 sp<AMessage> inputFormat;
1159 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001160 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001161 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001162 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1163 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001164 inputFormat = config->mInputFormat;
1165 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001166 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001167 }
1168
Lajos Molnar47118272019-01-31 16:28:04 -08001169 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001170 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1171 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1172 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001173
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001174 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001175 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1176 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001177 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001178 inputSurface));
1179 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001180 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001181 int32_t width = 0;
1182 (void)outputFormat->findInt32("width", &width);
1183 int32_t height = 0;
1184 (void)outputFormat->findInt32("height", &height);
1185 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001186 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001187 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001188 } else {
1189 ALOGE("Corrupted input surface");
1190 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1191 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001192 }
1193
1194 if (err != OK) {
1195 ALOGE("Failed to set up input surface: %d", err);
1196 mCallback->onInputSurfaceCreationFailed(err);
1197 return;
1198 }
1199
1200 mCallback->onInputSurfaceCreated(
1201 inputFormat,
1202 outputFormat,
1203 new BufferProducerWrapper(bufferProducer));
1204}
1205
1206status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001207 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1208 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001209 config->mUsingSurface = true;
1210
1211 // we are now using surface - apply default color aspects to input format - as well as
1212 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001213 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001214 ALOGD("input format %s to %s",
1215 inputFormatChanged ? "changed" : "unchanged",
1216 config->mInputFormat->debugString().c_str());
1217
1218 // configure dataspace
1219 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1220 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1221 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1222 surface->setDataSpace(dataSpace);
1223
1224 status_t err = mChannel->setInputSurface(surface);
1225 if (err != OK) {
1226 // undo input format update
1227 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001228 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001229 return err;
1230 }
1231 config->mInputSurface = surface;
1232
1233 if (config->mISConfig) {
1234 surface->configure(*config->mISConfig);
1235 } else {
1236 ALOGD("ISConfig: no configuration");
1237 }
1238
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001239 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001240}
1241
1242void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1243 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1244 msg->setObject("surface", surface);
1245 msg->post();
1246}
1247
1248void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1249 sp<AMessage> inputFormat;
1250 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001251 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001252 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001253 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1254 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001255 inputFormat = config->mInputFormat;
1256 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001257 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001258 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001259 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1260 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1261 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1262 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001263 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1264 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1265 if (err != OK) {
1266 ALOGE("Failed to set up input surface: %d", err);
1267 mCallback->onInputSurfaceDeclined(err);
1268 return;
1269 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001270 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001271 int32_t width = 0;
1272 (void)outputFormat->findInt32("width", &width);
1273 int32_t height = 0;
1274 (void)outputFormat->findInt32("height", &height);
1275 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001276 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001277 if (err != OK) {
1278 ALOGE("Failed to set up input surface: %d", err);
1279 mCallback->onInputSurfaceDeclined(err);
1280 return;
1281 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001282 } else {
1283 ALOGE("Failed to set input surface: Corrupted surface.");
1284 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1285 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001286 }
1287 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1288}
1289
1290void CCodec::initiateStart() {
1291 auto setStarting = [this] {
1292 Mutexed<State>::Locked state(mState);
1293 if (state->get() != ALLOCATED) {
1294 return UNKNOWN_ERROR;
1295 }
1296 state->set(STARTING);
1297 return OK;
1298 };
1299 if (tryAndReportOnError(setStarting) != OK) {
1300 return;
1301 }
1302
1303 (new AMessage(kWhatStart, this))->post();
1304}
1305
1306void CCodec::start() {
1307 std::shared_ptr<Codec2Client::Component> comp;
1308 auto checkStarting = [this, &comp] {
1309 Mutexed<State>::Locked state(mState);
1310 if (state->get() != STARTING) {
1311 return UNKNOWN_ERROR;
1312 }
1313 comp = state->comp;
1314 return OK;
1315 };
1316 if (tryAndReportOnError(checkStarting) != OK) {
1317 return;
1318 }
1319
1320 c2_status_t err = comp->start();
1321 if (err != C2_OK) {
1322 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1323 ACTION_CODE_FATAL);
1324 return;
1325 }
1326 sp<AMessage> inputFormat;
1327 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001328 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001329 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001330 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001331 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1332 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001333 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001334 // start triggers format dup
1335 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001336 if (config->mInputSurface) {
1337 err2 = config->mInputSurface->start();
1338 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001339 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001340 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001341 if (err2 != OK) {
1342 mCallback->onError(err2, ACTION_CODE_FATAL);
1343 return;
1344 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001345 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001346 if (err2 != OK) {
1347 mCallback->onError(err2, ACTION_CODE_FATAL);
1348 return;
1349 }
1350
1351 auto setRunning = [this] {
1352 Mutexed<State>::Locked state(mState);
1353 if (state->get() != STARTING) {
1354 return UNKNOWN_ERROR;
1355 }
1356 state->set(RUNNING);
1357 return OK;
1358 };
1359 if (tryAndReportOnError(setRunning) != OK) {
1360 return;
1361 }
1362 mCallback->onStartCompleted();
1363
1364 (void)mChannel->requestInitialInputBuffers();
1365}
1366
1367void CCodec::initiateShutdown(bool keepComponentAllocated) {
1368 if (keepComponentAllocated) {
1369 initiateStop();
1370 } else {
1371 initiateRelease();
1372 }
1373}
1374
1375void CCodec::initiateStop() {
1376 {
1377 Mutexed<State>::Locked state(mState);
1378 if (state->get() == ALLOCATED
1379 || state->get() == RELEASED
1380 || state->get() == STOPPING
1381 || state->get() == RELEASING) {
1382 // We're already stopped, released, or doing it right now.
1383 state.unlock();
1384 mCallback->onStopCompleted();
1385 state.lock();
1386 return;
1387 }
1388 state->set(STOPPING);
1389 }
1390
Wonsik Kim936a89c2020-05-08 16:07:50 -07001391 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001392 (new AMessage(kWhatStop, this))->post();
1393}
1394
1395void CCodec::stop() {
1396 std::shared_ptr<Codec2Client::Component> comp;
1397 {
1398 Mutexed<State>::Locked state(mState);
1399 if (state->get() == RELEASING) {
1400 state.unlock();
1401 // We're already stopped or release is in progress.
1402 mCallback->onStopCompleted();
1403 state.lock();
1404 return;
1405 } else if (state->get() != STOPPING) {
1406 state.unlock();
1407 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1408 state.lock();
1409 return;
1410 }
1411 comp = state->comp;
1412 }
1413 status_t err = comp->stop();
1414 if (err != C2_OK) {
1415 // TODO: convert err into status_t
1416 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1417 }
1418
1419 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001420 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1421 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001422 if (config->mInputSurface) {
1423 config->mInputSurface->disconnect();
1424 config->mInputSurface = nullptr;
1425 }
1426 }
1427 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001428 Mutexed<State>::Locked state(mState);
1429 if (state->get() == STOPPING) {
1430 state->set(ALLOCATED);
1431 }
1432 }
1433 mCallback->onStopCompleted();
1434}
1435
1436void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001437 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001438 {
1439 Mutexed<State>::Locked state(mState);
1440 if (state->get() == RELEASED || state->get() == RELEASING) {
1441 // We're already released or doing it right now.
1442 if (sendCallback) {
1443 state.unlock();
1444 mCallback->onReleaseCompleted();
1445 state.lock();
1446 }
1447 return;
1448 }
1449 if (state->get() == ALLOCATING) {
1450 state->set(RELEASING);
1451 // With the altered state allocate() would fail and clean up.
1452 if (sendCallback) {
1453 state.unlock();
1454 mCallback->onReleaseCompleted();
1455 state.lock();
1456 }
1457 return;
1458 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001459 if (state->get() == STARTING
1460 || state->get() == RUNNING
1461 || state->get() == STOPPING) {
1462 // Input surface may have been started, so clean up is needed.
1463 clearInputSurfaceIfNeeded = true;
1464 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001465 state->set(RELEASING);
1466 }
1467
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001468 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001469 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1470 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001471 if (config->mInputSurface) {
1472 config->mInputSurface->disconnect();
1473 config->mInputSurface = nullptr;
1474 }
1475 }
1476
Wonsik Kim936a89c2020-05-08 16:07:50 -07001477 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001478 // thiz holds strong ref to this while the thread is running.
1479 sp<CCodec> thiz(this);
1480 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1481}
1482
1483void CCodec::release(bool sendCallback) {
1484 std::shared_ptr<Codec2Client::Component> comp;
1485 {
1486 Mutexed<State>::Locked state(mState);
1487 if (state->get() == RELEASED) {
1488 if (sendCallback) {
1489 state.unlock();
1490 mCallback->onReleaseCompleted();
1491 state.lock();
1492 }
1493 return;
1494 }
1495 comp = state->comp;
1496 }
1497 comp->release();
1498
1499 {
1500 Mutexed<State>::Locked state(mState);
1501 state->set(RELEASED);
1502 state->comp.reset();
1503 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001504 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001505 if (sendCallback) {
1506 mCallback->onReleaseCompleted();
1507 }
1508}
1509
1510status_t CCodec::setSurface(const sp<Surface> &surface) {
1511 return mChannel->setSurface(surface);
1512}
1513
1514void CCodec::signalFlush() {
1515 status_t err = [this] {
1516 Mutexed<State>::Locked state(mState);
1517 if (state->get() == FLUSHED) {
1518 return ALREADY_EXISTS;
1519 }
1520 if (state->get() != RUNNING) {
1521 return UNKNOWN_ERROR;
1522 }
1523 state->set(FLUSHING);
1524 return OK;
1525 }();
1526 switch (err) {
1527 case ALREADY_EXISTS:
1528 mCallback->onFlushCompleted();
1529 return;
1530 case OK:
1531 break;
1532 default:
1533 mCallback->onError(err, ACTION_CODE_FATAL);
1534 return;
1535 }
1536
1537 mChannel->stop();
1538 (new AMessage(kWhatFlush, this))->post();
1539}
1540
1541void CCodec::flush() {
1542 std::shared_ptr<Codec2Client::Component> comp;
1543 auto checkFlushing = [this, &comp] {
1544 Mutexed<State>::Locked state(mState);
1545 if (state->get() != FLUSHING) {
1546 return UNKNOWN_ERROR;
1547 }
1548 comp = state->comp;
1549 return OK;
1550 };
1551 if (tryAndReportOnError(checkFlushing) != OK) {
1552 return;
1553 }
1554
1555 std::list<std::unique_ptr<C2Work>> flushedWork;
1556 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1557 {
1558 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1559 flushedWork.splice(flushedWork.end(), *queue);
1560 }
1561 if (err != C2_OK) {
1562 // TODO: convert err into status_t
1563 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1564 }
1565
1566 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001567
1568 {
1569 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001570 if (state->get() == FLUSHING) {
1571 state->set(FLUSHED);
1572 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001573 }
1574 mCallback->onFlushCompleted();
1575}
1576
1577void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001578 std::shared_ptr<Codec2Client::Component> comp;
1579 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001580 Mutexed<State>::Locked state(mState);
1581 if (state->get() != FLUSHED) {
1582 return UNKNOWN_ERROR;
1583 }
1584 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001585 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001586 return OK;
1587 };
1588 if (tryAndReportOnError(setResuming) != OK) {
1589 return;
1590 }
1591
Wonsik Kime75a5da2020-02-14 17:29:03 -08001592 {
1593 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1594 const std::unique_ptr<Config> &config = *configLocked;
1595 config->queryConfiguration(comp);
1596 }
1597
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001598 (void)mChannel->start(nullptr, nullptr, [&]{
1599 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1600 const std::unique_ptr<Config> &config = *configLocked;
1601 return config->mBuffersBoundToCodec;
1602 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001603
1604 {
1605 Mutexed<State>::Locked state(mState);
1606 if (state->get() != RESUMING) {
1607 state.unlock();
1608 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1609 state.lock();
1610 return;
1611 }
1612 state->set(RUNNING);
1613 }
1614
1615 (void)mChannel->requestInitialInputBuffers();
1616}
1617
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001618void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001619 std::shared_ptr<Codec2Client::Component> comp;
1620 auto checkState = [this, &comp] {
1621 Mutexed<State>::Locked state(mState);
1622 if (state->get() == RELEASED) {
1623 return INVALID_OPERATION;
1624 }
1625 comp = state->comp;
1626 return OK;
1627 };
1628 if (tryAndReportOnError(checkState) != OK) {
1629 return;
1630 }
1631
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001632 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1633 // the behavior here.
1634 sp<AMessage> params = msg;
1635 int32_t bitrate;
1636 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1637 params = msg->dup();
1638 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1639 }
1640
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001641 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1642 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001643
1644 /**
1645 * Handle input surface parameters
1646 */
1647 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001648 && (config->mDomain & Config::IS_ENCODER)
1649 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001650 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001651
1652 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1653 config->mISConfig->mStopped = false;
1654 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1655 config->mISConfig->mStopped = true;
1656 }
1657
1658 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001659 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001660 config->mISConfig->mSuspended = value;
1661 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001662 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001663 }
1664
1665 (void)config->mInputSurface->configure(*config->mISConfig);
1666 if (config->mISConfig->mStopped) {
1667 config->mInputFormat->setInt64(
1668 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1669 }
1670 }
1671
1672 std::vector<std::unique_ptr<C2Param>> configUpdate;
1673 (void)config->getConfigUpdateFromSdkParams(
1674 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1675 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1676 // Parameter synchronization is not defined when using input surface. For now, route
1677 // these directly to the component.
1678 if (config->mInputSurface == nullptr
1679 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1680 || comp->getName().find("c2.android.") == 0)) {
1681 mChannel->setParameters(configUpdate);
1682 } else {
1683 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1684 }
1685}
1686
1687void CCodec::signalEndOfInputStream() {
1688 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1689}
1690
1691void CCodec::signalRequestIDRFrame() {
1692 std::shared_ptr<Codec2Client::Component> comp;
1693 {
1694 Mutexed<State>::Locked state(mState);
1695 if (state->get() == RELEASED) {
1696 ALOGD("no IDR request sent since component is released");
1697 return;
1698 }
1699 comp = state->comp;
1700 }
1701 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001702 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1703 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001704 std::vector<std::unique_ptr<C2Param>> params;
1705 params.push_back(
1706 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1707 config->setParameters(comp, params, C2_MAY_BLOCK);
1708}
1709
Wonsik Kimab34ed62019-01-31 15:28:46 -08001710void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001711 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001712 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1713 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001714 }
1715 (new AMessage(kWhatWorkDone, this))->post();
1716}
1717
Wonsik Kimab34ed62019-01-31 15:28:46 -08001718void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1719 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001720 if (arrayIndex == 0) {
1721 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001722 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1723 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001724 if (config->mInputSurface) {
1725 config->mInputSurface->onInputBufferDone(frameIndex);
1726 }
1727 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001728}
1729
1730void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1731 TimePoint now = std::chrono::steady_clock::now();
1732 CCodecWatchdog::getInstance()->watch(this);
1733 switch (msg->what()) {
1734 case kWhatAllocate: {
1735 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001736 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001737 sp<RefBase> obj;
1738 CHECK(msg->findObject("codecInfo", &obj));
1739 allocate((MediaCodecInfo *)obj.get());
1740 break;
1741 }
1742 case kWhatConfigure: {
1743 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001744 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001745 sp<AMessage> format;
1746 CHECK(msg->findMessage("format", &format));
1747 configure(format);
1748 break;
1749 }
1750 case kWhatStart: {
1751 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001752 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001753 start();
1754 break;
1755 }
1756 case kWhatStop: {
1757 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001758 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001759 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001760 break;
1761 }
1762 case kWhatFlush: {
1763 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001764 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001765 flush();
1766 break;
1767 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001768 case kWhatRelease: {
1769 mChannel->release();
1770 mClient.reset();
1771 mClientListener.reset();
1772 break;
1773 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001774 case kWhatCreateInputSurface: {
1775 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001776 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001777 createInputSurface();
1778 break;
1779 }
1780 case kWhatSetInputSurface: {
1781 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001782 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001783 sp<RefBase> obj;
1784 CHECK(msg->findObject("surface", &obj));
1785 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1786 setInputSurface(surface);
1787 break;
1788 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001789 case kWhatWorkDone: {
1790 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001791 bool shouldPost = false;
1792 {
1793 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1794 if (queue->empty()) {
1795 break;
1796 }
1797 work.swap(queue->front());
1798 queue->pop_front();
1799 shouldPost = !queue->empty();
1800 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001801 if (shouldPost) {
1802 (new AMessage(kWhatWorkDone, this))->post();
1803 }
1804
Pawin Vongmasa36653902018-11-15 00:10:25 -08001805 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001806 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1807 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8ec93ab2020-11-13 16:17:04 -08001808 bool changed = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001809 Config::Watcher<C2StreamInitDataInfo::output> initData =
1810 config->watch<C2StreamInitDataInfo::output>();
1811 if (!work->worklets.empty()
1812 && (work->worklets.front()->output.flags
1813 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1814
1815 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001816 std::vector<std::unique_ptr<C2Param>> updates;
1817 for (const std::unique_ptr<C2Param> &param
1818 : work->worklets.front()->output.configUpdate) {
1819 updates.push_back(C2Param::Copy(*param));
1820 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001821 unsigned stream = 0;
1822 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1823 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1824 // move all info into output-stream #0 domain
1825 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1826 }
George Burgess IVc813a592020-02-22 22:54:44 -08001827
1828 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
1829 // for now only do the first block
1830 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001831 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1832 // block.crop().left, block.crop().top,
1833 // block.crop().width, block.crop().height,
1834 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08001835 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08001836 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1837 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07001838 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001839 }
1840 ++stream;
1841 }
1842
Wonsik Kim8ec93ab2020-11-13 16:17:04 -08001843 if (config->updateConfiguration(updates, config->mOutputDomain)) {
1844 changed = true;
1845 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001846
1847 // copy standard infos to graphic buffers if not already present (otherwise, we
1848 // may overwrite the actual intermediate value with a final value)
1849 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07001850 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001851 C2StreamRotationInfo::output::PARAM_TYPE,
1852 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1853 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1854 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001855 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001856 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1857 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1858 };
1859 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1860 if (buf->data().graphicBlocks().size()) {
1861 for (C2Param::Index ix : stdGfxInfos) {
1862 if (!buf->hasInfo(ix)) {
1863 const C2Param *param =
1864 config->getConfigParameterValue(ix.withStream(stream));
1865 if (param) {
1866 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1867 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1868 }
1869 }
1870 }
1871 }
1872 ++stream;
1873 }
1874 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001875 if (config->mInputSurface) {
1876 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
1877 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001878 mChannel->onWorkDone(
Wonsik Kim8ec93ab2020-11-13 16:17:04 -08001879 std::move(work), changed ? config->mOutputFormat->dup() : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001880 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001881 break;
1882 }
1883 case kWhatWatch: {
1884 // watch message already posted; no-op.
1885 break;
1886 }
1887 default: {
1888 ALOGE("unrecognized message");
1889 break;
1890 }
1891 }
1892 setDeadline(TimePoint::max(), 0ms, "none");
1893}
1894
1895void CCodec::setDeadline(
1896 const TimePoint &now,
1897 const std::chrono::milliseconds &timeout,
1898 const char *name) {
1899 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1900 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1901 deadline->set(now + (timeout * mult), name);
1902}
1903
1904void CCodec::initiateReleaseIfStuck() {
1905 std::string name;
1906 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001907 {
1908 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001909 if (deadline->get() < std::chrono::steady_clock::now()) {
1910 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001911 }
1912 if (deadline->get() != TimePoint::max()) {
1913 pendingDeadline = true;
1914 }
1915 }
1916 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001917 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1918 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1919 if (elapsed >= kWorkDurationThreshold) {
1920 name = "queue";
1921 }
1922 if (elapsed > 0s) {
1923 pendingDeadline = true;
1924 }
1925 }
1926 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001927 // We're not stuck.
1928 if (pendingDeadline) {
1929 // If we are not stuck yet but still has deadline coming up,
1930 // post watch message to check back later.
1931 (new AMessage(kWhatWatch, this))->post();
1932 }
1933 return;
1934 }
1935
1936 ALOGW("previous call to %s exceeded timeout", name.c_str());
1937 initiateRelease(false);
1938 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1939}
1940
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001941// static
1942PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07001943 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001944 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001945 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07001946 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1947 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001948 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07001949 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
1950 sp<IGraphicBufferProducer> gbp;
1951 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
1952 status_t err = gbs->initCheck();
1953 if (err != OK) {
1954 ALOGE("Failed to create persistent input surface: error %d", err);
1955 return nullptr;
1956 }
1957 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001958 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07001959 } else {
1960 return nullptr;
1961 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001962 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07001963 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001964 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07001965 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08001966 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001967}
1968
Wonsik Kimffb889a2020-05-28 11:32:25 -07001969class IntfCache {
1970public:
1971 IntfCache() = default;
1972
1973 status_t init(const std::string &name) {
1974 std::shared_ptr<Codec2Client::Interface> intf{
1975 Codec2Client::CreateInterfaceByName(name.c_str())};
1976 if (!intf) {
1977 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
1978 mInitStatus = NO_INIT;
1979 return NO_INIT;
1980 }
1981 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
1982 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
1983 C2ParamField{&sUsage, &sUsage.value}));
1984 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
1985 if (err != C2_OK) {
1986 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
1987 name.c_str(), err);
1988 mFields[0].status = err;
1989 }
1990 std::vector<std::unique_ptr<C2Param>> params;
1991 err = intf->query(
1992 {&mApiFeatures},
1993 {C2PortAllocatorsTuning::input::PARAM_TYPE},
1994 C2_MAY_BLOCK,
1995 &params);
1996 if (err != C2_OK && err != C2_BAD_INDEX) {
1997 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
1998 name.c_str(), err);
1999 }
2000 while (!params.empty()) {
2001 C2Param *param = params.back().release();
2002 params.pop_back();
2003 if (!param) {
2004 continue;
2005 }
2006 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2007 mInputAllocators.reset(
2008 C2PortAllocatorsTuning::input::From(params[0].get()));
2009 }
2010 }
2011 mInitStatus = OK;
2012 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002013 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002014
2015 status_t initCheck() const { return mInitStatus; }
2016
2017 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2018 CHECK_EQ(1u, mFields.size());
2019 return mFields[0];
2020 }
2021
2022 const C2ApiFeaturesSetting &getApiFeatures() const {
2023 return mApiFeatures;
2024 }
2025
2026 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2027 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2028 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2029 C2PortAllocatorsTuning::input::AllocUnique(0);
2030 param->invalidate();
2031 return param;
2032 }();
2033 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2034 }
2035
2036private:
2037 status_t mInitStatus{NO_INIT};
2038
2039 std::vector<C2FieldSupportedValuesQuery> mFields;
2040 C2ApiFeaturesSetting mApiFeatures;
2041 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2042};
2043
2044static const IntfCache &GetIntfCache(const std::string &name) {
2045 static IntfCache sNullIntfCache;
2046 static std::mutex sMutex;
2047 static std::map<std::string, IntfCache> sCache;
2048 std::unique_lock<std::mutex> lock{sMutex};
2049 auto it = sCache.find(name);
2050 if (it == sCache.end()) {
2051 lock.unlock();
2052 IntfCache intfCache;
2053 status_t err = intfCache.init(name);
2054 if (err != OK) {
2055 return sNullIntfCache;
2056 }
2057 lock.lock();
2058 it = sCache.insert({name, std::move(intfCache)}).first;
2059 }
2060 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002061}
2062
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002063static status_t GetCommonAllocatorIds(
2064 const std::vector<std::string> &names,
2065 C2Allocator::type_t type,
2066 std::set<C2Allocator::id_t> *ids) {
2067 int poolMask = GetCodec2PoolMask();
2068 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2069 C2Allocator::id_t defaultAllocatorId =
2070 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2071
2072 ids->clear();
2073 if (names.empty()) {
2074 return OK;
2075 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002076 bool firstIteration = true;
2077 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002078 const IntfCache &intfCache = GetIntfCache(name);
2079 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002080 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002081 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002082 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002083 if (firstIteration) {
2084 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002085 if (allocators && allocators.flexCount() > 0) {
2086 ids->insert(allocators.m.values,
2087 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002088 }
2089 if (ids->empty()) {
2090 // The component does not advertise allocators. Use default.
2091 ids->insert(defaultAllocatorId);
2092 }
2093 continue;
2094 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002095 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002096 if (allocators && allocators.flexCount() > 0) {
2097 filtered = true;
2098 for (auto it = ids->begin(); it != ids->end(); ) {
2099 bool found = false;
2100 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2101 if (allocators.m.values[j] == *it) {
2102 found = true;
2103 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002104 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002105 }
2106 if (found) {
2107 ++it;
2108 } else {
2109 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002110 }
2111 }
2112 }
2113 if (!filtered) {
2114 // The component does not advertise supported allocators. Use default.
2115 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2116 if (ids->size() != (containsDefault ? 1 : 0)) {
2117 ids->clear();
2118 if (containsDefault) {
2119 ids->insert(defaultAllocatorId);
2120 }
2121 }
2122 }
2123 }
2124 // Finally, filter with pool masks
2125 for (auto it = ids->begin(); it != ids->end(); ) {
2126 if ((poolMask >> *it) & 1) {
2127 ++it;
2128 } else {
2129 it = ids->erase(it);
2130 }
2131 }
2132 return OK;
2133}
2134
2135static status_t CalculateMinMaxUsage(
2136 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2137 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2138 *minUsage = 0;
2139 *maxUsage = ~0ull;
2140 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002141 const IntfCache &intfCache = GetIntfCache(name);
2142 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002143 continue;
2144 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002145 const C2FieldSupportedValuesQuery &usageSupportedValues =
2146 intfCache.getUsageSupportedValues();
2147 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002148 continue;
2149 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002150 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002151 if (supported.type != C2FieldSupportedValues::FLAGS) {
2152 continue;
2153 }
2154 if (supported.values.empty()) {
2155 *maxUsage = 0;
2156 continue;
2157 }
2158 *minUsage |= supported.values[0].u64;
2159 int64_t currentMaxUsage = 0;
2160 for (const C2Value::Primitive &flags : supported.values) {
2161 currentMaxUsage |= flags.u64;
2162 }
2163 *maxUsage &= currentMaxUsage;
2164 }
2165 return OK;
2166}
2167
2168// static
2169status_t CCodec::CanFetchLinearBlock(
2170 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002171 for (const std::string &name : names) {
2172 const IntfCache &intfCache = GetIntfCache(name);
2173 if (intfCache.initCheck() != OK) {
2174 continue;
2175 }
2176 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2177 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2178 *isCompatible = false;
2179 return OK;
2180 }
2181 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002182 uint64_t minUsage = usage.expected;
2183 uint64_t maxUsage = ~0ull;
2184 std::set<C2Allocator::id_t> allocators;
2185 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2186 if (allocators.empty()) {
2187 *isCompatible = false;
2188 return OK;
2189 }
2190 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2191 *isCompatible = ((maxUsage & minUsage) == minUsage);
2192 return OK;
2193}
2194
2195static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2196 static std::mutex sMutex{};
2197 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2198 std::unique_lock<std::mutex> lock{sMutex};
2199 std::shared_ptr<C2BlockPool> pool;
2200 auto it = sPools.find(allocId);
2201 if (it == sPools.end()) {
2202 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2203 if (err == OK) {
2204 sPools.emplace(allocId, pool);
2205 } else {
2206 pool.reset();
2207 }
2208 } else {
2209 pool = it->second;
2210 }
2211 return pool;
2212}
2213
2214// static
2215std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2216 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
2217 uint64_t minUsage = usage.expected;
2218 uint64_t maxUsage = ~0ull;
2219 std::set<C2Allocator::id_t> allocators;
2220 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2221 if (allocators.empty()) {
2222 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2223 }
2224 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2225 if ((maxUsage & minUsage) != minUsage) {
2226 allocators.clear();
2227 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2228 }
2229 std::shared_ptr<C2LinearBlock> block;
2230 for (C2Allocator::id_t allocId : allocators) {
2231 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2232 if (!pool) {
2233 continue;
2234 }
2235 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2236 if (err != C2_OK || !block) {
2237 block.reset();
2238 continue;
2239 }
2240 break;
2241 }
2242 return block;
2243}
2244
2245// static
2246status_t CCodec::CanFetchGraphicBlock(
2247 const std::vector<std::string> &names, bool *isCompatible) {
2248 uint64_t minUsage = 0;
2249 uint64_t maxUsage = ~0ull;
2250 std::set<C2Allocator::id_t> allocators;
2251 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2252 if (allocators.empty()) {
2253 *isCompatible = false;
2254 return OK;
2255 }
2256 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2257 *isCompatible = ((maxUsage & minUsage) == minUsage);
2258 return OK;
2259}
2260
2261// static
2262std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2263 int32_t width,
2264 int32_t height,
2265 int32_t format,
2266 uint64_t usage,
2267 const std::vector<std::string> &names) {
2268 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2269 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2270 ALOGD("Unrecognized pixel format: %d", format);
2271 return nullptr;
2272 }
2273 uint64_t minUsage = 0;
2274 uint64_t maxUsage = ~0ull;
2275 std::set<C2Allocator::id_t> allocators;
2276 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2277 if (allocators.empty()) {
2278 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2279 }
2280 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2281 minUsage |= usage;
2282 if ((maxUsage & minUsage) != minUsage) {
2283 allocators.clear();
2284 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2285 }
2286 std::shared_ptr<C2GraphicBlock> block;
2287 for (C2Allocator::id_t allocId : allocators) {
2288 std::shared_ptr<C2BlockPool> pool;
2289 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2290 if (err != C2_OK || !pool) {
2291 continue;
2292 }
2293 err = pool->fetchGraphicBlock(
2294 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2295 if (err != C2_OK || !block) {
2296 block.reset();
2297 continue;
2298 }
2299 break;
2300 }
2301 return block;
2302}
2303
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002304} // namespace android
2305