blob: 452ffce1193062fad5d0fc1659e6aab3ac33a3e4 [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;
251 // WORKAROUND: having more slots improve performance while consuming
252 // more memory. This is a temporary workaround to reduce memory for
253 // larger-than-4K scenario.
254 if (mWidth * mHeight > 4096 * 2340) {
255 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900256
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800257 OMX_PARAM_PORTDEFINITIONTYPE param;
258 param.nPortIndex = kPortIndexInput;
259 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
260 &param, sizeof(param));
261 if (err == OK) {
262 numSlots = param.nBufferCountActual;
263 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900264 }
265
266 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800267 source->onInputBufferAdded(i);
268 }
269
270 source->onOmxExecuting();
271 return OK;
272 }
273
274 status_t signalEndOfInputStream() override {
275 return GetStatus(mSource->signalEndOfInputStream());
276 }
277
278 status_t configure(Config &config) {
279 std::stringstream status;
280 status_t err = OK;
281
282 // handle each configuration granually, in case we need to handle part of the configuration
283 // elsewhere
284
285 // TRICKY: we do not unset frame delay repeating
286 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
287 int64_t us = 1e6 / config.mMinFps + 0.5;
288 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
289 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
290 if (res != OK) {
291 status << " (=> " << asString(res) << ")";
292 err = res;
293 }
294 mConfig.mMinFps = config.mMinFps;
295 }
296
297 // pts gap
298 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
299 if (mNode != nullptr) {
300 OMX_PARAM_U32TYPE ptrGapParam = {};
301 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700302 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800303 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
304 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700305 // float -> uint32_t is undefined if the value is negative.
306 // First convert to int32_t to ensure the expected behavior.
307 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800308 (void)mNode->setParameter(
309 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
310 &ptrGapParam, sizeof(ptrGapParam));
311 }
312 }
313
314 // max fps
315 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700316 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800317 && config.mMaxFps != mConfig.mMaxFps) {
318 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
319 status << " maxFps=" << config.mMaxFps;
320 if (res != OK) {
321 status << " (=> " << asString(res) << ")";
322 err = res;
323 }
324 mConfig.mMaxFps = config.mMaxFps;
325 }
326
327 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
328 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
329 status << " timeOffset " << config.mTimeOffsetUs << "us";
330 if (res != OK) {
331 status << " (=> " << asString(res) << ")";
332 err = res;
333 }
334 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
335 }
336
337 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
338 status_t res =
339 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
340 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
341 if (res != OK) {
342 status << " (=> " << asString(res) << ")";
343 err = res;
344 }
345 mConfig.mCaptureFps = config.mCaptureFps;
346 mConfig.mCodedFps = config.mCodedFps;
347 }
348
349 if (config.mStartAtUs != mConfig.mStartAtUs
350 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
351 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
352 status << " start at " << config.mStartAtUs << "us";
353 if (res != OK) {
354 status << " (=> " << asString(res) << ")";
355 err = res;
356 }
357 mConfig.mStartAtUs = config.mStartAtUs;
358 mConfig.mStopped = config.mStopped;
359 }
360
361 // suspend-resume
362 if (config.mSuspended != mConfig.mSuspended) {
363 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
364 status << " " << (config.mSuspended ? "suspend" : "resume")
365 << " at " << config.mSuspendAtUs << "us";
366 if (res != OK) {
367 status << " (=> " << asString(res) << ")";
368 err = res;
369 }
370 mConfig.mSuspended = config.mSuspended;
371 mConfig.mSuspendAtUs = config.mSuspendAtUs;
372 }
373
374 if (config.mStopped != mConfig.mStopped && config.mStopped) {
375 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
376 status << " stop at " << config.mStopAtUs << "us";
377 if (res != OK) {
378 status << " (=> " << asString(res) << ")";
379 err = res;
380 } else {
381 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700382 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
383 [&res, &delayUs = config.mInputDelayUs](
384 auto status, auto stopTimeOffsetUs) {
385 res = static_cast<status_t>(status);
386 delayUs = stopTimeOffsetUs;
387 });
388 if (!trans.isOk()) {
389 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
390 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800391 if (res != OK) {
392 status << " (=> " << asString(res) << ")";
393 } else {
394 status << "=" << config.mInputDelayUs << "us";
395 }
396 mConfig.mInputDelayUs = config.mInputDelayUs;
397 }
398 mConfig.mStopAtUs = config.mStopAtUs;
399 mConfig.mStopped = config.mStopped;
400 }
401
402 // color aspects (android._color-aspects)
403
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700404 // consumer usage is queried earlier.
405
Wonsik Kimbd557932019-07-02 15:51:20 -0700406 if (status.str().empty()) {
407 ALOGD("ISConfig not changed");
408 } else {
409 ALOGD("ISConfig%s", status.str().c_str());
410 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800411 return err;
412 }
413
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700414 void onInputBufferDone(c2_cntr64_t index) override {
415 mNode->onInputBufferDone(index);
416 }
417
Pawin Vongmasa36653902018-11-15 00:10:25 -0800418private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700419 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800420 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700421 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800422 uint32_t mWidth;
423 uint32_t mHeight;
424 Config mConfig;
425};
426
427class Codec2ClientInterfaceWrapper : public C2ComponentStore {
428 std::shared_ptr<Codec2Client> mClient;
429
430public:
431 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
432 : mClient(client) { }
433
434 virtual ~Codec2ClientInterfaceWrapper() = default;
435
436 virtual c2_status_t config_sm(
437 const std::vector<C2Param *> &params,
438 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
439 return mClient->config(params, C2_MAY_BLOCK, failures);
440 };
441
442 virtual c2_status_t copyBuffer(
443 std::shared_ptr<C2GraphicBuffer>,
444 std::shared_ptr<C2GraphicBuffer>) {
445 return C2_OMITTED;
446 }
447
448 virtual c2_status_t createComponent(
449 C2String, std::shared_ptr<C2Component> *const component) {
450 component->reset();
451 return C2_OMITTED;
452 }
453
454 virtual c2_status_t createInterface(
455 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
456 interface->reset();
457 return C2_OMITTED;
458 }
459
460 virtual c2_status_t query_sm(
461 const std::vector<C2Param *> &stackParams,
462 const std::vector<C2Param::Index> &heapParamIndices,
463 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
464 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
465 }
466
467 virtual c2_status_t querySupportedParams_nb(
468 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
469 return mClient->querySupportedParams(params);
470 }
471
472 virtual c2_status_t querySupportedValues_sm(
473 std::vector<C2FieldSupportedValuesQuery> &fields) const {
474 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
475 }
476
477 virtual C2String getName() const {
478 return mClient->getName();
479 }
480
481 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
482 return mClient->getParamReflector();
483 }
484
485 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
486 return std::vector<std::shared_ptr<const C2Component::Traits>>();
487 }
488};
489
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800490void RevertOutputFormatIfNeeded(
491 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
492 // We used to not report changes to these keys to the client.
493 const static std::set<std::string> sIgnoredKeys({
494 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800495 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800496 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800497 KEY_MAX_WIDTH,
498 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800499 "csd-0",
500 "csd-1",
501 "csd-2",
502 });
503 if (currentFormat == oldFormat) {
504 return;
505 }
506 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
507 AMessage::Type type;
508 for (size_t i = diff->countEntries(); i > 0; --i) {
509 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
510 diff->removeEntryAt(i - 1);
511 }
512 }
513 if (diff->countEntries() == 0) {
514 currentFormat = oldFormat;
515 }
516}
517
Pawin Vongmasa36653902018-11-15 00:10:25 -0800518} // namespace
519
520// CCodec::ClientListener
521
522struct CCodec::ClientListener : public Codec2Client::Listener {
523
524 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
525
526 virtual void onWorkDone(
527 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800528 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800529 (void)component;
530 sp<CCodec> codec(mCodec.promote());
531 if (!codec) {
532 return;
533 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800534 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800535 }
536
537 virtual void onTripped(
538 const std::weak_ptr<Codec2Client::Component>& component,
539 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
540 ) override {
541 // TODO
542 (void)component;
543 (void)settingResult;
544 }
545
546 virtual void onError(
547 const std::weak_ptr<Codec2Client::Component>& component,
548 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800549 {
550 // Component is only used for reporting as we use a separate listener for each instance
551 std::shared_ptr<Codec2Client::Component> comp = component.lock();
552 if (!comp) {
553 ALOGD("Component died with error: 0x%x", errorCode);
554 } else {
555 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
556 }
557 }
558
559 // Report to MediaCodec
560 // Note: for now we do not propagate the error code to MediaCodec as we would need
561 // to translate to a MediaCodec error.
562 sp<CCodec> codec(mCodec.promote());
563 if (!codec || !codec->mCallback) {
564 return;
565 }
566 codec->mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800567 }
568
569 virtual void onDeath(
570 const std::weak_ptr<Codec2Client::Component>& component) override {
571 { // Log the death of the component.
572 std::shared_ptr<Codec2Client::Component> comp = component.lock();
573 if (!comp) {
574 ALOGE("Codec2 component died.");
575 } else {
576 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
577 }
578 }
579
580 // Report to MediaCodec.
581 sp<CCodec> codec(mCodec.promote());
582 if (!codec || !codec->mCallback) {
583 return;
584 }
585 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
586 }
587
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800588 virtual void onFrameRendered(uint64_t bufferQueueId,
589 int32_t slotId,
590 int64_t timestampNs) override {
591 // TODO: implement
592 (void)bufferQueueId;
593 (void)slotId;
594 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800595 }
596
597 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800598 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800599 sp<CCodec> codec(mCodec.promote());
600 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800601 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800602 }
603 }
604
605private:
606 wp<CCodec> mCodec;
607};
608
609// CCodecCallbackImpl
610
611class CCodecCallbackImpl : public CCodecCallback {
612public:
613 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
614 ~CCodecCallbackImpl() override = default;
615
616 void onError(status_t err, enum ActionCode actionCode) override {
617 mCodec->mCallback->onError(err, actionCode);
618 }
619
620 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
621 mCodec->mCallback->onOutputFramesRendered(
622 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
623 }
624
Pawin Vongmasa36653902018-11-15 00:10:25 -0800625 void onOutputBuffersChanged() override {
626 mCodec->mCallback->onOutputBuffersChanged();
627 }
628
629private:
630 CCodec *mCodec;
631};
632
633// CCodec
634
635CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700636 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
637 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800638}
639
640CCodec::~CCodec() {
641}
642
643std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
644 return mChannel;
645}
646
647status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
648 status_t err = job();
649 if (err != C2_OK) {
650 mCallback->onError(err, ACTION_CODE_FATAL);
651 }
652 return err;
653}
654
655void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
656 auto setAllocating = [this] {
657 Mutexed<State>::Locked state(mState);
658 if (state->get() != RELEASED) {
659 return INVALID_OPERATION;
660 }
661 state->set(ALLOCATING);
662 return OK;
663 };
664 if (tryAndReportOnError(setAllocating) != OK) {
665 return;
666 }
667
668 sp<RefBase> codecInfo;
669 CHECK(msg->findObject("codecInfo", &codecInfo));
670 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
671
672 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
673 allocMsg->setObject("codecInfo", codecInfo);
674 allocMsg->post();
675}
676
677void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
678 if (codecInfo == nullptr) {
679 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
680 return;
681 }
682 ALOGD("allocate(%s)", codecInfo->getCodecName());
683 mClientListener.reset(new ClientListener(this));
684
685 AString componentName = codecInfo->getCodecName();
686 std::shared_ptr<Codec2Client> client;
687
688 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700689 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800690 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800691 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800692 SetPreferredCodec2ComponentStore(
693 std::make_shared<Codec2ClientInterfaceWrapper>(client));
694 }
695
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900696 std::shared_ptr<Codec2Client::Component> comp;
697 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800698 componentName.c_str(),
699 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900700 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800701 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900702 if (status != C2_OK) {
703 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800704 Mutexed<State>::Locked state(mState);
705 state->set(RELEASED);
706 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900707 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800708 state.lock();
709 return;
710 }
711 ALOGI("Created component [%s]", componentName.c_str());
712 mChannel->setComponent(comp);
713 auto setAllocated = [this, comp, client] {
714 Mutexed<State>::Locked state(mState);
715 if (state->get() != ALLOCATING) {
716 state->set(RELEASED);
717 return UNKNOWN_ERROR;
718 }
719 state->set(ALLOCATED);
720 state->comp = comp;
721 mClient = client;
722 return OK;
723 };
724 if (tryAndReportOnError(setAllocated) != OK) {
725 return;
726 }
727
728 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700729 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
730 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800731 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800732 if (err != OK) {
733 ALOGW("Failed to initialize configuration support");
734 // TODO: report error once we complete implementation.
735 }
736 config->queryConfiguration(comp);
737
738 mCallback->onComponentAllocated(componentName.c_str());
739}
740
741void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
742 auto checkAllocated = [this] {
743 Mutexed<State>::Locked state(mState);
744 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
745 };
746 if (tryAndReportOnError(checkAllocated) != OK) {
747 return;
748 }
749
750 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
751 msg->setMessage("format", format);
752 msg->post();
753}
754
755void CCodec::configure(const sp<AMessage> &msg) {
756 std::shared_ptr<Codec2Client::Component> comp;
757 auto checkAllocated = [this, &comp] {
758 Mutexed<State>::Locked state(mState);
759 if (state->get() != ALLOCATED) {
760 state->set(RELEASED);
761 return UNKNOWN_ERROR;
762 }
763 comp = state->comp;
764 return OK;
765 };
766 if (tryAndReportOnError(checkAllocated) != OK) {
767 return;
768 }
769
770 auto doConfig = [msg, comp, this]() -> status_t {
771 AString mime;
772 if (!msg->findString("mime", &mime)) {
773 return BAD_VALUE;
774 }
775
776 int32_t encoder;
777 if (!msg->findInt32("encoder", &encoder)) {
778 encoder = false;
779 }
780
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800781 int32_t flags;
782 if (!msg->findInt32("flags", &flags)) {
783 return BAD_VALUE;
784 }
785
Pawin Vongmasa36653902018-11-15 00:10:25 -0800786 // TODO: read from intf()
787 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
788 return UNKNOWN_ERROR;
789 }
790
791 int32_t storeMeta;
792 if (encoder
793 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
794 && storeMeta != kMetadataBufferTypeInvalid) {
795 if (storeMeta != kMetadataBufferTypeANWBuffer) {
796 ALOGD("Only ANW buffers are supported for legacy metadata mode");
797 return BAD_VALUE;
798 }
799 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
800 }
801
802 sp<RefBase> obj;
803 sp<Surface> surface;
804 if (msg->findObject("native-window", &obj)) {
805 surface = static_cast<Surface *>(obj.get());
806 setSurface(surface);
807 }
808
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700809 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
810 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800811 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800812 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
813 ALOGD("[%s] buffers are %sbound to CCodec for this session",
814 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800815
Wonsik Kim1114eea2019-02-25 14:35:24 -0800816 // Enforce required parameters
817 int32_t i32;
818 float flt;
819 if (config->mDomain & Config::IS_AUDIO) {
820 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
821 ALOGD("sample rate is missing, which is required for audio components.");
822 return BAD_VALUE;
823 }
824 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
825 ALOGD("channel count is missing, which is required for audio components.");
826 return BAD_VALUE;
827 }
828 if ((config->mDomain & Config::IS_ENCODER)
829 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
830 && !msg->findInt32(KEY_BIT_RATE, &i32)
831 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
832 ALOGD("bitrate is missing, which is required for audio encoders.");
833 return BAD_VALUE;
834 }
835 }
836 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
837 if (!msg->findInt32(KEY_WIDTH, &i32)) {
838 ALOGD("width is missing, which is required for image/video components.");
839 return BAD_VALUE;
840 }
841 if (!msg->findInt32(KEY_HEIGHT, &i32)) {
842 ALOGD("height is missing, which is required for image/video components.");
843 return BAD_VALUE;
844 }
845 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700846 int32_t mode = BITRATE_MODE_VBR;
847 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700848 if (!msg->findInt32(KEY_QUALITY, &i32)) {
849 ALOGD("quality is missing, which is required for video encoders in CQ.");
850 return BAD_VALUE;
851 }
852 } else {
853 if (!msg->findInt32(KEY_BIT_RATE, &i32)
854 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
855 ALOGD("bitrate is missing, which is required for video encoders.");
856 return BAD_VALUE;
857 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800858 }
859 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
860 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
861 ALOGD("I frame interval is missing, which is required for video encoders.");
862 return BAD_VALUE;
863 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700864 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
865 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
866 ALOGD("frame rate is missing, which is required for video encoders.");
867 return BAD_VALUE;
868 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800869 }
870 }
871
Pawin Vongmasa36653902018-11-15 00:10:25 -0800872 /*
873 * Handle input surface configuration
874 */
875 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
876 && (config->mDomain & Config::IS_ENCODER)) {
877 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
878 {
879 config->mISConfig->mMinFps = 0;
880 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800881 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800882 config->mISConfig->mMinFps = 1e6 / value;
883 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700884 if (!msg->findFloat(
885 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
886 config->mISConfig->mMaxFps = -1;
887 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800888 config->mISConfig->mMinAdjustedFps = 0;
889 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800890 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800891 if (value < 0 && value >= INT32_MIN) {
892 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700893 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800894 } else if (value > 0 && value <= INT32_MAX) {
895 config->mISConfig->mMinAdjustedFps = 1e6 / value;
896 }
897 }
898 }
899
900 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700901 bool captureFpsFound = false;
902 double timeLapseFps;
903 float captureRate;
904 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
905 config->mISConfig->mCaptureFps = timeLapseFps;
906 captureFpsFound = true;
907 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
908 config->mISConfig->mCaptureFps = captureRate;
909 captureFpsFound = true;
910 }
911 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800912 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
913 }
914 }
915
916 {
917 config->mISConfig->mSuspended = false;
918 config->mISConfig->mSuspendAtUs = -1;
919 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800920 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800921 config->mISConfig->mSuspended = true;
922 }
923 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700924 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800925 }
926
927 /*
928 * Handle desired color format.
929 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700930 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800931 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700932 int32_t format = 0;
933 // Query vendor format for Flexible YUV
934 std::vector<std::unique_ptr<C2Param>> heapParams;
935 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
936 if (mClient->query(
937 {},
938 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
939 C2_MAY_BLOCK,
940 &heapParams) == C2_OK
941 && heapParams.size() == 1u) {
942 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
943 heapParams[0].get());
944 } else {
945 pixelFormatInfo = nullptr;
946 }
947 std::optional<uint32_t> flexPixelFormat{};
948 std::optional<uint32_t> flexPlanarPixelFormat{};
949 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
950 if (pixelFormatInfo && *pixelFormatInfo) {
951 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
952 const C2FlexiblePixelFormatDescriptorStruct &desc =
953 pixelFormatInfo->m.values[i];
954 if (desc.bitDepth != 8
955 || desc.subsampling != C2Color::YUV_420
956 // TODO(b/180076105): some device report wrong layout
957 // || desc.layout == C2Color::INTERLEAVED_PACKED
958 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
959 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
960 continue;
961 }
962 if (!flexPixelFormat) {
963 flexPixelFormat = desc.pixelFormat;
964 }
965 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
966 flexPlanarPixelFormat = desc.pixelFormat;
967 }
968 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
969 flexSemiPlanarPixelFormat = desc.pixelFormat;
970 }
971 }
972 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800973 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700974 // Also handle default color format (encoders require color format, so this is only
975 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -0800976 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700977 if (surface == nullptr) {
978 format = flexPixelFormat.value_or(COLOR_FormatYUV420Flexible);
979 } else {
980 format = COLOR_FormatSurface;
981 }
982 defaultColorFormat = format;
983 }
984 } else {
985 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
986 switch (format) {
987 case COLOR_FormatYUV420Flexible:
988 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
989 break;
990 case COLOR_FormatYUV420Planar:
991 case COLOR_FormatYUV420PackedPlanar:
992 format = flexPlanarPixelFormat.value_or(
993 flexPixelFormat.value_or(format));
994 break;
995 case COLOR_FormatYUV420SemiPlanar:
996 case COLOR_FormatYUV420PackedSemiPlanar:
997 format = flexSemiPlanarPixelFormat.value_or(
998 flexPixelFormat.value_or(format));
999 break;
1000 default:
1001 // No-op
1002 break;
1003 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001004 }
1005 }
1006
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001007 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001008 msg->setInt32("android._color-format", format);
1009 }
1010 }
1011
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001012 int32_t subscribeToAllVendorParams;
1013 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1014 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1015 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1016 }
1017 }
1018
Pawin Vongmasa36653902018-11-15 00:10:25 -08001019 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001020 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1021 // the behavior here.
1022 sp<AMessage> sdkParams = msg;
1023 int32_t videoBitrate;
1024 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1025 sdkParams = msg->dup();
1026 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1027 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001028 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001029 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001030 if (err != OK) {
1031 ALOGW("failed to convert configuration to c2 params");
1032 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001033
1034 int32_t maxBframes = 0;
1035 if ((config->mDomain & Config::IS_ENCODER)
1036 && (config->mDomain & Config::IS_VIDEO)
1037 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1038 && maxBframes > 0) {
1039 std::unique_ptr<C2StreamGopTuning::output> gop =
1040 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1041 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1042 gop->m.values[1] = {
1043 C2Config::picture_type_t(P_FRAME | B_FRAME),
1044 uint32_t(maxBframes)
1045 };
1046 configUpdate.push_back(std::move(gop));
1047 }
1048
Pawin Vongmasa36653902018-11-15 00:10:25 -08001049 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1050 if (err != OK) {
1051 ALOGW("failed to configure c2 params");
1052 return err;
1053 }
1054
1055 std::vector<std::unique_ptr<C2Param>> params;
1056 C2StreamUsageTuning::input usage(0u, 0u);
1057 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001058 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001059
Wonsik Kim3baecda2021-02-07 22:19:56 -08001060 C2Param::Index colorAspectsRequestIndex =
1061 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001062 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001063 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001064 };
1065 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001066 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001067 indices,
1068 C2_DONT_BLOCK,
1069 &params);
1070 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1071 ALOGE("Failed to query component interface: %d", c2err);
1072 return UNKNOWN_ERROR;
1073 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001074 if (usage) {
1075 if (usage.value & C2MemoryUsage::CPU_READ) {
1076 config->mInputFormat->setInt32("using-sw-read-often", true);
1077 }
1078 if (config->mISConfig) {
1079 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1080 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1081 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001082 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001083 }
1084
1085 // NOTE: we don't blindly use client specified input size if specified as clients
1086 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1087 // client specified size is only used to ask for bigger buffers than component suggested
1088 // size.
1089 int32_t clientInputSize = 0;
1090 bool clientSpecifiedInputSize =
1091 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1092 // TEMP: enforce minimum buffer size of 1MB for video decoders
1093 // and 16K / 4K for audio encoders/decoders
1094 if (maxInputSize.value == 0) {
1095 if (config->mDomain & Config::IS_AUDIO) {
1096 maxInputSize.value = encoder ? 16384 : 4096;
1097 } else if (!encoder) {
1098 maxInputSize.value = 1048576u;
1099 }
1100 }
1101
1102 // verify that CSD fits into this size (if defined)
1103 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1104 sp<ABuffer> csd;
1105 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1106 if (csd && csd->size() > maxInputSize.value) {
1107 maxInputSize.value = csd->size();
1108 }
1109 }
1110 }
1111
1112 // TODO: do this based on component requiring linear allocator for input
1113 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1114 if (clientSpecifiedInputSize) {
1115 // Warn that we're overriding client's max input size if necessary.
1116 if ((uint32_t)clientInputSize < maxInputSize.value) {
1117 ALOGD("client requested max input size %d, which is smaller than "
1118 "what component recommended (%u); overriding with component "
1119 "recommendation.", clientInputSize, maxInputSize.value);
1120 ALOGW("This behavior is subject to change. It is recommended that "
1121 "app developers double check whether the requested "
1122 "max input size is in reasonable range.");
1123 } else {
1124 maxInputSize.value = clientInputSize;
1125 }
1126 }
1127 // Pass max input size on input format to the buffer channel (if supplied by the
1128 // component or by a default)
1129 if (maxInputSize.value) {
1130 config->mInputFormat->setInt32(
1131 KEY_MAX_INPUT_SIZE,
1132 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1133 }
1134 }
1135
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001136 int32_t clientPrepend;
1137 if ((config->mDomain & Config::IS_VIDEO)
1138 && (config->mDomain & Config::IS_ENCODER)
1139 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1140 && clientPrepend
1141 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1142 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1143 return BAD_VALUE;
1144 }
1145
Pawin Vongmasa36653902018-11-15 00:10:25 -08001146 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1147 // propagate HDR static info to output format for both encoders and decoders
1148 // if component supports this info, we will update from component, but only the raw port,
1149 // so don't propagate if component already filled it in.
1150 sp<ABuffer> hdrInfo;
1151 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1152 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1153 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1154 }
1155
1156 // Set desired color format from configuration parameter
1157 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001158 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1159 format = defaultColorFormat;
1160 }
1161 if (config->mDomain & Config::IS_ENCODER) {
1162 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
1163 if (msg->findInt32("android._color-format", &format)) {
1164 config->mInputFormat->setInt32("android._color-format", format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001165 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001166 } else {
1167 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001168 }
1169 }
1170
1171 // propagate encoder delay and padding to output format
1172 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1173 int delay = 0;
1174 if (msg->findInt32("encoder-delay", &delay)) {
1175 config->mOutputFormat->setInt32("encoder-delay", delay);
1176 }
1177 int padding = 0;
1178 if (msg->findInt32("encoder-padding", &padding)) {
1179 config->mOutputFormat->setInt32("encoder-padding", padding);
1180 }
1181 }
1182
1183 // set channel-mask
1184 if (config->mDomain & Config::IS_AUDIO) {
1185 int32_t mask;
1186 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1187 if (config->mDomain & Config::IS_ENCODER) {
1188 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1189 } else {
1190 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1191 }
1192 }
1193 }
1194
Wonsik Kim3baecda2021-02-07 22:19:56 -08001195 std::unique_ptr<C2Param> colorTransferRequestParam;
1196 for (std::unique_ptr<C2Param> &param : params) {
1197 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1198 ALOGI("found color transfer request param");
1199 colorTransferRequestParam = std::move(param);
1200 }
1201 }
1202 int32_t colorTransferRequest = 0;
1203 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1204 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1205 colorTransferRequest = 0;
1206 }
1207
1208 if (colorTransferRequest != 0) {
1209 if (colorTransferRequestParam && *colorTransferRequestParam) {
1210 C2StreamColorAspectsInfo::output *info =
1211 static_cast<C2StreamColorAspectsInfo::output *>(
1212 colorTransferRequestParam.get());
1213 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1214 colorTransferRequest = 0;
1215 }
1216 } else {
1217 colorTransferRequest = 0;
1218 }
1219 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1220 }
1221
Pawin Vongmasa36653902018-11-15 00:10:25 -08001222 ALOGD("setup formats input: %s and output: %s",
1223 config->mInputFormat->debugString().c_str(),
1224 config->mOutputFormat->debugString().c_str());
1225 return OK;
1226 };
1227 if (tryAndReportOnError(doConfig) != OK) {
1228 return;
1229 }
1230
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001231 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1232 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001233
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001234 config->queryConfiguration(comp);
1235
Pawin Vongmasa36653902018-11-15 00:10:25 -08001236 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1237}
1238
1239void CCodec::initiateCreateInputSurface() {
1240 status_t err = [this] {
1241 Mutexed<State>::Locked state(mState);
1242 if (state->get() != ALLOCATED) {
1243 return UNKNOWN_ERROR;
1244 }
1245 // TODO: read it from intf() properly.
1246 if (state->comp->getName().find("encoder") == std::string::npos) {
1247 return INVALID_OPERATION;
1248 }
1249 return OK;
1250 }();
1251 if (err != OK) {
1252 mCallback->onInputSurfaceCreationFailed(err);
1253 return;
1254 }
1255
1256 (new AMessage(kWhatCreateInputSurface, this))->post();
1257}
1258
Lajos Molnar47118272019-01-31 16:28:04 -08001259sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1260 using namespace android::hardware::media::omx::V1_0;
1261 using namespace android::hardware::media::omx::V1_0::utils;
1262 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1263 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1264 android::sp<IOmx> omx = IOmx::getService();
1265 typedef android::hardware::graphics::bufferqueue::V1_0::
1266 IGraphicBufferProducer HGraphicBufferProducer;
1267 typedef android::hardware::media::omx::V1_0::
1268 IGraphicBufferSource HGraphicBufferSource;
1269 OmxStatus s;
1270 android::sp<HGraphicBufferProducer> gbp;
1271 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001272
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001273 using ::android::hardware::Return;
1274 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001275 [&s, &gbp, &gbs](
1276 OmxStatus status,
1277 const android::sp<HGraphicBufferProducer>& producer,
1278 const android::sp<HGraphicBufferSource>& source) {
1279 s = status;
1280 gbp = producer;
1281 gbs = source;
1282 });
1283 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001284 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001285 }
1286
1287 return nullptr;
1288}
1289
1290sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1291 sp<PersistentSurface> surface(CreateInputSurface());
1292
1293 if (surface == nullptr) {
1294 surface = CreateOmxInputSurface();
1295 }
1296
1297 return surface;
1298}
1299
Pawin Vongmasa36653902018-11-15 00:10:25 -08001300void CCodec::createInputSurface() {
1301 status_t err;
1302 sp<IGraphicBufferProducer> bufferProducer;
1303
1304 sp<AMessage> inputFormat;
1305 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001306 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001307 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001308 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1309 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001310 inputFormat = config->mInputFormat;
1311 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001312 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001313 }
1314
Lajos Molnar47118272019-01-31 16:28:04 -08001315 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001316 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1317 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1318 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001319
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001320 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001321 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1322 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001323 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001324 inputSurface));
1325 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001326 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001327 int32_t width = 0;
1328 (void)outputFormat->findInt32("width", &width);
1329 int32_t height = 0;
1330 (void)outputFormat->findInt32("height", &height);
1331 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001332 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001333 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001334 } else {
1335 ALOGE("Corrupted input surface");
1336 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1337 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001338 }
1339
1340 if (err != OK) {
1341 ALOGE("Failed to set up input surface: %d", err);
1342 mCallback->onInputSurfaceCreationFailed(err);
1343 return;
1344 }
1345
1346 mCallback->onInputSurfaceCreated(
1347 inputFormat,
1348 outputFormat,
1349 new BufferProducerWrapper(bufferProducer));
1350}
1351
1352status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001353 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1354 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001355 config->mUsingSurface = true;
1356
1357 // we are now using surface - apply default color aspects to input format - as well as
1358 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001359 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001360 ALOGD("input format %s to %s",
1361 inputFormatChanged ? "changed" : "unchanged",
1362 config->mInputFormat->debugString().c_str());
1363
1364 // configure dataspace
1365 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1366 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1367 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1368 surface->setDataSpace(dataSpace);
1369
1370 status_t err = mChannel->setInputSurface(surface);
1371 if (err != OK) {
1372 // undo input format update
1373 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001374 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001375 return err;
1376 }
1377 config->mInputSurface = surface;
1378
1379 if (config->mISConfig) {
1380 surface->configure(*config->mISConfig);
1381 } else {
1382 ALOGD("ISConfig: no configuration");
1383 }
1384
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001385 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001386}
1387
1388void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1389 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1390 msg->setObject("surface", surface);
1391 msg->post();
1392}
1393
1394void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1395 sp<AMessage> inputFormat;
1396 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001397 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001398 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001399 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1400 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001401 inputFormat = config->mInputFormat;
1402 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001403 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001404 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001405 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1406 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1407 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1408 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001409 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1410 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1411 if (err != OK) {
1412 ALOGE("Failed to set up input surface: %d", err);
1413 mCallback->onInputSurfaceDeclined(err);
1414 return;
1415 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001416 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001417 int32_t width = 0;
1418 (void)outputFormat->findInt32("width", &width);
1419 int32_t height = 0;
1420 (void)outputFormat->findInt32("height", &height);
1421 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001422 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001423 if (err != OK) {
1424 ALOGE("Failed to set up input surface: %d", err);
1425 mCallback->onInputSurfaceDeclined(err);
1426 return;
1427 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001428 } else {
1429 ALOGE("Failed to set input surface: Corrupted surface.");
1430 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1431 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001432 }
1433 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1434}
1435
1436void CCodec::initiateStart() {
1437 auto setStarting = [this] {
1438 Mutexed<State>::Locked state(mState);
1439 if (state->get() != ALLOCATED) {
1440 return UNKNOWN_ERROR;
1441 }
1442 state->set(STARTING);
1443 return OK;
1444 };
1445 if (tryAndReportOnError(setStarting) != OK) {
1446 return;
1447 }
1448
1449 (new AMessage(kWhatStart, this))->post();
1450}
1451
1452void CCodec::start() {
1453 std::shared_ptr<Codec2Client::Component> comp;
1454 auto checkStarting = [this, &comp] {
1455 Mutexed<State>::Locked state(mState);
1456 if (state->get() != STARTING) {
1457 return UNKNOWN_ERROR;
1458 }
1459 comp = state->comp;
1460 return OK;
1461 };
1462 if (tryAndReportOnError(checkStarting) != OK) {
1463 return;
1464 }
1465
1466 c2_status_t err = comp->start();
1467 if (err != C2_OK) {
1468 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1469 ACTION_CODE_FATAL);
1470 return;
1471 }
1472 sp<AMessage> inputFormat;
1473 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001474 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001475 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001476 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001477 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1478 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001479 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001480 // start triggers format dup
1481 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001482 if (config->mInputSurface) {
1483 err2 = config->mInputSurface->start();
1484 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001485 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001486 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001487 if (err2 != OK) {
1488 mCallback->onError(err2, ACTION_CODE_FATAL);
1489 return;
1490 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001491 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001492 if (err2 != OK) {
1493 mCallback->onError(err2, ACTION_CODE_FATAL);
1494 return;
1495 }
1496
1497 auto setRunning = [this] {
1498 Mutexed<State>::Locked state(mState);
1499 if (state->get() != STARTING) {
1500 return UNKNOWN_ERROR;
1501 }
1502 state->set(RUNNING);
1503 return OK;
1504 };
1505 if (tryAndReportOnError(setRunning) != OK) {
1506 return;
1507 }
1508 mCallback->onStartCompleted();
1509
1510 (void)mChannel->requestInitialInputBuffers();
1511}
1512
1513void CCodec::initiateShutdown(bool keepComponentAllocated) {
1514 if (keepComponentAllocated) {
1515 initiateStop();
1516 } else {
1517 initiateRelease();
1518 }
1519}
1520
1521void CCodec::initiateStop() {
1522 {
1523 Mutexed<State>::Locked state(mState);
1524 if (state->get() == ALLOCATED
1525 || state->get() == RELEASED
1526 || state->get() == STOPPING
1527 || state->get() == RELEASING) {
1528 // We're already stopped, released, or doing it right now.
1529 state.unlock();
1530 mCallback->onStopCompleted();
1531 state.lock();
1532 return;
1533 }
1534 state->set(STOPPING);
1535 }
1536
Wonsik Kim936a89c2020-05-08 16:07:50 -07001537 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001538 (new AMessage(kWhatStop, this))->post();
1539}
1540
1541void CCodec::stop() {
1542 std::shared_ptr<Codec2Client::Component> comp;
1543 {
1544 Mutexed<State>::Locked state(mState);
1545 if (state->get() == RELEASING) {
1546 state.unlock();
1547 // We're already stopped or release is in progress.
1548 mCallback->onStopCompleted();
1549 state.lock();
1550 return;
1551 } else if (state->get() != STOPPING) {
1552 state.unlock();
1553 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1554 state.lock();
1555 return;
1556 }
1557 comp = state->comp;
1558 }
1559 status_t err = comp->stop();
1560 if (err != C2_OK) {
1561 // TODO: convert err into status_t
1562 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1563 }
1564
1565 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001566 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1567 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001568 if (config->mInputSurface) {
1569 config->mInputSurface->disconnect();
1570 config->mInputSurface = nullptr;
1571 }
1572 }
1573 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001574 Mutexed<State>::Locked state(mState);
1575 if (state->get() == STOPPING) {
1576 state->set(ALLOCATED);
1577 }
1578 }
1579 mCallback->onStopCompleted();
1580}
1581
1582void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001583 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001584 {
1585 Mutexed<State>::Locked state(mState);
1586 if (state->get() == RELEASED || state->get() == RELEASING) {
1587 // We're already released or doing it right now.
1588 if (sendCallback) {
1589 state.unlock();
1590 mCallback->onReleaseCompleted();
1591 state.lock();
1592 }
1593 return;
1594 }
1595 if (state->get() == ALLOCATING) {
1596 state->set(RELEASING);
1597 // With the altered state allocate() would fail and clean up.
1598 if (sendCallback) {
1599 state.unlock();
1600 mCallback->onReleaseCompleted();
1601 state.lock();
1602 }
1603 return;
1604 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001605 if (state->get() == STARTING
1606 || state->get() == RUNNING
1607 || state->get() == STOPPING) {
1608 // Input surface may have been started, so clean up is needed.
1609 clearInputSurfaceIfNeeded = true;
1610 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001611 state->set(RELEASING);
1612 }
1613
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001614 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001615 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1616 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001617 if (config->mInputSurface) {
1618 config->mInputSurface->disconnect();
1619 config->mInputSurface = nullptr;
1620 }
1621 }
1622
Wonsik Kim936a89c2020-05-08 16:07:50 -07001623 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001624 // thiz holds strong ref to this while the thread is running.
1625 sp<CCodec> thiz(this);
1626 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1627}
1628
1629void CCodec::release(bool sendCallback) {
1630 std::shared_ptr<Codec2Client::Component> comp;
1631 {
1632 Mutexed<State>::Locked state(mState);
1633 if (state->get() == RELEASED) {
1634 if (sendCallback) {
1635 state.unlock();
1636 mCallback->onReleaseCompleted();
1637 state.lock();
1638 }
1639 return;
1640 }
1641 comp = state->comp;
1642 }
1643 comp->release();
1644
1645 {
1646 Mutexed<State>::Locked state(mState);
1647 state->set(RELEASED);
1648 state->comp.reset();
1649 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001650 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001651 if (sendCallback) {
1652 mCallback->onReleaseCompleted();
1653 }
1654}
1655
1656status_t CCodec::setSurface(const sp<Surface> &surface) {
1657 return mChannel->setSurface(surface);
1658}
1659
1660void CCodec::signalFlush() {
1661 status_t err = [this] {
1662 Mutexed<State>::Locked state(mState);
1663 if (state->get() == FLUSHED) {
1664 return ALREADY_EXISTS;
1665 }
1666 if (state->get() != RUNNING) {
1667 return UNKNOWN_ERROR;
1668 }
1669 state->set(FLUSHING);
1670 return OK;
1671 }();
1672 switch (err) {
1673 case ALREADY_EXISTS:
1674 mCallback->onFlushCompleted();
1675 return;
1676 case OK:
1677 break;
1678 default:
1679 mCallback->onError(err, ACTION_CODE_FATAL);
1680 return;
1681 }
1682
1683 mChannel->stop();
1684 (new AMessage(kWhatFlush, this))->post();
1685}
1686
1687void CCodec::flush() {
1688 std::shared_ptr<Codec2Client::Component> comp;
1689 auto checkFlushing = [this, &comp] {
1690 Mutexed<State>::Locked state(mState);
1691 if (state->get() != FLUSHING) {
1692 return UNKNOWN_ERROR;
1693 }
1694 comp = state->comp;
1695 return OK;
1696 };
1697 if (tryAndReportOnError(checkFlushing) != OK) {
1698 return;
1699 }
1700
1701 std::list<std::unique_ptr<C2Work>> flushedWork;
1702 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1703 {
1704 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1705 flushedWork.splice(flushedWork.end(), *queue);
1706 }
1707 if (err != C2_OK) {
1708 // TODO: convert err into status_t
1709 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1710 }
1711
1712 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001713
1714 {
1715 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001716 if (state->get() == FLUSHING) {
1717 state->set(FLUSHED);
1718 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001719 }
1720 mCallback->onFlushCompleted();
1721}
1722
1723void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001724 std::shared_ptr<Codec2Client::Component> comp;
1725 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001726 Mutexed<State>::Locked state(mState);
1727 if (state->get() != FLUSHED) {
1728 return UNKNOWN_ERROR;
1729 }
1730 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001731 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001732 return OK;
1733 };
1734 if (tryAndReportOnError(setResuming) != OK) {
1735 return;
1736 }
1737
Wonsik Kime75a5da2020-02-14 17:29:03 -08001738 {
1739 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1740 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001741 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001742 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001743 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001744 }
1745
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001746 (void)mChannel->start(nullptr, nullptr, [&]{
1747 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1748 const std::unique_ptr<Config> &config = *configLocked;
1749 return config->mBuffersBoundToCodec;
1750 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001751
1752 {
1753 Mutexed<State>::Locked state(mState);
1754 if (state->get() != RESUMING) {
1755 state.unlock();
1756 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1757 state.lock();
1758 return;
1759 }
1760 state->set(RUNNING);
1761 }
1762
1763 (void)mChannel->requestInitialInputBuffers();
1764}
1765
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001766void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001767 std::shared_ptr<Codec2Client::Component> comp;
1768 auto checkState = [this, &comp] {
1769 Mutexed<State>::Locked state(mState);
1770 if (state->get() == RELEASED) {
1771 return INVALID_OPERATION;
1772 }
1773 comp = state->comp;
1774 return OK;
1775 };
1776 if (tryAndReportOnError(checkState) != OK) {
1777 return;
1778 }
1779
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001780 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1781 // the behavior here.
1782 sp<AMessage> params = msg;
1783 int32_t bitrate;
1784 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1785 params = msg->dup();
1786 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1787 }
1788
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001789 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1790 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001791
1792 /**
1793 * Handle input surface parameters
1794 */
1795 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001796 && (config->mDomain & Config::IS_ENCODER)
1797 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001798 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001799
1800 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1801 config->mISConfig->mStopped = false;
1802 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1803 config->mISConfig->mStopped = true;
1804 }
1805
1806 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001807 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001808 config->mISConfig->mSuspended = value;
1809 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001810 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001811 }
1812
1813 (void)config->mInputSurface->configure(*config->mISConfig);
1814 if (config->mISConfig->mStopped) {
1815 config->mInputFormat->setInt64(
1816 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1817 }
1818 }
1819
1820 std::vector<std::unique_ptr<C2Param>> configUpdate;
1821 (void)config->getConfigUpdateFromSdkParams(
1822 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1823 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1824 // Parameter synchronization is not defined when using input surface. For now, route
1825 // these directly to the component.
1826 if (config->mInputSurface == nullptr
1827 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1828 || comp->getName().find("c2.android.") == 0)) {
1829 mChannel->setParameters(configUpdate);
1830 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08001831 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001832 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08001833 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001834 }
1835}
1836
1837void CCodec::signalEndOfInputStream() {
1838 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1839}
1840
1841void CCodec::signalRequestIDRFrame() {
1842 std::shared_ptr<Codec2Client::Component> comp;
1843 {
1844 Mutexed<State>::Locked state(mState);
1845 if (state->get() == RELEASED) {
1846 ALOGD("no IDR request sent since component is released");
1847 return;
1848 }
1849 comp = state->comp;
1850 }
1851 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001852 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1853 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001854 std::vector<std::unique_ptr<C2Param>> params;
1855 params.push_back(
1856 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1857 config->setParameters(comp, params, C2_MAY_BLOCK);
1858}
1859
Wonsik Kimab34ed62019-01-31 15:28:46 -08001860void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001861 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001862 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1863 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001864 }
1865 (new AMessage(kWhatWorkDone, this))->post();
1866}
1867
Wonsik Kimab34ed62019-01-31 15:28:46 -08001868void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1869 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001870 if (arrayIndex == 0) {
1871 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001872 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1873 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001874 if (config->mInputSurface) {
1875 config->mInputSurface->onInputBufferDone(frameIndex);
1876 }
1877 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001878}
1879
1880void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1881 TimePoint now = std::chrono::steady_clock::now();
1882 CCodecWatchdog::getInstance()->watch(this);
1883 switch (msg->what()) {
1884 case kWhatAllocate: {
1885 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001886 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001887 sp<RefBase> obj;
1888 CHECK(msg->findObject("codecInfo", &obj));
1889 allocate((MediaCodecInfo *)obj.get());
1890 break;
1891 }
1892 case kWhatConfigure: {
1893 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001894 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001895 sp<AMessage> format;
1896 CHECK(msg->findMessage("format", &format));
1897 configure(format);
1898 break;
1899 }
1900 case kWhatStart: {
1901 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001902 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001903 start();
1904 break;
1905 }
1906 case kWhatStop: {
1907 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001908 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001909 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001910 break;
1911 }
1912 case kWhatFlush: {
1913 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001914 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001915 flush();
1916 break;
1917 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001918 case kWhatRelease: {
1919 mChannel->release();
1920 mClient.reset();
1921 mClientListener.reset();
1922 break;
1923 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001924 case kWhatCreateInputSurface: {
1925 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001926 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001927 createInputSurface();
1928 break;
1929 }
1930 case kWhatSetInputSurface: {
1931 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001932 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001933 sp<RefBase> obj;
1934 CHECK(msg->findObject("surface", &obj));
1935 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1936 setInputSurface(surface);
1937 break;
1938 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001939 case kWhatWorkDone: {
1940 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001941 bool shouldPost = false;
1942 {
1943 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1944 if (queue->empty()) {
1945 break;
1946 }
1947 work.swap(queue->front());
1948 queue->pop_front();
1949 shouldPost = !queue->empty();
1950 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001951 if (shouldPost) {
1952 (new AMessage(kWhatWorkDone, this))->post();
1953 }
1954
Pawin Vongmasa36653902018-11-15 00:10:25 -08001955 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001956 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1957 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001958 Config::Watcher<C2StreamInitDataInfo::output> initData =
1959 config->watch<C2StreamInitDataInfo::output>();
1960 if (!work->worklets.empty()
1961 && (work->worklets.front()->output.flags
1962 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1963
1964 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001965 std::vector<std::unique_ptr<C2Param>> updates;
1966 for (const std::unique_ptr<C2Param> &param
1967 : work->worklets.front()->output.configUpdate) {
1968 updates.push_back(C2Param::Copy(*param));
1969 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001970 unsigned stream = 0;
1971 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1972 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1973 // move all info into output-stream #0 domain
1974 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1975 }
George Burgess IVc813a592020-02-22 22:54:44 -08001976
1977 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
1978 // for now only do the first block
1979 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001980 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1981 // block.crop().left, block.crop().top,
1982 // block.crop().width, block.crop().height,
1983 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08001984 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08001985 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1986 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07001987 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001988 }
1989 ++stream;
1990 }
1991
Wonsik Kim3b4349a2020-11-10 11:54:15 -08001992 sp<AMessage> outputFormat = config->mOutputFormat;
1993 config->updateConfiguration(updates, config->mOutputDomain);
1994 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001995
1996 // copy standard infos to graphic buffers if not already present (otherwise, we
1997 // may overwrite the actual intermediate value with a final value)
1998 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07001999 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002000 C2StreamRotationInfo::output::PARAM_TYPE,
2001 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2002 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2003 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08002004 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08002005 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2006 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2007 };
2008 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2009 if (buf->data().graphicBlocks().size()) {
2010 for (C2Param::Index ix : stdGfxInfos) {
2011 if (!buf->hasInfo(ix)) {
2012 const C2Param *param =
2013 config->getConfigParameterValue(ix.withStream(stream));
2014 if (param) {
2015 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2016 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2017 }
2018 }
2019 }
2020 }
2021 ++stream;
2022 }
2023 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002024 if (config->mInputSurface) {
2025 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2026 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002027 mChannel->onWorkDone(
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002028 std::move(work), config->mOutputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002029 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002030 break;
2031 }
2032 case kWhatWatch: {
2033 // watch message already posted; no-op.
2034 break;
2035 }
2036 default: {
2037 ALOGE("unrecognized message");
2038 break;
2039 }
2040 }
2041 setDeadline(TimePoint::max(), 0ms, "none");
2042}
2043
2044void CCodec::setDeadline(
2045 const TimePoint &now,
2046 const std::chrono::milliseconds &timeout,
2047 const char *name) {
2048 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2049 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2050 deadline->set(now + (timeout * mult), name);
2051}
2052
2053void CCodec::initiateReleaseIfStuck() {
2054 std::string name;
2055 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002056 {
2057 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002058 if (deadline->get() < std::chrono::steady_clock::now()) {
2059 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002060 }
2061 if (deadline->get() != TimePoint::max()) {
2062 pendingDeadline = true;
2063 }
2064 }
2065 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002066 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2067 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2068 if (elapsed >= kWorkDurationThreshold) {
2069 name = "queue";
2070 }
2071 if (elapsed > 0s) {
2072 pendingDeadline = true;
2073 }
2074 }
2075 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002076 // We're not stuck.
2077 if (pendingDeadline) {
2078 // If we are not stuck yet but still has deadline coming up,
2079 // post watch message to check back later.
2080 (new AMessage(kWhatWatch, this))->post();
2081 }
2082 return;
2083 }
2084
2085 ALOGW("previous call to %s exceeded timeout", name.c_str());
2086 initiateRelease(false);
2087 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2088}
2089
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002090// static
2091PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002092 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002093 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002094 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002095 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2096 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002097 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002098 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2099 sp<IGraphicBufferProducer> gbp;
2100 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2101 status_t err = gbs->initCheck();
2102 if (err != OK) {
2103 ALOGE("Failed to create persistent input surface: error %d", err);
2104 return nullptr;
2105 }
2106 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002107 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002108 } else {
2109 return nullptr;
2110 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002111 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002112 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002113 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002114 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002115 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002116}
2117
Wonsik Kimffb889a2020-05-28 11:32:25 -07002118class IntfCache {
2119public:
2120 IntfCache() = default;
2121
2122 status_t init(const std::string &name) {
2123 std::shared_ptr<Codec2Client::Interface> intf{
2124 Codec2Client::CreateInterfaceByName(name.c_str())};
2125 if (!intf) {
2126 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2127 mInitStatus = NO_INIT;
2128 return NO_INIT;
2129 }
2130 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2131 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2132 C2ParamField{&sUsage, &sUsage.value}));
2133 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2134 if (err != C2_OK) {
2135 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2136 name.c_str(), err);
2137 mFields[0].status = err;
2138 }
2139 std::vector<std::unique_ptr<C2Param>> params;
2140 err = intf->query(
2141 {&mApiFeatures},
2142 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2143 C2_MAY_BLOCK,
2144 &params);
2145 if (err != C2_OK && err != C2_BAD_INDEX) {
2146 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2147 name.c_str(), err);
2148 }
2149 while (!params.empty()) {
2150 C2Param *param = params.back().release();
2151 params.pop_back();
2152 if (!param) {
2153 continue;
2154 }
2155 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2156 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002157 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002158 }
2159 }
2160 mInitStatus = OK;
2161 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002162 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002163
2164 status_t initCheck() const { return mInitStatus; }
2165
2166 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2167 CHECK_EQ(1u, mFields.size());
2168 return mFields[0];
2169 }
2170
2171 const C2ApiFeaturesSetting &getApiFeatures() const {
2172 return mApiFeatures;
2173 }
2174
2175 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2176 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2177 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2178 C2PortAllocatorsTuning::input::AllocUnique(0);
2179 param->invalidate();
2180 return param;
2181 }();
2182 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2183 }
2184
2185private:
2186 status_t mInitStatus{NO_INIT};
2187
2188 std::vector<C2FieldSupportedValuesQuery> mFields;
2189 C2ApiFeaturesSetting mApiFeatures;
2190 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2191};
2192
2193static const IntfCache &GetIntfCache(const std::string &name) {
2194 static IntfCache sNullIntfCache;
2195 static std::mutex sMutex;
2196 static std::map<std::string, IntfCache> sCache;
2197 std::unique_lock<std::mutex> lock{sMutex};
2198 auto it = sCache.find(name);
2199 if (it == sCache.end()) {
2200 lock.unlock();
2201 IntfCache intfCache;
2202 status_t err = intfCache.init(name);
2203 if (err != OK) {
2204 return sNullIntfCache;
2205 }
2206 lock.lock();
2207 it = sCache.insert({name, std::move(intfCache)}).first;
2208 }
2209 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002210}
2211
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002212static status_t GetCommonAllocatorIds(
2213 const std::vector<std::string> &names,
2214 C2Allocator::type_t type,
2215 std::set<C2Allocator::id_t> *ids) {
2216 int poolMask = GetCodec2PoolMask();
2217 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2218 C2Allocator::id_t defaultAllocatorId =
2219 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2220
2221 ids->clear();
2222 if (names.empty()) {
2223 return OK;
2224 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002225 bool firstIteration = true;
2226 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002227 const IntfCache &intfCache = GetIntfCache(name);
2228 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002229 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002230 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002231 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002232 if (firstIteration) {
2233 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002234 if (allocators && allocators.flexCount() > 0) {
2235 ids->insert(allocators.m.values,
2236 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002237 }
2238 if (ids->empty()) {
2239 // The component does not advertise allocators. Use default.
2240 ids->insert(defaultAllocatorId);
2241 }
2242 continue;
2243 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002244 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002245 if (allocators && allocators.flexCount() > 0) {
2246 filtered = true;
2247 for (auto it = ids->begin(); it != ids->end(); ) {
2248 bool found = false;
2249 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2250 if (allocators.m.values[j] == *it) {
2251 found = true;
2252 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002253 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002254 }
2255 if (found) {
2256 ++it;
2257 } else {
2258 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002259 }
2260 }
2261 }
2262 if (!filtered) {
2263 // The component does not advertise supported allocators. Use default.
2264 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2265 if (ids->size() != (containsDefault ? 1 : 0)) {
2266 ids->clear();
2267 if (containsDefault) {
2268 ids->insert(defaultAllocatorId);
2269 }
2270 }
2271 }
2272 }
2273 // Finally, filter with pool masks
2274 for (auto it = ids->begin(); it != ids->end(); ) {
2275 if ((poolMask >> *it) & 1) {
2276 ++it;
2277 } else {
2278 it = ids->erase(it);
2279 }
2280 }
2281 return OK;
2282}
2283
2284static status_t CalculateMinMaxUsage(
2285 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2286 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2287 *minUsage = 0;
2288 *maxUsage = ~0ull;
2289 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002290 const IntfCache &intfCache = GetIntfCache(name);
2291 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002292 continue;
2293 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002294 const C2FieldSupportedValuesQuery &usageSupportedValues =
2295 intfCache.getUsageSupportedValues();
2296 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002297 continue;
2298 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002299 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002300 if (supported.type != C2FieldSupportedValues::FLAGS) {
2301 continue;
2302 }
2303 if (supported.values.empty()) {
2304 *maxUsage = 0;
2305 continue;
2306 }
2307 *minUsage |= supported.values[0].u64;
2308 int64_t currentMaxUsage = 0;
2309 for (const C2Value::Primitive &flags : supported.values) {
2310 currentMaxUsage |= flags.u64;
2311 }
2312 *maxUsage &= currentMaxUsage;
2313 }
2314 return OK;
2315}
2316
2317// static
2318status_t CCodec::CanFetchLinearBlock(
2319 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002320 for (const std::string &name : names) {
2321 const IntfCache &intfCache = GetIntfCache(name);
2322 if (intfCache.initCheck() != OK) {
2323 continue;
2324 }
2325 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2326 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2327 *isCompatible = false;
2328 return OK;
2329 }
2330 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002331 std::set<C2Allocator::id_t> allocators;
2332 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2333 if (allocators.empty()) {
2334 *isCompatible = false;
2335 return OK;
2336 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002337
2338 uint64_t minUsage = 0;
2339 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002340 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002341 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002342 *isCompatible = ((maxUsage & minUsage) == minUsage);
2343 return OK;
2344}
2345
2346static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2347 static std::mutex sMutex{};
2348 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2349 std::unique_lock<std::mutex> lock{sMutex};
2350 std::shared_ptr<C2BlockPool> pool;
2351 auto it = sPools.find(allocId);
2352 if (it == sPools.end()) {
2353 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2354 if (err == OK) {
2355 sPools.emplace(allocId, pool);
2356 } else {
2357 pool.reset();
2358 }
2359 } else {
2360 pool = it->second;
2361 }
2362 return pool;
2363}
2364
2365// static
2366std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2367 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002368 std::set<C2Allocator::id_t> allocators;
2369 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2370 if (allocators.empty()) {
2371 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2372 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002373
2374 uint64_t minUsage = 0;
2375 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002376 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002377 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002378 if ((maxUsage & minUsage) != minUsage) {
2379 allocators.clear();
2380 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2381 }
2382 std::shared_ptr<C2LinearBlock> block;
2383 for (C2Allocator::id_t allocId : allocators) {
2384 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2385 if (!pool) {
2386 continue;
2387 }
2388 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2389 if (err != C2_OK || !block) {
2390 block.reset();
2391 continue;
2392 }
2393 break;
2394 }
2395 return block;
2396}
2397
2398// static
2399status_t CCodec::CanFetchGraphicBlock(
2400 const std::vector<std::string> &names, bool *isCompatible) {
2401 uint64_t minUsage = 0;
2402 uint64_t maxUsage = ~0ull;
2403 std::set<C2Allocator::id_t> allocators;
2404 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2405 if (allocators.empty()) {
2406 *isCompatible = false;
2407 return OK;
2408 }
2409 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2410 *isCompatible = ((maxUsage & minUsage) == minUsage);
2411 return OK;
2412}
2413
2414// static
2415std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2416 int32_t width,
2417 int32_t height,
2418 int32_t format,
2419 uint64_t usage,
2420 const std::vector<std::string> &names) {
2421 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2422 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2423 ALOGD("Unrecognized pixel format: %d", format);
2424 return nullptr;
2425 }
2426 uint64_t minUsage = 0;
2427 uint64_t maxUsage = ~0ull;
2428 std::set<C2Allocator::id_t> allocators;
2429 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2430 if (allocators.empty()) {
2431 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2432 }
2433 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2434 minUsage |= usage;
2435 if ((maxUsage & minUsage) != minUsage) {
2436 allocators.clear();
2437 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2438 }
2439 std::shared_ptr<C2GraphicBlock> block;
2440 for (C2Allocator::id_t allocId : allocators) {
2441 std::shared_ptr<C2BlockPool> pool;
2442 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2443 if (err != C2_OK || !pool) {
2444 continue;
2445 }
2446 err = pool->fetchGraphicBlock(
2447 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2448 if (err != C2_OK || !block) {
2449 block.reset();
2450 continue;
2451 }
2452 break;
2453 }
2454 return block;
2455}
2456
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002457} // namespace android
2458