blob: 3e83e4236fe1fb10e64b43e87ebecc730216fc8b [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
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800250 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800251 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900252
Wonsik Kim34d66012021-03-01 16:40:33 -0800253 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;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900259 }
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
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800485void RevertOutputFormatIfNeeded(
486 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
487 // We used to not report changes to these keys to the client.
488 const static std::set<std::string> sIgnoredKeys({
489 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800490 KEY_FRAME_RATE,
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800491 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800492 KEY_MAX_WIDTH,
493 KEY_MAX_HEIGHT,
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800494 "csd-0",
495 "csd-1",
496 "csd-2",
497 });
498 if (currentFormat == oldFormat) {
499 return;
500 }
501 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
502 AMessage::Type type;
503 for (size_t i = diff->countEntries(); i > 0; --i) {
504 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
505 diff->removeEntryAt(i - 1);
506 }
507 }
508 if (diff->countEntries() == 0) {
509 currentFormat = oldFormat;
510 }
511}
512
Pawin Vongmasa36653902018-11-15 00:10:25 -0800513} // namespace
514
515// CCodec::ClientListener
516
517struct CCodec::ClientListener : public Codec2Client::Listener {
518
519 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
520
521 virtual void onWorkDone(
522 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800523 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800524 (void)component;
525 sp<CCodec> codec(mCodec.promote());
526 if (!codec) {
527 return;
528 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800529 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800530 }
531
532 virtual void onTripped(
533 const std::weak_ptr<Codec2Client::Component>& component,
534 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
535 ) override {
536 // TODO
537 (void)component;
538 (void)settingResult;
539 }
540
541 virtual void onError(
542 const std::weak_ptr<Codec2Client::Component>& component,
543 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800544 {
545 // Component is only used for reporting as we use a separate listener for each instance
546 std::shared_ptr<Codec2Client::Component> comp = component.lock();
547 if (!comp) {
548 ALOGD("Component died with error: 0x%x", errorCode);
549 } else {
550 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
551 }
552 }
553
554 // Report to MediaCodec
555 // Note: for now we do not propagate the error code to MediaCodec as we would need
556 // to translate to a MediaCodec error.
557 sp<CCodec> codec(mCodec.promote());
558 if (!codec || !codec->mCallback) {
559 return;
560 }
561 codec->mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800562 }
563
564 virtual void onDeath(
565 const std::weak_ptr<Codec2Client::Component>& component) override {
566 { // Log the death of the component.
567 std::shared_ptr<Codec2Client::Component> comp = component.lock();
568 if (!comp) {
569 ALOGE("Codec2 component died.");
570 } else {
571 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
572 }
573 }
574
575 // Report to MediaCodec.
576 sp<CCodec> codec(mCodec.promote());
577 if (!codec || !codec->mCallback) {
578 return;
579 }
580 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
581 }
582
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800583 virtual void onFrameRendered(uint64_t bufferQueueId,
584 int32_t slotId,
585 int64_t timestampNs) override {
586 // TODO: implement
587 (void)bufferQueueId;
588 (void)slotId;
589 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800590 }
591
592 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800593 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800594 sp<CCodec> codec(mCodec.promote());
595 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800596 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800597 }
598 }
599
600private:
601 wp<CCodec> mCodec;
602};
603
604// CCodecCallbackImpl
605
606class CCodecCallbackImpl : public CCodecCallback {
607public:
608 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
609 ~CCodecCallbackImpl() override = default;
610
611 void onError(status_t err, enum ActionCode actionCode) override {
612 mCodec->mCallback->onError(err, actionCode);
613 }
614
615 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
616 mCodec->mCallback->onOutputFramesRendered(
617 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
618 }
619
Pawin Vongmasa36653902018-11-15 00:10:25 -0800620 void onOutputBuffersChanged() override {
621 mCodec->mCallback->onOutputBuffersChanged();
622 }
623
624private:
625 CCodec *mCodec;
626};
627
628// CCodec
629
630CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700631 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
632 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800633}
634
635CCodec::~CCodec() {
636}
637
638std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
639 return mChannel;
640}
641
642status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
643 status_t err = job();
644 if (err != C2_OK) {
645 mCallback->onError(err, ACTION_CODE_FATAL);
646 }
647 return err;
648}
649
650void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
651 auto setAllocating = [this] {
652 Mutexed<State>::Locked state(mState);
653 if (state->get() != RELEASED) {
654 return INVALID_OPERATION;
655 }
656 state->set(ALLOCATING);
657 return OK;
658 };
659 if (tryAndReportOnError(setAllocating) != OK) {
660 return;
661 }
662
663 sp<RefBase> codecInfo;
664 CHECK(msg->findObject("codecInfo", &codecInfo));
665 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
666
667 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
668 allocMsg->setObject("codecInfo", codecInfo);
669 allocMsg->post();
670}
671
672void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
673 if (codecInfo == nullptr) {
674 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
675 return;
676 }
677 ALOGD("allocate(%s)", codecInfo->getCodecName());
678 mClientListener.reset(new ClientListener(this));
679
680 AString componentName = codecInfo->getCodecName();
681 std::shared_ptr<Codec2Client> client;
682
683 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700684 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800685 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800686 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800687 SetPreferredCodec2ComponentStore(
688 std::make_shared<Codec2ClientInterfaceWrapper>(client));
689 }
690
691 std::shared_ptr<Codec2Client::Component> comp =
692 Codec2Client::CreateComponentByName(
693 componentName.c_str(),
694 mClientListener,
695 &client);
696 if (!comp) {
697 ALOGE("Failed Create component: %s", componentName.c_str());
698 Mutexed<State>::Locked state(mState);
699 state->set(RELEASED);
700 state.unlock();
701 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
702 state.lock();
703 return;
704 }
705 ALOGI("Created component [%s]", componentName.c_str());
706 mChannel->setComponent(comp);
707 auto setAllocated = [this, comp, client] {
708 Mutexed<State>::Locked state(mState);
709 if (state->get() != ALLOCATING) {
710 state->set(RELEASED);
711 return UNKNOWN_ERROR;
712 }
713 state->set(ALLOCATED);
714 state->comp = comp;
715 mClient = client;
716 return OK;
717 };
718 if (tryAndReportOnError(setAllocated) != OK) {
719 return;
720 }
721
722 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700723 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
724 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800725 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800726 if (err != OK) {
727 ALOGW("Failed to initialize configuration support");
728 // TODO: report error once we complete implementation.
729 }
730 config->queryConfiguration(comp);
731
732 mCallback->onComponentAllocated(componentName.c_str());
733}
734
735void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
736 auto checkAllocated = [this] {
737 Mutexed<State>::Locked state(mState);
738 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
739 };
740 if (tryAndReportOnError(checkAllocated) != OK) {
741 return;
742 }
743
744 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
745 msg->setMessage("format", format);
746 msg->post();
747}
748
749void CCodec::configure(const sp<AMessage> &msg) {
750 std::shared_ptr<Codec2Client::Component> comp;
751 auto checkAllocated = [this, &comp] {
752 Mutexed<State>::Locked state(mState);
753 if (state->get() != ALLOCATED) {
754 state->set(RELEASED);
755 return UNKNOWN_ERROR;
756 }
757 comp = state->comp;
758 return OK;
759 };
760 if (tryAndReportOnError(checkAllocated) != OK) {
761 return;
762 }
763
764 auto doConfig = [msg, comp, this]() -> status_t {
765 AString mime;
766 if (!msg->findString("mime", &mime)) {
767 return BAD_VALUE;
768 }
769
770 int32_t encoder;
771 if (!msg->findInt32("encoder", &encoder)) {
772 encoder = false;
773 }
774
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800775 int32_t flags;
776 if (!msg->findInt32("flags", &flags)) {
777 return BAD_VALUE;
778 }
779
Pawin Vongmasa36653902018-11-15 00:10:25 -0800780 // TODO: read from intf()
781 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
782 return UNKNOWN_ERROR;
783 }
784
785 int32_t storeMeta;
786 if (encoder
787 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
788 && storeMeta != kMetadataBufferTypeInvalid) {
789 if (storeMeta != kMetadataBufferTypeANWBuffer) {
790 ALOGD("Only ANW buffers are supported for legacy metadata mode");
791 return BAD_VALUE;
792 }
793 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
794 }
795
796 sp<RefBase> obj;
797 sp<Surface> surface;
798 if (msg->findObject("native-window", &obj)) {
799 surface = static_cast<Surface *>(obj.get());
800 setSurface(surface);
801 }
802
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700803 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
804 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800805 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800806 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
807 ALOGD("[%s] buffers are %sbound to CCodec for this session",
808 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800809
Wonsik Kim1114eea2019-02-25 14:35:24 -0800810 // Enforce required parameters
811 int32_t i32;
812 float flt;
813 if (config->mDomain & Config::IS_AUDIO) {
814 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
815 ALOGD("sample rate is missing, which is required for audio components.");
816 return BAD_VALUE;
817 }
818 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
819 ALOGD("channel count is missing, which is required for audio components.");
820 return BAD_VALUE;
821 }
822 if ((config->mDomain & Config::IS_ENCODER)
823 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
824 && !msg->findInt32(KEY_BIT_RATE, &i32)
825 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
826 ALOGD("bitrate is missing, which is required for audio encoders.");
827 return BAD_VALUE;
828 }
829 }
830 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
831 if (!msg->findInt32(KEY_WIDTH, &i32)) {
832 ALOGD("width is missing, which is required for image/video components.");
833 return BAD_VALUE;
834 }
835 if (!msg->findInt32(KEY_HEIGHT, &i32)) {
836 ALOGD("height is missing, which is required for image/video components.");
837 return BAD_VALUE;
838 }
839 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700840 int32_t mode = BITRATE_MODE_VBR;
841 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700842 if (!msg->findInt32(KEY_QUALITY, &i32)) {
843 ALOGD("quality is missing, which is required for video encoders in CQ.");
844 return BAD_VALUE;
845 }
846 } else {
847 if (!msg->findInt32(KEY_BIT_RATE, &i32)
848 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
849 ALOGD("bitrate is missing, which is required for video encoders.");
850 return BAD_VALUE;
851 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800852 }
853 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
854 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
855 ALOGD("I frame interval is missing, which is required for video encoders.");
856 return BAD_VALUE;
857 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700858 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
859 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
860 ALOGD("frame rate is missing, which is required for video encoders.");
861 return BAD_VALUE;
862 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800863 }
864 }
865
Pawin Vongmasa36653902018-11-15 00:10:25 -0800866 /*
867 * Handle input surface configuration
868 */
869 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
870 && (config->mDomain & Config::IS_ENCODER)) {
871 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
872 {
873 config->mISConfig->mMinFps = 0;
874 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800875 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800876 config->mISConfig->mMinFps = 1e6 / value;
877 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700878 if (!msg->findFloat(
879 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
880 config->mISConfig->mMaxFps = -1;
881 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800882 config->mISConfig->mMinAdjustedFps = 0;
883 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800884 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800885 if (value < 0 && value >= INT32_MIN) {
886 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700887 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800888 } else if (value > 0 && value <= INT32_MAX) {
889 config->mISConfig->mMinAdjustedFps = 1e6 / value;
890 }
891 }
892 }
893
894 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700895 bool captureFpsFound = false;
896 double timeLapseFps;
897 float captureRate;
898 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
899 config->mISConfig->mCaptureFps = timeLapseFps;
900 captureFpsFound = true;
901 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
902 config->mISConfig->mCaptureFps = captureRate;
903 captureFpsFound = true;
904 }
905 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800906 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
907 }
908 }
909
910 {
911 config->mISConfig->mSuspended = false;
912 config->mISConfig->mSuspendAtUs = -1;
913 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800914 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800915 config->mISConfig->mSuspended = true;
916 }
917 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700918 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800919 }
920
921 /*
922 * Handle desired color format.
923 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700924 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800925 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700926 int32_t format = 0;
927 // Query vendor format for Flexible YUV
928 std::vector<std::unique_ptr<C2Param>> heapParams;
929 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
930 if (mClient->query(
931 {},
932 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
933 C2_MAY_BLOCK,
934 &heapParams) == C2_OK
935 && heapParams.size() == 1u) {
936 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
937 heapParams[0].get());
938 } else {
939 pixelFormatInfo = nullptr;
940 }
941 std::optional<uint32_t> flexPixelFormat{};
942 std::optional<uint32_t> flexPlanarPixelFormat{};
943 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
944 if (pixelFormatInfo && *pixelFormatInfo) {
945 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
946 const C2FlexiblePixelFormatDescriptorStruct &desc =
947 pixelFormatInfo->m.values[i];
948 if (desc.bitDepth != 8
949 || desc.subsampling != C2Color::YUV_420
950 // TODO(b/180076105): some device report wrong layout
951 // || desc.layout == C2Color::INTERLEAVED_PACKED
952 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
953 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
954 continue;
955 }
956 if (!flexPixelFormat) {
957 flexPixelFormat = desc.pixelFormat;
958 }
959 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
960 flexPlanarPixelFormat = desc.pixelFormat;
961 }
962 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
963 flexSemiPlanarPixelFormat = desc.pixelFormat;
964 }
965 }
966 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800967 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700968 // Also handle default color format (encoders require color format, so this is only
969 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -0800970 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700971 if (surface == nullptr) {
972 format = flexPixelFormat.value_or(COLOR_FormatYUV420Flexible);
973 } else {
974 format = COLOR_FormatSurface;
975 }
976 defaultColorFormat = format;
977 }
978 } else {
979 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
980 switch (format) {
981 case COLOR_FormatYUV420Flexible:
982 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
983 break;
984 case COLOR_FormatYUV420Planar:
985 case COLOR_FormatYUV420PackedPlanar:
986 format = flexPlanarPixelFormat.value_or(
987 flexPixelFormat.value_or(format));
988 break;
989 case COLOR_FormatYUV420SemiPlanar:
990 case COLOR_FormatYUV420PackedSemiPlanar:
991 format = flexSemiPlanarPixelFormat.value_or(
992 flexPixelFormat.value_or(format));
993 break;
994 default:
995 // No-op
996 break;
997 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800998 }
999 }
1000
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001001 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001002 msg->setInt32("android._color-format", format);
1003 }
1004 }
1005
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001006 int32_t subscribeToAllVendorParams;
1007 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1008 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1009 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1010 }
1011 }
1012
Pawin Vongmasa36653902018-11-15 00:10:25 -08001013 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001014 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1015 // the behavior here.
1016 sp<AMessage> sdkParams = msg;
1017 int32_t videoBitrate;
1018 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1019 sdkParams = msg->dup();
1020 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1021 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001022 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001023 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001024 if (err != OK) {
1025 ALOGW("failed to convert configuration to c2 params");
1026 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001027
1028 int32_t maxBframes = 0;
1029 if ((config->mDomain & Config::IS_ENCODER)
1030 && (config->mDomain & Config::IS_VIDEO)
1031 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1032 && maxBframes > 0) {
1033 std::unique_ptr<C2StreamGopTuning::output> gop =
1034 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1035 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1036 gop->m.values[1] = {
1037 C2Config::picture_type_t(P_FRAME | B_FRAME),
1038 uint32_t(maxBframes)
1039 };
1040 configUpdate.push_back(std::move(gop));
1041 }
1042
Pawin Vongmasa36653902018-11-15 00:10:25 -08001043 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1044 if (err != OK) {
1045 ALOGW("failed to configure c2 params");
1046 return err;
1047 }
1048
1049 std::vector<std::unique_ptr<C2Param>> params;
1050 C2StreamUsageTuning::input usage(0u, 0u);
1051 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001052 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001053
Wonsik Kim58d83332021-02-07 22:19:56 -08001054 C2Param::Index colorAspectsRequestIndex =
1055 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001056 std::initializer_list<C2Param::Index> indices {
Wonsik Kim58d83332021-02-07 22:19:56 -08001057 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001058 };
1059 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001060 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001061 indices,
1062 C2_DONT_BLOCK,
1063 &params);
1064 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1065 ALOGE("Failed to query component interface: %d", c2err);
1066 return UNKNOWN_ERROR;
1067 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001068 if (usage) {
1069 if (usage.value & C2MemoryUsage::CPU_READ) {
1070 config->mInputFormat->setInt32("using-sw-read-often", true);
1071 }
1072 if (config->mISConfig) {
1073 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1074 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1075 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001076 }
1077
1078 // NOTE: we don't blindly use client specified input size if specified as clients
1079 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1080 // client specified size is only used to ask for bigger buffers than component suggested
1081 // size.
1082 int32_t clientInputSize = 0;
1083 bool clientSpecifiedInputSize =
1084 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1085 // TEMP: enforce minimum buffer size of 1MB for video decoders
1086 // and 16K / 4K for audio encoders/decoders
1087 if (maxInputSize.value == 0) {
1088 if (config->mDomain & Config::IS_AUDIO) {
1089 maxInputSize.value = encoder ? 16384 : 4096;
1090 } else if (!encoder) {
1091 maxInputSize.value = 1048576u;
1092 }
1093 }
1094
1095 // verify that CSD fits into this size (if defined)
1096 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1097 sp<ABuffer> csd;
1098 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1099 if (csd && csd->size() > maxInputSize.value) {
1100 maxInputSize.value = csd->size();
1101 }
1102 }
1103 }
1104
1105 // TODO: do this based on component requiring linear allocator for input
1106 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1107 if (clientSpecifiedInputSize) {
1108 // Warn that we're overriding client's max input size if necessary.
1109 if ((uint32_t)clientInputSize < maxInputSize.value) {
1110 ALOGD("client requested max input size %d, which is smaller than "
1111 "what component recommended (%u); overriding with component "
1112 "recommendation.", clientInputSize, maxInputSize.value);
1113 ALOGW("This behavior is subject to change. It is recommended that "
1114 "app developers double check whether the requested "
1115 "max input size is in reasonable range.");
1116 } else {
1117 maxInputSize.value = clientInputSize;
1118 }
1119 }
1120 // Pass max input size on input format to the buffer channel (if supplied by the
1121 // component or by a default)
1122 if (maxInputSize.value) {
1123 config->mInputFormat->setInt32(
1124 KEY_MAX_INPUT_SIZE,
1125 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1126 }
1127 }
1128
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001129 int32_t clientPrepend;
1130 if ((config->mDomain & Config::IS_VIDEO)
1131 && (config->mDomain & Config::IS_ENCODER)
1132 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1133 && clientPrepend
1134 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1135 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1136 return BAD_VALUE;
1137 }
1138
Pawin Vongmasa36653902018-11-15 00:10:25 -08001139 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1140 // propagate HDR static info to output format for both encoders and decoders
1141 // if component supports this info, we will update from component, but only the raw port,
1142 // so don't propagate if component already filled it in.
1143 sp<ABuffer> hdrInfo;
1144 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1145 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1146 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1147 }
1148
1149 // Set desired color format from configuration parameter
1150 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001151 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1152 format = defaultColorFormat;
1153 }
1154 if (config->mDomain & Config::IS_ENCODER) {
1155 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
1156 if (msg->findInt32("android._color-format", &format)) {
1157 config->mInputFormat->setInt32("android._color-format", format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001158 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001159 } else {
1160 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001161 }
1162 }
1163
1164 // propagate encoder delay and padding to output format
1165 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1166 int delay = 0;
1167 if (msg->findInt32("encoder-delay", &delay)) {
1168 config->mOutputFormat->setInt32("encoder-delay", delay);
1169 }
1170 int padding = 0;
1171 if (msg->findInt32("encoder-padding", &padding)) {
1172 config->mOutputFormat->setInt32("encoder-padding", padding);
1173 }
1174 }
1175
1176 // set channel-mask
1177 if (config->mDomain & Config::IS_AUDIO) {
1178 int32_t mask;
1179 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1180 if (config->mDomain & Config::IS_ENCODER) {
1181 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1182 } else {
1183 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1184 }
1185 }
1186 }
1187
Wonsik Kim58d83332021-02-07 22:19:56 -08001188 std::unique_ptr<C2Param> colorTransferRequestParam;
1189 for (std::unique_ptr<C2Param> &param : params) {
1190 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1191 ALOGI("found color transfer request param");
1192 colorTransferRequestParam = std::move(param);
1193 }
1194 }
1195 int32_t colorTransferRequest = 0;
1196 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1197 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1198 colorTransferRequest = 0;
1199 }
1200
1201 if (colorTransferRequest != 0) {
1202 if (colorTransferRequestParam && *colorTransferRequestParam) {
1203 C2StreamColorAspectsInfo::output *info =
1204 static_cast<C2StreamColorAspectsInfo::output *>(
1205 colorTransferRequestParam.get());
1206 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1207 colorTransferRequest = 0;
1208 }
1209 } else {
1210 colorTransferRequest = 0;
1211 }
1212 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1213 }
1214
Pawin Vongmasa36653902018-11-15 00:10:25 -08001215 ALOGD("setup formats input: %s and output: %s",
1216 config->mInputFormat->debugString().c_str(),
1217 config->mOutputFormat->debugString().c_str());
1218 return OK;
1219 };
1220 if (tryAndReportOnError(doConfig) != OK) {
1221 return;
1222 }
1223
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001224 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1225 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001226
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001227 config->queryConfiguration(comp);
1228
Pawin Vongmasa36653902018-11-15 00:10:25 -08001229 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1230}
1231
1232void CCodec::initiateCreateInputSurface() {
1233 status_t err = [this] {
1234 Mutexed<State>::Locked state(mState);
1235 if (state->get() != ALLOCATED) {
1236 return UNKNOWN_ERROR;
1237 }
1238 // TODO: read it from intf() properly.
1239 if (state->comp->getName().find("encoder") == std::string::npos) {
1240 return INVALID_OPERATION;
1241 }
1242 return OK;
1243 }();
1244 if (err != OK) {
1245 mCallback->onInputSurfaceCreationFailed(err);
1246 return;
1247 }
1248
1249 (new AMessage(kWhatCreateInputSurface, this))->post();
1250}
1251
Lajos Molnar47118272019-01-31 16:28:04 -08001252sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1253 using namespace android::hardware::media::omx::V1_0;
1254 using namespace android::hardware::media::omx::V1_0::utils;
1255 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1256 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1257 android::sp<IOmx> omx = IOmx::getService();
1258 typedef android::hardware::graphics::bufferqueue::V1_0::
1259 IGraphicBufferProducer HGraphicBufferProducer;
1260 typedef android::hardware::media::omx::V1_0::
1261 IGraphicBufferSource HGraphicBufferSource;
1262 OmxStatus s;
1263 android::sp<HGraphicBufferProducer> gbp;
1264 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001265
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001266 using ::android::hardware::Return;
1267 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001268 [&s, &gbp, &gbs](
1269 OmxStatus status,
1270 const android::sp<HGraphicBufferProducer>& producer,
1271 const android::sp<HGraphicBufferSource>& source) {
1272 s = status;
1273 gbp = producer;
1274 gbs = source;
1275 });
1276 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001277 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001278 }
1279
1280 return nullptr;
1281}
1282
1283sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1284 sp<PersistentSurface> surface(CreateInputSurface());
1285
1286 if (surface == nullptr) {
1287 surface = CreateOmxInputSurface();
1288 }
1289
1290 return surface;
1291}
1292
Pawin Vongmasa36653902018-11-15 00:10:25 -08001293void CCodec::createInputSurface() {
1294 status_t err;
1295 sp<IGraphicBufferProducer> bufferProducer;
1296
1297 sp<AMessage> inputFormat;
1298 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001299 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001300 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001301 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1302 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001303 inputFormat = config->mInputFormat;
1304 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001305 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001306 }
1307
Lajos Molnar47118272019-01-31 16:28:04 -08001308 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001309 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1310 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1311 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001312
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001313 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001314 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1315 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001316 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001317 inputSurface));
1318 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001319 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001320 int32_t width = 0;
1321 (void)outputFormat->findInt32("width", &width);
1322 int32_t height = 0;
1323 (void)outputFormat->findInt32("height", &height);
1324 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001325 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001326 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001327 } else {
1328 ALOGE("Corrupted input surface");
1329 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1330 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001331 }
1332
1333 if (err != OK) {
1334 ALOGE("Failed to set up input surface: %d", err);
1335 mCallback->onInputSurfaceCreationFailed(err);
1336 return;
1337 }
1338
1339 mCallback->onInputSurfaceCreated(
1340 inputFormat,
1341 outputFormat,
1342 new BufferProducerWrapper(bufferProducer));
1343}
1344
1345status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001346 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1347 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001348 config->mUsingSurface = true;
1349
1350 // we are now using surface - apply default color aspects to input format - as well as
1351 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001352 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001353 ALOGD("input format %s to %s",
1354 inputFormatChanged ? "changed" : "unchanged",
1355 config->mInputFormat->debugString().c_str());
1356
1357 // configure dataspace
1358 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1359 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1360 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1361 surface->setDataSpace(dataSpace);
1362
1363 status_t err = mChannel->setInputSurface(surface);
1364 if (err != OK) {
1365 // undo input format update
1366 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001367 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001368 return err;
1369 }
1370 config->mInputSurface = surface;
1371
1372 if (config->mISConfig) {
1373 surface->configure(*config->mISConfig);
1374 } else {
1375 ALOGD("ISConfig: no configuration");
1376 }
1377
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001378 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001379}
1380
1381void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1382 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1383 msg->setObject("surface", surface);
1384 msg->post();
1385}
1386
1387void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1388 sp<AMessage> inputFormat;
1389 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001390 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001391 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001392 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1393 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001394 inputFormat = config->mInputFormat;
1395 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001396 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001397 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001398 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1399 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1400 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1401 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001402 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1403 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1404 if (err != OK) {
1405 ALOGE("Failed to set up input surface: %d", err);
1406 mCallback->onInputSurfaceDeclined(err);
1407 return;
1408 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001409 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001410 int32_t width = 0;
1411 (void)outputFormat->findInt32("width", &width);
1412 int32_t height = 0;
1413 (void)outputFormat->findInt32("height", &height);
1414 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001415 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001416 if (err != OK) {
1417 ALOGE("Failed to set up input surface: %d", err);
1418 mCallback->onInputSurfaceDeclined(err);
1419 return;
1420 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001421 } else {
1422 ALOGE("Failed to set input surface: Corrupted surface.");
1423 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1424 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001425 }
1426 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1427}
1428
1429void CCodec::initiateStart() {
1430 auto setStarting = [this] {
1431 Mutexed<State>::Locked state(mState);
1432 if (state->get() != ALLOCATED) {
1433 return UNKNOWN_ERROR;
1434 }
1435 state->set(STARTING);
1436 return OK;
1437 };
1438 if (tryAndReportOnError(setStarting) != OK) {
1439 return;
1440 }
1441
1442 (new AMessage(kWhatStart, this))->post();
1443}
1444
1445void CCodec::start() {
1446 std::shared_ptr<Codec2Client::Component> comp;
1447 auto checkStarting = [this, &comp] {
1448 Mutexed<State>::Locked state(mState);
1449 if (state->get() != STARTING) {
1450 return UNKNOWN_ERROR;
1451 }
1452 comp = state->comp;
1453 return OK;
1454 };
1455 if (tryAndReportOnError(checkStarting) != OK) {
1456 return;
1457 }
1458
1459 c2_status_t err = comp->start();
1460 if (err != C2_OK) {
1461 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1462 ACTION_CODE_FATAL);
1463 return;
1464 }
1465 sp<AMessage> inputFormat;
1466 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001467 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001468 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001469 {
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 Vongmasa36653902018-11-15 00:10:25 -08001472 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001473 // start triggers format dup
1474 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001475 if (config->mInputSurface) {
1476 err2 = config->mInputSurface->start();
1477 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001478 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001479 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001480 if (err2 != OK) {
1481 mCallback->onError(err2, ACTION_CODE_FATAL);
1482 return;
1483 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001484 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001485 if (err2 != OK) {
1486 mCallback->onError(err2, ACTION_CODE_FATAL);
1487 return;
1488 }
1489
1490 auto setRunning = [this] {
1491 Mutexed<State>::Locked state(mState);
1492 if (state->get() != STARTING) {
1493 return UNKNOWN_ERROR;
1494 }
1495 state->set(RUNNING);
1496 return OK;
1497 };
1498 if (tryAndReportOnError(setRunning) != OK) {
1499 return;
1500 }
1501 mCallback->onStartCompleted();
1502
1503 (void)mChannel->requestInitialInputBuffers();
1504}
1505
1506void CCodec::initiateShutdown(bool keepComponentAllocated) {
1507 if (keepComponentAllocated) {
1508 initiateStop();
1509 } else {
1510 initiateRelease();
1511 }
1512}
1513
1514void CCodec::initiateStop() {
1515 {
1516 Mutexed<State>::Locked state(mState);
1517 if (state->get() == ALLOCATED
1518 || state->get() == RELEASED
1519 || state->get() == STOPPING
1520 || state->get() == RELEASING) {
1521 // We're already stopped, released, or doing it right now.
1522 state.unlock();
1523 mCallback->onStopCompleted();
1524 state.lock();
1525 return;
1526 }
1527 state->set(STOPPING);
1528 }
1529
Wonsik Kim936a89c2020-05-08 16:07:50 -07001530 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001531 (new AMessage(kWhatStop, this))->post();
1532}
1533
1534void CCodec::stop() {
1535 std::shared_ptr<Codec2Client::Component> comp;
1536 {
1537 Mutexed<State>::Locked state(mState);
1538 if (state->get() == RELEASING) {
1539 state.unlock();
1540 // We're already stopped or release is in progress.
1541 mCallback->onStopCompleted();
1542 state.lock();
1543 return;
1544 } else if (state->get() != STOPPING) {
1545 state.unlock();
1546 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1547 state.lock();
1548 return;
1549 }
1550 comp = state->comp;
1551 }
1552 status_t err = comp->stop();
1553 if (err != C2_OK) {
1554 // TODO: convert err into status_t
1555 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1556 }
1557
1558 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001559 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1560 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001561 if (config->mInputSurface) {
1562 config->mInputSurface->disconnect();
1563 config->mInputSurface = nullptr;
1564 }
1565 }
1566 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001567 Mutexed<State>::Locked state(mState);
1568 if (state->get() == STOPPING) {
1569 state->set(ALLOCATED);
1570 }
1571 }
1572 mCallback->onStopCompleted();
1573}
1574
1575void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001576 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001577 {
1578 Mutexed<State>::Locked state(mState);
1579 if (state->get() == RELEASED || state->get() == RELEASING) {
1580 // We're already released or doing it right now.
1581 if (sendCallback) {
1582 state.unlock();
1583 mCallback->onReleaseCompleted();
1584 state.lock();
1585 }
1586 return;
1587 }
1588 if (state->get() == ALLOCATING) {
1589 state->set(RELEASING);
1590 // With the altered state allocate() would fail and clean up.
1591 if (sendCallback) {
1592 state.unlock();
1593 mCallback->onReleaseCompleted();
1594 state.lock();
1595 }
1596 return;
1597 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001598 if (state->get() == STARTING
1599 || state->get() == RUNNING
1600 || state->get() == STOPPING) {
1601 // Input surface may have been started, so clean up is needed.
1602 clearInputSurfaceIfNeeded = true;
1603 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001604 state->set(RELEASING);
1605 }
1606
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001607 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001608 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1609 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001610 if (config->mInputSurface) {
1611 config->mInputSurface->disconnect();
1612 config->mInputSurface = nullptr;
1613 }
1614 }
1615
Wonsik Kim936a89c2020-05-08 16:07:50 -07001616 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001617 // thiz holds strong ref to this while the thread is running.
1618 sp<CCodec> thiz(this);
1619 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1620}
1621
1622void CCodec::release(bool sendCallback) {
1623 std::shared_ptr<Codec2Client::Component> comp;
1624 {
1625 Mutexed<State>::Locked state(mState);
1626 if (state->get() == RELEASED) {
1627 if (sendCallback) {
1628 state.unlock();
1629 mCallback->onReleaseCompleted();
1630 state.lock();
1631 }
1632 return;
1633 }
1634 comp = state->comp;
1635 }
1636 comp->release();
1637
1638 {
1639 Mutexed<State>::Locked state(mState);
1640 state->set(RELEASED);
1641 state->comp.reset();
1642 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001643 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001644 if (sendCallback) {
1645 mCallback->onReleaseCompleted();
1646 }
1647}
1648
1649status_t CCodec::setSurface(const sp<Surface> &surface) {
1650 return mChannel->setSurface(surface);
1651}
1652
1653void CCodec::signalFlush() {
1654 status_t err = [this] {
1655 Mutexed<State>::Locked state(mState);
1656 if (state->get() == FLUSHED) {
1657 return ALREADY_EXISTS;
1658 }
1659 if (state->get() != RUNNING) {
1660 return UNKNOWN_ERROR;
1661 }
1662 state->set(FLUSHING);
1663 return OK;
1664 }();
1665 switch (err) {
1666 case ALREADY_EXISTS:
1667 mCallback->onFlushCompleted();
1668 return;
1669 case OK:
1670 break;
1671 default:
1672 mCallback->onError(err, ACTION_CODE_FATAL);
1673 return;
1674 }
1675
1676 mChannel->stop();
1677 (new AMessage(kWhatFlush, this))->post();
1678}
1679
1680void CCodec::flush() {
1681 std::shared_ptr<Codec2Client::Component> comp;
1682 auto checkFlushing = [this, &comp] {
1683 Mutexed<State>::Locked state(mState);
1684 if (state->get() != FLUSHING) {
1685 return UNKNOWN_ERROR;
1686 }
1687 comp = state->comp;
1688 return OK;
1689 };
1690 if (tryAndReportOnError(checkFlushing) != OK) {
1691 return;
1692 }
1693
1694 std::list<std::unique_ptr<C2Work>> flushedWork;
1695 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1696 {
1697 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1698 flushedWork.splice(flushedWork.end(), *queue);
1699 }
1700 if (err != C2_OK) {
1701 // TODO: convert err into status_t
1702 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1703 }
1704
1705 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001706
1707 {
1708 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001709 if (state->get() == FLUSHING) {
1710 state->set(FLUSHED);
1711 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001712 }
1713 mCallback->onFlushCompleted();
1714}
1715
1716void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001717 std::shared_ptr<Codec2Client::Component> comp;
1718 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001719 Mutexed<State>::Locked state(mState);
1720 if (state->get() != FLUSHED) {
1721 return UNKNOWN_ERROR;
1722 }
1723 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001724 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001725 return OK;
1726 };
1727 if (tryAndReportOnError(setResuming) != OK) {
1728 return;
1729 }
1730
Wonsik Kime75a5da2020-02-14 17:29:03 -08001731 {
1732 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1733 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001734 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001735 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001736 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001737 }
1738
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001739 (void)mChannel->start(nullptr, nullptr, [&]{
1740 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1741 const std::unique_ptr<Config> &config = *configLocked;
1742 return config->mBuffersBoundToCodec;
1743 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001744
1745 {
1746 Mutexed<State>::Locked state(mState);
1747 if (state->get() != RESUMING) {
1748 state.unlock();
1749 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1750 state.lock();
1751 return;
1752 }
1753 state->set(RUNNING);
1754 }
1755
1756 (void)mChannel->requestInitialInputBuffers();
1757}
1758
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001759void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001760 std::shared_ptr<Codec2Client::Component> comp;
1761 auto checkState = [this, &comp] {
1762 Mutexed<State>::Locked state(mState);
1763 if (state->get() == RELEASED) {
1764 return INVALID_OPERATION;
1765 }
1766 comp = state->comp;
1767 return OK;
1768 };
1769 if (tryAndReportOnError(checkState) != OK) {
1770 return;
1771 }
1772
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001773 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1774 // the behavior here.
1775 sp<AMessage> params = msg;
1776 int32_t bitrate;
1777 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1778 params = msg->dup();
1779 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1780 }
1781
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001782 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1783 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001784
1785 /**
1786 * Handle input surface parameters
1787 */
1788 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001789 && (config->mDomain & Config::IS_ENCODER)
1790 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001791 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001792
1793 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1794 config->mISConfig->mStopped = false;
1795 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1796 config->mISConfig->mStopped = true;
1797 }
1798
1799 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001800 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001801 config->mISConfig->mSuspended = value;
1802 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001803 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001804 }
1805
1806 (void)config->mInputSurface->configure(*config->mISConfig);
1807 if (config->mISConfig->mStopped) {
1808 config->mInputFormat->setInt64(
1809 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1810 }
1811 }
1812
1813 std::vector<std::unique_ptr<C2Param>> configUpdate;
1814 (void)config->getConfigUpdateFromSdkParams(
1815 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1816 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1817 // Parameter synchronization is not defined when using input surface. For now, route
1818 // these directly to the component.
1819 if (config->mInputSurface == nullptr
1820 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1821 || comp->getName().find("c2.android.") == 0)) {
1822 mChannel->setParameters(configUpdate);
1823 } else {
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001824 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001825 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001826 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001827 }
1828}
1829
1830void CCodec::signalEndOfInputStream() {
1831 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1832}
1833
1834void CCodec::signalRequestIDRFrame() {
1835 std::shared_ptr<Codec2Client::Component> comp;
1836 {
1837 Mutexed<State>::Locked state(mState);
1838 if (state->get() == RELEASED) {
1839 ALOGD("no IDR request sent since component is released");
1840 return;
1841 }
1842 comp = state->comp;
1843 }
1844 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001845 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1846 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001847 std::vector<std::unique_ptr<C2Param>> params;
1848 params.push_back(
1849 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1850 config->setParameters(comp, params, C2_MAY_BLOCK);
1851}
1852
Wonsik Kimab34ed62019-01-31 15:28:46 -08001853void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001854 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001855 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1856 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001857 }
1858 (new AMessage(kWhatWorkDone, this))->post();
1859}
1860
Wonsik Kimab34ed62019-01-31 15:28:46 -08001861void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1862 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001863 if (arrayIndex == 0) {
1864 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001865 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1866 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001867 if (config->mInputSurface) {
1868 config->mInputSurface->onInputBufferDone(frameIndex);
1869 }
1870 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001871}
1872
1873void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1874 TimePoint now = std::chrono::steady_clock::now();
1875 CCodecWatchdog::getInstance()->watch(this);
1876 switch (msg->what()) {
1877 case kWhatAllocate: {
1878 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001879 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001880 sp<RefBase> obj;
1881 CHECK(msg->findObject("codecInfo", &obj));
1882 allocate((MediaCodecInfo *)obj.get());
1883 break;
1884 }
1885 case kWhatConfigure: {
1886 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001887 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001888 sp<AMessage> format;
1889 CHECK(msg->findMessage("format", &format));
1890 configure(format);
1891 break;
1892 }
1893 case kWhatStart: {
1894 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001895 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001896 start();
1897 break;
1898 }
1899 case kWhatStop: {
1900 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001901 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001902 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001903 break;
1904 }
1905 case kWhatFlush: {
1906 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001907 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001908 flush();
1909 break;
1910 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001911 case kWhatRelease: {
1912 mChannel->release();
1913 mClient.reset();
1914 mClientListener.reset();
1915 break;
1916 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001917 case kWhatCreateInputSurface: {
1918 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001919 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001920 createInputSurface();
1921 break;
1922 }
1923 case kWhatSetInputSurface: {
1924 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001925 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001926 sp<RefBase> obj;
1927 CHECK(msg->findObject("surface", &obj));
1928 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1929 setInputSurface(surface);
1930 break;
1931 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001932 case kWhatWorkDone: {
1933 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001934 bool shouldPost = false;
1935 {
1936 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1937 if (queue->empty()) {
1938 break;
1939 }
1940 work.swap(queue->front());
1941 queue->pop_front();
1942 shouldPost = !queue->empty();
1943 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001944 if (shouldPost) {
1945 (new AMessage(kWhatWorkDone, this))->post();
1946 }
1947
Pawin Vongmasa36653902018-11-15 00:10:25 -08001948 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001949 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1950 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001951 Config::Watcher<C2StreamInitDataInfo::output> initData =
1952 config->watch<C2StreamInitDataInfo::output>();
1953 if (!work->worklets.empty()
1954 && (work->worklets.front()->output.flags
1955 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1956
1957 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001958 std::vector<std::unique_ptr<C2Param>> updates;
1959 for (const std::unique_ptr<C2Param> &param
1960 : work->worklets.front()->output.configUpdate) {
1961 updates.push_back(C2Param::Copy(*param));
1962 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001963 unsigned stream = 0;
1964 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1965 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1966 // move all info into output-stream #0 domain
1967 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1968 }
George Burgess IVc813a592020-02-22 22:54:44 -08001969
1970 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
1971 // for now only do the first block
1972 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001973 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1974 // block.crop().left, block.crop().top,
1975 // block.crop().width, block.crop().height,
1976 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08001977 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08001978 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1979 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07001980 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001981 }
1982 ++stream;
1983 }
1984
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001985 sp<AMessage> outputFormat = config->mOutputFormat;
1986 config->updateConfiguration(updates, config->mOutputDomain);
1987 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001988
1989 // copy standard infos to graphic buffers if not already present (otherwise, we
1990 // may overwrite the actual intermediate value with a final value)
1991 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07001992 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001993 C2StreamRotationInfo::output::PARAM_TYPE,
1994 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1995 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1996 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001997 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001998 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1999 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2000 };
2001 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2002 if (buf->data().graphicBlocks().size()) {
2003 for (C2Param::Index ix : stdGfxInfos) {
2004 if (!buf->hasInfo(ix)) {
2005 const C2Param *param =
2006 config->getConfigParameterValue(ix.withStream(stream));
2007 if (param) {
2008 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2009 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2010 }
2011 }
2012 }
2013 }
2014 ++stream;
2015 }
2016 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002017 if (config->mInputSurface) {
2018 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2019 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002020 mChannel->onWorkDone(
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002021 std::move(work), config->mOutputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002022 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002023 break;
2024 }
2025 case kWhatWatch: {
2026 // watch message already posted; no-op.
2027 break;
2028 }
2029 default: {
2030 ALOGE("unrecognized message");
2031 break;
2032 }
2033 }
2034 setDeadline(TimePoint::max(), 0ms, "none");
2035}
2036
2037void CCodec::setDeadline(
2038 const TimePoint &now,
2039 const std::chrono::milliseconds &timeout,
2040 const char *name) {
2041 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2042 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2043 deadline->set(now + (timeout * mult), name);
2044}
2045
2046void CCodec::initiateReleaseIfStuck() {
2047 std::string name;
2048 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002049 {
2050 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002051 if (deadline->get() < std::chrono::steady_clock::now()) {
2052 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002053 }
2054 if (deadline->get() != TimePoint::max()) {
2055 pendingDeadline = true;
2056 }
2057 }
2058 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002059 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2060 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2061 if (elapsed >= kWorkDurationThreshold) {
2062 name = "queue";
2063 }
2064 if (elapsed > 0s) {
2065 pendingDeadline = true;
2066 }
2067 }
2068 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002069 // We're not stuck.
2070 if (pendingDeadline) {
2071 // If we are not stuck yet but still has deadline coming up,
2072 // post watch message to check back later.
2073 (new AMessage(kWhatWatch, this))->post();
2074 }
2075 return;
2076 }
2077
2078 ALOGW("previous call to %s exceeded timeout", name.c_str());
2079 initiateRelease(false);
2080 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2081}
2082
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002083// static
2084PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002085 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002086 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002087 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002088 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2089 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002090 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002091 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2092 sp<IGraphicBufferProducer> gbp;
2093 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2094 status_t err = gbs->initCheck();
2095 if (err != OK) {
2096 ALOGE("Failed to create persistent input surface: error %d", err);
2097 return nullptr;
2098 }
2099 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002100 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002101 } else {
2102 return nullptr;
2103 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002104 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002105 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002106 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002107 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002108 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002109}
2110
Wonsik Kimffb889a2020-05-28 11:32:25 -07002111class IntfCache {
2112public:
2113 IntfCache() = default;
2114
2115 status_t init(const std::string &name) {
2116 std::shared_ptr<Codec2Client::Interface> intf{
2117 Codec2Client::CreateInterfaceByName(name.c_str())};
2118 if (!intf) {
2119 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2120 mInitStatus = NO_INIT;
2121 return NO_INIT;
2122 }
2123 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2124 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2125 C2ParamField{&sUsage, &sUsage.value}));
2126 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2127 if (err != C2_OK) {
2128 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2129 name.c_str(), err);
2130 mFields[0].status = err;
2131 }
2132 std::vector<std::unique_ptr<C2Param>> params;
2133 err = intf->query(
2134 {&mApiFeatures},
2135 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2136 C2_MAY_BLOCK,
2137 &params);
2138 if (err != C2_OK && err != C2_BAD_INDEX) {
2139 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2140 name.c_str(), err);
2141 }
2142 while (!params.empty()) {
2143 C2Param *param = params.back().release();
2144 params.pop_back();
2145 if (!param) {
2146 continue;
2147 }
2148 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2149 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002150 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002151 }
2152 }
2153 mInitStatus = OK;
2154 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002155 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002156
2157 status_t initCheck() const { return mInitStatus; }
2158
2159 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2160 CHECK_EQ(1u, mFields.size());
2161 return mFields[0];
2162 }
2163
2164 const C2ApiFeaturesSetting &getApiFeatures() const {
2165 return mApiFeatures;
2166 }
2167
2168 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2169 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2170 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2171 C2PortAllocatorsTuning::input::AllocUnique(0);
2172 param->invalidate();
2173 return param;
2174 }();
2175 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2176 }
2177
2178private:
2179 status_t mInitStatus{NO_INIT};
2180
2181 std::vector<C2FieldSupportedValuesQuery> mFields;
2182 C2ApiFeaturesSetting mApiFeatures;
2183 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2184};
2185
2186static const IntfCache &GetIntfCache(const std::string &name) {
2187 static IntfCache sNullIntfCache;
2188 static std::mutex sMutex;
2189 static std::map<std::string, IntfCache> sCache;
2190 std::unique_lock<std::mutex> lock{sMutex};
2191 auto it = sCache.find(name);
2192 if (it == sCache.end()) {
2193 lock.unlock();
2194 IntfCache intfCache;
2195 status_t err = intfCache.init(name);
2196 if (err != OK) {
2197 return sNullIntfCache;
2198 }
2199 lock.lock();
2200 it = sCache.insert({name, std::move(intfCache)}).first;
2201 }
2202 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002203}
2204
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002205static status_t GetCommonAllocatorIds(
2206 const std::vector<std::string> &names,
2207 C2Allocator::type_t type,
2208 std::set<C2Allocator::id_t> *ids) {
2209 int poolMask = GetCodec2PoolMask();
2210 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2211 C2Allocator::id_t defaultAllocatorId =
2212 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2213
2214 ids->clear();
2215 if (names.empty()) {
2216 return OK;
2217 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002218 bool firstIteration = true;
2219 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002220 const IntfCache &intfCache = GetIntfCache(name);
2221 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002222 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002223 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002224 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002225 if (firstIteration) {
2226 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002227 if (allocators && allocators.flexCount() > 0) {
2228 ids->insert(allocators.m.values,
2229 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002230 }
2231 if (ids->empty()) {
2232 // The component does not advertise allocators. Use default.
2233 ids->insert(defaultAllocatorId);
2234 }
2235 continue;
2236 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002237 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002238 if (allocators && allocators.flexCount() > 0) {
2239 filtered = true;
2240 for (auto it = ids->begin(); it != ids->end(); ) {
2241 bool found = false;
2242 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2243 if (allocators.m.values[j] == *it) {
2244 found = true;
2245 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002246 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002247 }
2248 if (found) {
2249 ++it;
2250 } else {
2251 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002252 }
2253 }
2254 }
2255 if (!filtered) {
2256 // The component does not advertise supported allocators. Use default.
2257 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2258 if (ids->size() != (containsDefault ? 1 : 0)) {
2259 ids->clear();
2260 if (containsDefault) {
2261 ids->insert(defaultAllocatorId);
2262 }
2263 }
2264 }
2265 }
2266 // Finally, filter with pool masks
2267 for (auto it = ids->begin(); it != ids->end(); ) {
2268 if ((poolMask >> *it) & 1) {
2269 ++it;
2270 } else {
2271 it = ids->erase(it);
2272 }
2273 }
2274 return OK;
2275}
2276
2277static status_t CalculateMinMaxUsage(
2278 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2279 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2280 *minUsage = 0;
2281 *maxUsage = ~0ull;
2282 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002283 const IntfCache &intfCache = GetIntfCache(name);
2284 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002285 continue;
2286 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002287 const C2FieldSupportedValuesQuery &usageSupportedValues =
2288 intfCache.getUsageSupportedValues();
2289 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002290 continue;
2291 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002292 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002293 if (supported.type != C2FieldSupportedValues::FLAGS) {
2294 continue;
2295 }
2296 if (supported.values.empty()) {
2297 *maxUsage = 0;
2298 continue;
2299 }
2300 *minUsage |= supported.values[0].u64;
2301 int64_t currentMaxUsage = 0;
2302 for (const C2Value::Primitive &flags : supported.values) {
2303 currentMaxUsage |= flags.u64;
2304 }
2305 *maxUsage &= currentMaxUsage;
2306 }
2307 return OK;
2308}
2309
2310// static
2311status_t CCodec::CanFetchLinearBlock(
2312 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002313 for (const std::string &name : names) {
2314 const IntfCache &intfCache = GetIntfCache(name);
2315 if (intfCache.initCheck() != OK) {
2316 continue;
2317 }
2318 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2319 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2320 *isCompatible = false;
2321 return OK;
2322 }
2323 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002324 uint64_t minUsage = usage.expected;
2325 uint64_t maxUsage = ~0ull;
2326 std::set<C2Allocator::id_t> allocators;
2327 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2328 if (allocators.empty()) {
2329 *isCompatible = false;
2330 return OK;
2331 }
2332 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2333 *isCompatible = ((maxUsage & minUsage) == minUsage);
2334 return OK;
2335}
2336
2337static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2338 static std::mutex sMutex{};
2339 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2340 std::unique_lock<std::mutex> lock{sMutex};
2341 std::shared_ptr<C2BlockPool> pool;
2342 auto it = sPools.find(allocId);
2343 if (it == sPools.end()) {
2344 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2345 if (err == OK) {
2346 sPools.emplace(allocId, pool);
2347 } else {
2348 pool.reset();
2349 }
2350 } else {
2351 pool = it->second;
2352 }
2353 return pool;
2354}
2355
2356// static
2357std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2358 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
2359 uint64_t minUsage = usage.expected;
2360 uint64_t maxUsage = ~0ull;
2361 std::set<C2Allocator::id_t> allocators;
2362 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2363 if (allocators.empty()) {
2364 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2365 }
2366 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2367 if ((maxUsage & minUsage) != minUsage) {
2368 allocators.clear();
2369 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2370 }
2371 std::shared_ptr<C2LinearBlock> block;
2372 for (C2Allocator::id_t allocId : allocators) {
2373 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2374 if (!pool) {
2375 continue;
2376 }
2377 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2378 if (err != C2_OK || !block) {
2379 block.reset();
2380 continue;
2381 }
2382 break;
2383 }
2384 return block;
2385}
2386
2387// static
2388status_t CCodec::CanFetchGraphicBlock(
2389 const std::vector<std::string> &names, bool *isCompatible) {
2390 uint64_t minUsage = 0;
2391 uint64_t maxUsage = ~0ull;
2392 std::set<C2Allocator::id_t> allocators;
2393 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2394 if (allocators.empty()) {
2395 *isCompatible = false;
2396 return OK;
2397 }
2398 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2399 *isCompatible = ((maxUsage & minUsage) == minUsage);
2400 return OK;
2401}
2402
2403// static
2404std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2405 int32_t width,
2406 int32_t height,
2407 int32_t format,
2408 uint64_t usage,
2409 const std::vector<std::string> &names) {
2410 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2411 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2412 ALOGD("Unrecognized pixel format: %d", format);
2413 return nullptr;
2414 }
2415 uint64_t minUsage = 0;
2416 uint64_t maxUsage = ~0ull;
2417 std::set<C2Allocator::id_t> allocators;
2418 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2419 if (allocators.empty()) {
2420 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2421 }
2422 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2423 minUsage |= usage;
2424 if ((maxUsage & minUsage) != minUsage) {
2425 allocators.clear();
2426 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2427 }
2428 std::shared_ptr<C2GraphicBlock> block;
2429 for (C2Allocator::id_t allocId : allocators) {
2430 std::shared_ptr<C2BlockPool> pool;
2431 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2432 if (err != C2_OK || !pool) {
2433 continue;
2434 }
2435 err = pool->fetchGraphicBlock(
2436 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2437 if (err != C2_OK || !block) {
2438 block.reset();
2439 continue;
2440 }
2441 break;
2442 }
2443 return block;
2444}
2445
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002446} // namespace android
2447