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