blob: a4d2110728c74bf0b69807c4a9942c367d718e5b [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 }
Wonsik Kim666604a2020-05-14 16:57:49 -0700970 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800971 }
972
973 // NOTE: we don't blindly use client specified input size if specified as clients
974 // at times specify too small size. Instead, mimic the behavior from OMX, where the
975 // client specified size is only used to ask for bigger buffers than component suggested
976 // size.
977 int32_t clientInputSize = 0;
978 bool clientSpecifiedInputSize =
979 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
980 // TEMP: enforce minimum buffer size of 1MB for video decoders
981 // and 16K / 4K for audio encoders/decoders
982 if (maxInputSize.value == 0) {
983 if (config->mDomain & Config::IS_AUDIO) {
984 maxInputSize.value = encoder ? 16384 : 4096;
985 } else if (!encoder) {
986 maxInputSize.value = 1048576u;
987 }
988 }
989
990 // verify that CSD fits into this size (if defined)
991 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
992 sp<ABuffer> csd;
993 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
994 if (csd && csd->size() > maxInputSize.value) {
995 maxInputSize.value = csd->size();
996 }
997 }
998 }
999
1000 // TODO: do this based on component requiring linear allocator for input
1001 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1002 if (clientSpecifiedInputSize) {
1003 // Warn that we're overriding client's max input size if necessary.
1004 if ((uint32_t)clientInputSize < maxInputSize.value) {
1005 ALOGD("client requested max input size %d, which is smaller than "
1006 "what component recommended (%u); overriding with component "
1007 "recommendation.", clientInputSize, maxInputSize.value);
1008 ALOGW("This behavior is subject to change. It is recommended that "
1009 "app developers double check whether the requested "
1010 "max input size is in reasonable range.");
1011 } else {
1012 maxInputSize.value = clientInputSize;
1013 }
1014 }
1015 // Pass max input size on input format to the buffer channel (if supplied by the
1016 // component or by a default)
1017 if (maxInputSize.value) {
1018 config->mInputFormat->setInt32(
1019 KEY_MAX_INPUT_SIZE,
1020 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1021 }
1022 }
1023
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001024 int32_t clientPrepend;
1025 if ((config->mDomain & Config::IS_VIDEO)
1026 && (config->mDomain & Config::IS_ENCODER)
1027 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1028 && clientPrepend
1029 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1030 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1031 return BAD_VALUE;
1032 }
1033
Pawin Vongmasa36653902018-11-15 00:10:25 -08001034 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1035 // propagate HDR static info to output format for both encoders and decoders
1036 // if component supports this info, we will update from component, but only the raw port,
1037 // so don't propagate if component already filled it in.
1038 sp<ABuffer> hdrInfo;
1039 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1040 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1041 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1042 }
1043
1044 // Set desired color format from configuration parameter
1045 int32_t format;
1046 if (msg->findInt32("android._color-format", &format)) {
1047 if (config->mDomain & Config::IS_ENCODER) {
1048 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
1049 } else {
1050 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
1051 }
1052 }
1053 }
1054
1055 // propagate encoder delay and padding to output format
1056 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1057 int delay = 0;
1058 if (msg->findInt32("encoder-delay", &delay)) {
1059 config->mOutputFormat->setInt32("encoder-delay", delay);
1060 }
1061 int padding = 0;
1062 if (msg->findInt32("encoder-padding", &padding)) {
1063 config->mOutputFormat->setInt32("encoder-padding", padding);
1064 }
1065 }
1066
1067 // set channel-mask
1068 if (config->mDomain & Config::IS_AUDIO) {
1069 int32_t mask;
1070 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1071 if (config->mDomain & Config::IS_ENCODER) {
1072 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1073 } else {
1074 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1075 }
1076 }
1077 }
1078
1079 ALOGD("setup formats input: %s and output: %s",
1080 config->mInputFormat->debugString().c_str(),
1081 config->mOutputFormat->debugString().c_str());
1082 return OK;
1083 };
1084 if (tryAndReportOnError(doConfig) != OK) {
1085 return;
1086 }
1087
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001088 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1089 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001090
1091 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1092}
1093
1094void CCodec::initiateCreateInputSurface() {
1095 status_t err = [this] {
1096 Mutexed<State>::Locked state(mState);
1097 if (state->get() != ALLOCATED) {
1098 return UNKNOWN_ERROR;
1099 }
1100 // TODO: read it from intf() properly.
1101 if (state->comp->getName().find("encoder") == std::string::npos) {
1102 return INVALID_OPERATION;
1103 }
1104 return OK;
1105 }();
1106 if (err != OK) {
1107 mCallback->onInputSurfaceCreationFailed(err);
1108 return;
1109 }
1110
1111 (new AMessage(kWhatCreateInputSurface, this))->post();
1112}
1113
Lajos Molnar47118272019-01-31 16:28:04 -08001114sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1115 using namespace android::hardware::media::omx::V1_0;
1116 using namespace android::hardware::media::omx::V1_0::utils;
1117 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1118 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1119 android::sp<IOmx> omx = IOmx::getService();
1120 typedef android::hardware::graphics::bufferqueue::V1_0::
1121 IGraphicBufferProducer HGraphicBufferProducer;
1122 typedef android::hardware::media::omx::V1_0::
1123 IGraphicBufferSource HGraphicBufferSource;
1124 OmxStatus s;
1125 android::sp<HGraphicBufferProducer> gbp;
1126 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001127
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001128 using ::android::hardware::Return;
1129 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001130 [&s, &gbp, &gbs](
1131 OmxStatus status,
1132 const android::sp<HGraphicBufferProducer>& producer,
1133 const android::sp<HGraphicBufferSource>& source) {
1134 s = status;
1135 gbp = producer;
1136 gbs = source;
1137 });
1138 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001139 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001140 }
1141
1142 return nullptr;
1143}
1144
1145sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1146 sp<PersistentSurface> surface(CreateInputSurface());
1147
1148 if (surface == nullptr) {
1149 surface = CreateOmxInputSurface();
1150 }
1151
1152 return surface;
1153}
1154
Pawin Vongmasa36653902018-11-15 00:10:25 -08001155void CCodec::createInputSurface() {
1156 status_t err;
1157 sp<IGraphicBufferProducer> bufferProducer;
1158
1159 sp<AMessage> inputFormat;
1160 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001161 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001162 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001163 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1164 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001165 inputFormat = config->mInputFormat;
1166 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001167 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001168 }
1169
Lajos Molnar47118272019-01-31 16:28:04 -08001170 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001171 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1172 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1173 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001174
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001175 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001176 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1177 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001178 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001179 inputSurface));
1180 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001181 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001182 int32_t width = 0;
1183 (void)outputFormat->findInt32("width", &width);
1184 int32_t height = 0;
1185 (void)outputFormat->findInt32("height", &height);
1186 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001187 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001188 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001189 } else {
1190 ALOGE("Corrupted input surface");
1191 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1192 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001193 }
1194
1195 if (err != OK) {
1196 ALOGE("Failed to set up input surface: %d", err);
1197 mCallback->onInputSurfaceCreationFailed(err);
1198 return;
1199 }
1200
1201 mCallback->onInputSurfaceCreated(
1202 inputFormat,
1203 outputFormat,
1204 new BufferProducerWrapper(bufferProducer));
1205}
1206
1207status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001208 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1209 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001210 config->mUsingSurface = true;
1211
1212 // we are now using surface - apply default color aspects to input format - as well as
1213 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001214 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001215 ALOGD("input format %s to %s",
1216 inputFormatChanged ? "changed" : "unchanged",
1217 config->mInputFormat->debugString().c_str());
1218
1219 // configure dataspace
1220 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1221 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1222 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1223 surface->setDataSpace(dataSpace);
1224
1225 status_t err = mChannel->setInputSurface(surface);
1226 if (err != OK) {
1227 // undo input format update
1228 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001229 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001230 return err;
1231 }
1232 config->mInputSurface = surface;
1233
1234 if (config->mISConfig) {
1235 surface->configure(*config->mISConfig);
1236 } else {
1237 ALOGD("ISConfig: no configuration");
1238 }
1239
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001240 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001241}
1242
1243void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1244 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1245 msg->setObject("surface", surface);
1246 msg->post();
1247}
1248
1249void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1250 sp<AMessage> inputFormat;
1251 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001252 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001253 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001254 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1255 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001256 inputFormat = config->mInputFormat;
1257 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001258 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001259 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001260 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1261 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1262 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1263 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001264 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1265 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1266 if (err != OK) {
1267 ALOGE("Failed to set up input surface: %d", err);
1268 mCallback->onInputSurfaceDeclined(err);
1269 return;
1270 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001271 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001272 int32_t width = 0;
1273 (void)outputFormat->findInt32("width", &width);
1274 int32_t height = 0;
1275 (void)outputFormat->findInt32("height", &height);
1276 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001277 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001278 if (err != OK) {
1279 ALOGE("Failed to set up input surface: %d", err);
1280 mCallback->onInputSurfaceDeclined(err);
1281 return;
1282 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001283 } else {
1284 ALOGE("Failed to set input surface: Corrupted surface.");
1285 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1286 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001287 }
1288 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1289}
1290
1291void CCodec::initiateStart() {
1292 auto setStarting = [this] {
1293 Mutexed<State>::Locked state(mState);
1294 if (state->get() != ALLOCATED) {
1295 return UNKNOWN_ERROR;
1296 }
1297 state->set(STARTING);
1298 return OK;
1299 };
1300 if (tryAndReportOnError(setStarting) != OK) {
1301 return;
1302 }
1303
1304 (new AMessage(kWhatStart, this))->post();
1305}
1306
1307void CCodec::start() {
1308 std::shared_ptr<Codec2Client::Component> comp;
1309 auto checkStarting = [this, &comp] {
1310 Mutexed<State>::Locked state(mState);
1311 if (state->get() != STARTING) {
1312 return UNKNOWN_ERROR;
1313 }
1314 comp = state->comp;
1315 return OK;
1316 };
1317 if (tryAndReportOnError(checkStarting) != OK) {
1318 return;
1319 }
1320
1321 c2_status_t err = comp->start();
1322 if (err != C2_OK) {
1323 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1324 ACTION_CODE_FATAL);
1325 return;
1326 }
1327 sp<AMessage> inputFormat;
1328 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001329 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001330 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001331 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001332 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1333 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001334 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001335 // start triggers format dup
1336 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001337 if (config->mInputSurface) {
1338 err2 = config->mInputSurface->start();
1339 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001340 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001341 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001342 if (err2 != OK) {
1343 mCallback->onError(err2, ACTION_CODE_FATAL);
1344 return;
1345 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001346 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001347 if (err2 != OK) {
1348 mCallback->onError(err2, ACTION_CODE_FATAL);
1349 return;
1350 }
1351
1352 auto setRunning = [this] {
1353 Mutexed<State>::Locked state(mState);
1354 if (state->get() != STARTING) {
1355 return UNKNOWN_ERROR;
1356 }
1357 state->set(RUNNING);
1358 return OK;
1359 };
1360 if (tryAndReportOnError(setRunning) != OK) {
1361 return;
1362 }
1363 mCallback->onStartCompleted();
1364
1365 (void)mChannel->requestInitialInputBuffers();
1366}
1367
1368void CCodec::initiateShutdown(bool keepComponentAllocated) {
1369 if (keepComponentAllocated) {
1370 initiateStop();
1371 } else {
1372 initiateRelease();
1373 }
1374}
1375
1376void CCodec::initiateStop() {
1377 {
1378 Mutexed<State>::Locked state(mState);
1379 if (state->get() == ALLOCATED
1380 || state->get() == RELEASED
1381 || state->get() == STOPPING
1382 || state->get() == RELEASING) {
1383 // We're already stopped, released, or doing it right now.
1384 state.unlock();
1385 mCallback->onStopCompleted();
1386 state.lock();
1387 return;
1388 }
1389 state->set(STOPPING);
1390 }
1391
Wonsik Kim936a89c2020-05-08 16:07:50 -07001392 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001393 (new AMessage(kWhatStop, this))->post();
1394}
1395
1396void CCodec::stop() {
1397 std::shared_ptr<Codec2Client::Component> comp;
1398 {
1399 Mutexed<State>::Locked state(mState);
1400 if (state->get() == RELEASING) {
1401 state.unlock();
1402 // We're already stopped or release is in progress.
1403 mCallback->onStopCompleted();
1404 state.lock();
1405 return;
1406 } else if (state->get() != STOPPING) {
1407 state.unlock();
1408 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1409 state.lock();
1410 return;
1411 }
1412 comp = state->comp;
1413 }
1414 status_t err = comp->stop();
1415 if (err != C2_OK) {
1416 // TODO: convert err into status_t
1417 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1418 }
1419
1420 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001421 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1422 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001423 if (config->mInputSurface) {
1424 config->mInputSurface->disconnect();
1425 config->mInputSurface = nullptr;
1426 }
1427 }
1428 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001429 Mutexed<State>::Locked state(mState);
1430 if (state->get() == STOPPING) {
1431 state->set(ALLOCATED);
1432 }
1433 }
1434 mCallback->onStopCompleted();
1435}
1436
1437void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001438 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001439 {
1440 Mutexed<State>::Locked state(mState);
1441 if (state->get() == RELEASED || state->get() == RELEASING) {
1442 // We're already released or doing it right now.
1443 if (sendCallback) {
1444 state.unlock();
1445 mCallback->onReleaseCompleted();
1446 state.lock();
1447 }
1448 return;
1449 }
1450 if (state->get() == ALLOCATING) {
1451 state->set(RELEASING);
1452 // With the altered state allocate() would fail and clean up.
1453 if (sendCallback) {
1454 state.unlock();
1455 mCallback->onReleaseCompleted();
1456 state.lock();
1457 }
1458 return;
1459 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001460 if (state->get() == STARTING
1461 || state->get() == RUNNING
1462 || state->get() == STOPPING) {
1463 // Input surface may have been started, so clean up is needed.
1464 clearInputSurfaceIfNeeded = true;
1465 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001466 state->set(RELEASING);
1467 }
1468
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001469 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001470 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1471 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001472 if (config->mInputSurface) {
1473 config->mInputSurface->disconnect();
1474 config->mInputSurface = nullptr;
1475 }
1476 }
1477
Wonsik Kim936a89c2020-05-08 16:07:50 -07001478 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001479 // thiz holds strong ref to this while the thread is running.
1480 sp<CCodec> thiz(this);
1481 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1482}
1483
1484void CCodec::release(bool sendCallback) {
1485 std::shared_ptr<Codec2Client::Component> comp;
1486 {
1487 Mutexed<State>::Locked state(mState);
1488 if (state->get() == RELEASED) {
1489 if (sendCallback) {
1490 state.unlock();
1491 mCallback->onReleaseCompleted();
1492 state.lock();
1493 }
1494 return;
1495 }
1496 comp = state->comp;
1497 }
1498 comp->release();
1499
1500 {
1501 Mutexed<State>::Locked state(mState);
1502 state->set(RELEASED);
1503 state->comp.reset();
1504 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001505 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001506 if (sendCallback) {
1507 mCallback->onReleaseCompleted();
1508 }
1509}
1510
1511status_t CCodec::setSurface(const sp<Surface> &surface) {
1512 return mChannel->setSurface(surface);
1513}
1514
1515void CCodec::signalFlush() {
1516 status_t err = [this] {
1517 Mutexed<State>::Locked state(mState);
1518 if (state->get() == FLUSHED) {
1519 return ALREADY_EXISTS;
1520 }
1521 if (state->get() != RUNNING) {
1522 return UNKNOWN_ERROR;
1523 }
1524 state->set(FLUSHING);
1525 return OK;
1526 }();
1527 switch (err) {
1528 case ALREADY_EXISTS:
1529 mCallback->onFlushCompleted();
1530 return;
1531 case OK:
1532 break;
1533 default:
1534 mCallback->onError(err, ACTION_CODE_FATAL);
1535 return;
1536 }
1537
1538 mChannel->stop();
1539 (new AMessage(kWhatFlush, this))->post();
1540}
1541
1542void CCodec::flush() {
1543 std::shared_ptr<Codec2Client::Component> comp;
1544 auto checkFlushing = [this, &comp] {
1545 Mutexed<State>::Locked state(mState);
1546 if (state->get() != FLUSHING) {
1547 return UNKNOWN_ERROR;
1548 }
1549 comp = state->comp;
1550 return OK;
1551 };
1552 if (tryAndReportOnError(checkFlushing) != OK) {
1553 return;
1554 }
1555
1556 std::list<std::unique_ptr<C2Work>> flushedWork;
1557 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1558 {
1559 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1560 flushedWork.splice(flushedWork.end(), *queue);
1561 }
1562 if (err != C2_OK) {
1563 // TODO: convert err into status_t
1564 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1565 }
1566
1567 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001568
1569 {
1570 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001571 if (state->get() == FLUSHING) {
1572 state->set(FLUSHED);
1573 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001574 }
1575 mCallback->onFlushCompleted();
1576}
1577
1578void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001579 std::shared_ptr<Codec2Client::Component> comp;
1580 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001581 Mutexed<State>::Locked state(mState);
1582 if (state->get() != FLUSHED) {
1583 return UNKNOWN_ERROR;
1584 }
1585 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001586 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001587 return OK;
1588 };
1589 if (tryAndReportOnError(setResuming) != OK) {
1590 return;
1591 }
1592
Wonsik Kime75a5da2020-02-14 17:29:03 -08001593 {
1594 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1595 const std::unique_ptr<Config> &config = *configLocked;
1596 config->queryConfiguration(comp);
1597 }
1598
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001599 (void)mChannel->start(nullptr, nullptr, [&]{
1600 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1601 const std::unique_ptr<Config> &config = *configLocked;
1602 return config->mBuffersBoundToCodec;
1603 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001604
1605 {
1606 Mutexed<State>::Locked state(mState);
1607 if (state->get() != RESUMING) {
1608 state.unlock();
1609 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1610 state.lock();
1611 return;
1612 }
1613 state->set(RUNNING);
1614 }
1615
1616 (void)mChannel->requestInitialInputBuffers();
1617}
1618
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001619void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001620 std::shared_ptr<Codec2Client::Component> comp;
1621 auto checkState = [this, &comp] {
1622 Mutexed<State>::Locked state(mState);
1623 if (state->get() == RELEASED) {
1624 return INVALID_OPERATION;
1625 }
1626 comp = state->comp;
1627 return OK;
1628 };
1629 if (tryAndReportOnError(checkState) != OK) {
1630 return;
1631 }
1632
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001633 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1634 // the behavior here.
1635 sp<AMessage> params = msg;
1636 int32_t bitrate;
1637 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1638 params = msg->dup();
1639 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1640 }
1641
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001642 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1643 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001644
1645 /**
1646 * Handle input surface parameters
1647 */
1648 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001649 && (config->mDomain & Config::IS_ENCODER)
1650 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001651 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001652
1653 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1654 config->mISConfig->mStopped = false;
1655 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1656 config->mISConfig->mStopped = true;
1657 }
1658
1659 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001660 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001661 config->mISConfig->mSuspended = value;
1662 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001663 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001664 }
1665
1666 (void)config->mInputSurface->configure(*config->mISConfig);
1667 if (config->mISConfig->mStopped) {
1668 config->mInputFormat->setInt64(
1669 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1670 }
1671 }
1672
1673 std::vector<std::unique_ptr<C2Param>> configUpdate;
1674 (void)config->getConfigUpdateFromSdkParams(
1675 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1676 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1677 // Parameter synchronization is not defined when using input surface. For now, route
1678 // these directly to the component.
1679 if (config->mInputSurface == nullptr
1680 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1681 || comp->getName().find("c2.android.") == 0)) {
1682 mChannel->setParameters(configUpdate);
1683 } else {
1684 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1685 }
1686}
1687
1688void CCodec::signalEndOfInputStream() {
1689 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1690}
1691
1692void CCodec::signalRequestIDRFrame() {
1693 std::shared_ptr<Codec2Client::Component> comp;
1694 {
1695 Mutexed<State>::Locked state(mState);
1696 if (state->get() == RELEASED) {
1697 ALOGD("no IDR request sent since component is released");
1698 return;
1699 }
1700 comp = state->comp;
1701 }
1702 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001703 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1704 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001705 std::vector<std::unique_ptr<C2Param>> params;
1706 params.push_back(
1707 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1708 config->setParameters(comp, params, C2_MAY_BLOCK);
1709}
1710
Wonsik Kimab34ed62019-01-31 15:28:46 -08001711void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001712 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001713 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1714 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001715 }
1716 (new AMessage(kWhatWorkDone, this))->post();
1717}
1718
Wonsik Kimab34ed62019-01-31 15:28:46 -08001719void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1720 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001721 if (arrayIndex == 0) {
1722 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001723 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1724 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001725 if (config->mInputSurface) {
1726 config->mInputSurface->onInputBufferDone(frameIndex);
1727 }
1728 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001729}
1730
1731void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1732 TimePoint now = std::chrono::steady_clock::now();
1733 CCodecWatchdog::getInstance()->watch(this);
1734 switch (msg->what()) {
1735 case kWhatAllocate: {
1736 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001737 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001738 sp<RefBase> obj;
1739 CHECK(msg->findObject("codecInfo", &obj));
1740 allocate((MediaCodecInfo *)obj.get());
1741 break;
1742 }
1743 case kWhatConfigure: {
1744 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001745 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001746 sp<AMessage> format;
1747 CHECK(msg->findMessage("format", &format));
1748 configure(format);
1749 break;
1750 }
1751 case kWhatStart: {
1752 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001753 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001754 start();
1755 break;
1756 }
1757 case kWhatStop: {
1758 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001759 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001760 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001761 break;
1762 }
1763 case kWhatFlush: {
1764 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001765 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001766 flush();
1767 break;
1768 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001769 case kWhatRelease: {
1770 mChannel->release();
1771 mClient.reset();
1772 mClientListener.reset();
1773 break;
1774 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001775 case kWhatCreateInputSurface: {
1776 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001777 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001778 createInputSurface();
1779 break;
1780 }
1781 case kWhatSetInputSurface: {
1782 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001783 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001784 sp<RefBase> obj;
1785 CHECK(msg->findObject("surface", &obj));
1786 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1787 setInputSurface(surface);
1788 break;
1789 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001790 case kWhatWorkDone: {
1791 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001792 bool shouldPost = false;
1793 {
1794 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1795 if (queue->empty()) {
1796 break;
1797 }
1798 work.swap(queue->front());
1799 queue->pop_front();
1800 shouldPost = !queue->empty();
1801 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001802 if (shouldPost) {
1803 (new AMessage(kWhatWorkDone, this))->post();
1804 }
1805
Pawin Vongmasa36653902018-11-15 00:10:25 -08001806 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001807 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1808 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8ec93ab2020-11-13 16:17:04 -08001809 bool changed = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001810 Config::Watcher<C2StreamInitDataInfo::output> initData =
1811 config->watch<C2StreamInitDataInfo::output>();
1812 if (!work->worklets.empty()
1813 && (work->worklets.front()->output.flags
1814 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1815
1816 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001817 std::vector<std::unique_ptr<C2Param>> updates;
1818 for (const std::unique_ptr<C2Param> &param
1819 : work->worklets.front()->output.configUpdate) {
1820 updates.push_back(C2Param::Copy(*param));
1821 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001822 unsigned stream = 0;
1823 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1824 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1825 // move all info into output-stream #0 domain
1826 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1827 }
George Burgess IVc813a592020-02-22 22:54:44 -08001828
1829 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
1830 // for now only do the first block
1831 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001832 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1833 // block.crop().left, block.crop().top,
1834 // block.crop().width, block.crop().height,
1835 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08001836 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08001837 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1838 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07001839 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001840 }
1841 ++stream;
1842 }
1843
Wonsik Kim8ec93ab2020-11-13 16:17:04 -08001844 if (config->updateConfiguration(updates, config->mOutputDomain)) {
1845 changed = true;
1846 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001847
1848 // copy standard infos to graphic buffers if not already present (otherwise, we
1849 // may overwrite the actual intermediate value with a final value)
1850 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07001851 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001852 C2StreamRotationInfo::output::PARAM_TYPE,
1853 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1854 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1855 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001856 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001857 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1858 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1859 };
1860 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1861 if (buf->data().graphicBlocks().size()) {
1862 for (C2Param::Index ix : stdGfxInfos) {
1863 if (!buf->hasInfo(ix)) {
1864 const C2Param *param =
1865 config->getConfigParameterValue(ix.withStream(stream));
1866 if (param) {
1867 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1868 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1869 }
1870 }
1871 }
1872 }
1873 ++stream;
1874 }
1875 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001876 if (config->mInputSurface) {
1877 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
1878 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001879 mChannel->onWorkDone(
Wonsik Kim8ec93ab2020-11-13 16:17:04 -08001880 std::move(work), changed ? config->mOutputFormat->dup() : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001881 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001882 break;
1883 }
1884 case kWhatWatch: {
1885 // watch message already posted; no-op.
1886 break;
1887 }
1888 default: {
1889 ALOGE("unrecognized message");
1890 break;
1891 }
1892 }
1893 setDeadline(TimePoint::max(), 0ms, "none");
1894}
1895
1896void CCodec::setDeadline(
1897 const TimePoint &now,
1898 const std::chrono::milliseconds &timeout,
1899 const char *name) {
1900 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1901 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1902 deadline->set(now + (timeout * mult), name);
1903}
1904
1905void CCodec::initiateReleaseIfStuck() {
1906 std::string name;
1907 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001908 {
1909 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001910 if (deadline->get() < std::chrono::steady_clock::now()) {
1911 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001912 }
1913 if (deadline->get() != TimePoint::max()) {
1914 pendingDeadline = true;
1915 }
1916 }
1917 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001918 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1919 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1920 if (elapsed >= kWorkDurationThreshold) {
1921 name = "queue";
1922 }
1923 if (elapsed > 0s) {
1924 pendingDeadline = true;
1925 }
1926 }
1927 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001928 // We're not stuck.
1929 if (pendingDeadline) {
1930 // If we are not stuck yet but still has deadline coming up,
1931 // post watch message to check back later.
1932 (new AMessage(kWhatWatch, this))->post();
1933 }
1934 return;
1935 }
1936
1937 ALOGW("previous call to %s exceeded timeout", name.c_str());
1938 initiateRelease(false);
1939 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1940}
1941
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001942// static
1943PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07001944 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001945 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001946 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07001947 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1948 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001949 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07001950 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
1951 sp<IGraphicBufferProducer> gbp;
1952 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
1953 status_t err = gbs->initCheck();
1954 if (err != OK) {
1955 ALOGE("Failed to create persistent input surface: error %d", err);
1956 return nullptr;
1957 }
1958 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001959 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07001960 } else {
1961 return nullptr;
1962 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001963 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07001964 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001965 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07001966 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08001967 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001968}
1969
Wonsik Kimffb889a2020-05-28 11:32:25 -07001970class IntfCache {
1971public:
1972 IntfCache() = default;
1973
1974 status_t init(const std::string &name) {
1975 std::shared_ptr<Codec2Client::Interface> intf{
1976 Codec2Client::CreateInterfaceByName(name.c_str())};
1977 if (!intf) {
1978 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
1979 mInitStatus = NO_INIT;
1980 return NO_INIT;
1981 }
1982 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
1983 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
1984 C2ParamField{&sUsage, &sUsage.value}));
1985 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
1986 if (err != C2_OK) {
1987 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
1988 name.c_str(), err);
1989 mFields[0].status = err;
1990 }
1991 std::vector<std::unique_ptr<C2Param>> params;
1992 err = intf->query(
1993 {&mApiFeatures},
1994 {C2PortAllocatorsTuning::input::PARAM_TYPE},
1995 C2_MAY_BLOCK,
1996 &params);
1997 if (err != C2_OK && err != C2_BAD_INDEX) {
1998 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
1999 name.c_str(), err);
2000 }
2001 while (!params.empty()) {
2002 C2Param *param = params.back().release();
2003 params.pop_back();
2004 if (!param) {
2005 continue;
2006 }
2007 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2008 mInputAllocators.reset(
2009 C2PortAllocatorsTuning::input::From(params[0].get()));
2010 }
2011 }
2012 mInitStatus = OK;
2013 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002014 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002015
2016 status_t initCheck() const { return mInitStatus; }
2017
2018 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2019 CHECK_EQ(1u, mFields.size());
2020 return mFields[0];
2021 }
2022
2023 const C2ApiFeaturesSetting &getApiFeatures() const {
2024 return mApiFeatures;
2025 }
2026
2027 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2028 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2029 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2030 C2PortAllocatorsTuning::input::AllocUnique(0);
2031 param->invalidate();
2032 return param;
2033 }();
2034 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2035 }
2036
2037private:
2038 status_t mInitStatus{NO_INIT};
2039
2040 std::vector<C2FieldSupportedValuesQuery> mFields;
2041 C2ApiFeaturesSetting mApiFeatures;
2042 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2043};
2044
2045static const IntfCache &GetIntfCache(const std::string &name) {
2046 static IntfCache sNullIntfCache;
2047 static std::mutex sMutex;
2048 static std::map<std::string, IntfCache> sCache;
2049 std::unique_lock<std::mutex> lock{sMutex};
2050 auto it = sCache.find(name);
2051 if (it == sCache.end()) {
2052 lock.unlock();
2053 IntfCache intfCache;
2054 status_t err = intfCache.init(name);
2055 if (err != OK) {
2056 return sNullIntfCache;
2057 }
2058 lock.lock();
2059 it = sCache.insert({name, std::move(intfCache)}).first;
2060 }
2061 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002062}
2063
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002064static status_t GetCommonAllocatorIds(
2065 const std::vector<std::string> &names,
2066 C2Allocator::type_t type,
2067 std::set<C2Allocator::id_t> *ids) {
2068 int poolMask = GetCodec2PoolMask();
2069 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2070 C2Allocator::id_t defaultAllocatorId =
2071 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2072
2073 ids->clear();
2074 if (names.empty()) {
2075 return OK;
2076 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002077 bool firstIteration = true;
2078 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002079 const IntfCache &intfCache = GetIntfCache(name);
2080 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002081 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002082 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002083 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002084 if (firstIteration) {
2085 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002086 if (allocators && allocators.flexCount() > 0) {
2087 ids->insert(allocators.m.values,
2088 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002089 }
2090 if (ids->empty()) {
2091 // The component does not advertise allocators. Use default.
2092 ids->insert(defaultAllocatorId);
2093 }
2094 continue;
2095 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002096 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002097 if (allocators && allocators.flexCount() > 0) {
2098 filtered = true;
2099 for (auto it = ids->begin(); it != ids->end(); ) {
2100 bool found = false;
2101 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2102 if (allocators.m.values[j] == *it) {
2103 found = true;
2104 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002105 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002106 }
2107 if (found) {
2108 ++it;
2109 } else {
2110 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002111 }
2112 }
2113 }
2114 if (!filtered) {
2115 // The component does not advertise supported allocators. Use default.
2116 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2117 if (ids->size() != (containsDefault ? 1 : 0)) {
2118 ids->clear();
2119 if (containsDefault) {
2120 ids->insert(defaultAllocatorId);
2121 }
2122 }
2123 }
2124 }
2125 // Finally, filter with pool masks
2126 for (auto it = ids->begin(); it != ids->end(); ) {
2127 if ((poolMask >> *it) & 1) {
2128 ++it;
2129 } else {
2130 it = ids->erase(it);
2131 }
2132 }
2133 return OK;
2134}
2135
2136static status_t CalculateMinMaxUsage(
2137 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2138 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2139 *minUsage = 0;
2140 *maxUsage = ~0ull;
2141 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002142 const IntfCache &intfCache = GetIntfCache(name);
2143 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002144 continue;
2145 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002146 const C2FieldSupportedValuesQuery &usageSupportedValues =
2147 intfCache.getUsageSupportedValues();
2148 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002149 continue;
2150 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002151 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002152 if (supported.type != C2FieldSupportedValues::FLAGS) {
2153 continue;
2154 }
2155 if (supported.values.empty()) {
2156 *maxUsage = 0;
2157 continue;
2158 }
2159 *minUsage |= supported.values[0].u64;
2160 int64_t currentMaxUsage = 0;
2161 for (const C2Value::Primitive &flags : supported.values) {
2162 currentMaxUsage |= flags.u64;
2163 }
2164 *maxUsage &= currentMaxUsage;
2165 }
2166 return OK;
2167}
2168
2169// static
2170status_t CCodec::CanFetchLinearBlock(
2171 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002172 for (const std::string &name : names) {
2173 const IntfCache &intfCache = GetIntfCache(name);
2174 if (intfCache.initCheck() != OK) {
2175 continue;
2176 }
2177 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2178 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2179 *isCompatible = false;
2180 return OK;
2181 }
2182 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002183 std::set<C2Allocator::id_t> allocators;
2184 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2185 if (allocators.empty()) {
2186 *isCompatible = false;
2187 return OK;
2188 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002189
2190 uint64_t minUsage = 0;
2191 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002192 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002193 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002194 *isCompatible = ((maxUsage & minUsage) == minUsage);
2195 return OK;
2196}
2197
2198static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2199 static std::mutex sMutex{};
2200 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2201 std::unique_lock<std::mutex> lock{sMutex};
2202 std::shared_ptr<C2BlockPool> pool;
2203 auto it = sPools.find(allocId);
2204 if (it == sPools.end()) {
2205 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2206 if (err == OK) {
2207 sPools.emplace(allocId, pool);
2208 } else {
2209 pool.reset();
2210 }
2211 } else {
2212 pool = it->second;
2213 }
2214 return pool;
2215}
2216
2217// static
2218std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2219 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002220 std::set<C2Allocator::id_t> allocators;
2221 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2222 if (allocators.empty()) {
2223 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2224 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002225
2226 uint64_t minUsage = 0;
2227 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002228 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002229 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002230 if ((maxUsage & minUsage) != minUsage) {
2231 allocators.clear();
2232 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2233 }
2234 std::shared_ptr<C2LinearBlock> block;
2235 for (C2Allocator::id_t allocId : allocators) {
2236 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2237 if (!pool) {
2238 continue;
2239 }
2240 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2241 if (err != C2_OK || !block) {
2242 block.reset();
2243 continue;
2244 }
2245 break;
2246 }
2247 return block;
2248}
2249
2250// static
2251status_t CCodec::CanFetchGraphicBlock(
2252 const std::vector<std::string> &names, bool *isCompatible) {
2253 uint64_t minUsage = 0;
2254 uint64_t maxUsage = ~0ull;
2255 std::set<C2Allocator::id_t> allocators;
2256 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2257 if (allocators.empty()) {
2258 *isCompatible = false;
2259 return OK;
2260 }
2261 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2262 *isCompatible = ((maxUsage & minUsage) == minUsage);
2263 return OK;
2264}
2265
2266// static
2267std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2268 int32_t width,
2269 int32_t height,
2270 int32_t format,
2271 uint64_t usage,
2272 const std::vector<std::string> &names) {
2273 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2274 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2275 ALOGD("Unrecognized pixel format: %d", format);
2276 return nullptr;
2277 }
2278 uint64_t minUsage = 0;
2279 uint64_t maxUsage = ~0ull;
2280 std::set<C2Allocator::id_t> allocators;
2281 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2282 if (allocators.empty()) {
2283 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2284 }
2285 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2286 minUsage |= usage;
2287 if ((maxUsage & minUsage) != minUsage) {
2288 allocators.clear();
2289 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2290 }
2291 std::shared_ptr<C2GraphicBlock> block;
2292 for (C2Allocator::id_t allocId : allocators) {
2293 std::shared_ptr<C2BlockPool> pool;
2294 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2295 if (err != C2_OK || !pool) {
2296 continue;
2297 }
2298 err = pool->fetchGraphicBlock(
2299 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2300 if (err != C2_OK || !block) {
2301 block.reset();
2302 continue;
2303 }
2304 break;
2305 }
2306 return block;
2307}
2308
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002309} // namespace android
2310