blob: e2e92bc16f6b4e3800cbd2dea5660a42ecc79de9 [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 Kim970bf0b2020-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 {
546 // TODO
547 (void)component;
548 (void)errorCode;
549 }
550
551 virtual void onDeath(
552 const std::weak_ptr<Codec2Client::Component>& component) override {
553 { // Log the death of the component.
554 std::shared_ptr<Codec2Client::Component> comp = component.lock();
555 if (!comp) {
556 ALOGE("Codec2 component died.");
557 } else {
558 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
559 }
560 }
561
562 // Report to MediaCodec.
563 sp<CCodec> codec(mCodec.promote());
564 if (!codec || !codec->mCallback) {
565 return;
566 }
567 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
568 }
569
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800570 virtual void onFrameRendered(uint64_t bufferQueueId,
571 int32_t slotId,
572 int64_t timestampNs) override {
573 // TODO: implement
574 (void)bufferQueueId;
575 (void)slotId;
576 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800577 }
578
579 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800580 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800581 sp<CCodec> codec(mCodec.promote());
582 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800583 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800584 }
585 }
586
587private:
588 wp<CCodec> mCodec;
589};
590
591// CCodecCallbackImpl
592
593class CCodecCallbackImpl : public CCodecCallback {
594public:
595 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
596 ~CCodecCallbackImpl() override = default;
597
598 void onError(status_t err, enum ActionCode actionCode) override {
599 mCodec->mCallback->onError(err, actionCode);
600 }
601
602 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
603 mCodec->mCallback->onOutputFramesRendered(
604 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
605 }
606
Pawin Vongmasa36653902018-11-15 00:10:25 -0800607 void onOutputBuffersChanged() override {
608 mCodec->mCallback->onOutputBuffersChanged();
609 }
610
611private:
612 CCodec *mCodec;
613};
614
615// CCodec
616
617CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700618 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
619 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800620}
621
622CCodec::~CCodec() {
623}
624
625std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
626 return mChannel;
627}
628
629status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
630 status_t err = job();
631 if (err != C2_OK) {
632 mCallback->onError(err, ACTION_CODE_FATAL);
633 }
634 return err;
635}
636
637void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
638 auto setAllocating = [this] {
639 Mutexed<State>::Locked state(mState);
640 if (state->get() != RELEASED) {
641 return INVALID_OPERATION;
642 }
643 state->set(ALLOCATING);
644 return OK;
645 };
646 if (tryAndReportOnError(setAllocating) != OK) {
647 return;
648 }
649
650 sp<RefBase> codecInfo;
651 CHECK(msg->findObject("codecInfo", &codecInfo));
652 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
653
654 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
655 allocMsg->setObject("codecInfo", codecInfo);
656 allocMsg->post();
657}
658
659void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
660 if (codecInfo == nullptr) {
661 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
662 return;
663 }
664 ALOGD("allocate(%s)", codecInfo->getCodecName());
665 mClientListener.reset(new ClientListener(this));
666
667 AString componentName = codecInfo->getCodecName();
668 std::shared_ptr<Codec2Client> client;
669
670 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700671 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800672 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800673 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800674 SetPreferredCodec2ComponentStore(
675 std::make_shared<Codec2ClientInterfaceWrapper>(client));
676 }
677
678 std::shared_ptr<Codec2Client::Component> comp =
679 Codec2Client::CreateComponentByName(
680 componentName.c_str(),
681 mClientListener,
682 &client);
683 if (!comp) {
684 ALOGE("Failed Create component: %s", componentName.c_str());
685 Mutexed<State>::Locked state(mState);
686 state->set(RELEASED);
687 state.unlock();
688 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
689 state.lock();
690 return;
691 }
692 ALOGI("Created component [%s]", componentName.c_str());
693 mChannel->setComponent(comp);
694 auto setAllocated = [this, comp, client] {
695 Mutexed<State>::Locked state(mState);
696 if (state->get() != ALLOCATING) {
697 state->set(RELEASED);
698 return UNKNOWN_ERROR;
699 }
700 state->set(ALLOCATED);
701 state->comp = comp;
702 mClient = client;
703 return OK;
704 };
705 if (tryAndReportOnError(setAllocated) != OK) {
706 return;
707 }
708
709 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700710 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
711 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800712 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800713 if (err != OK) {
714 ALOGW("Failed to initialize configuration support");
715 // TODO: report error once we complete implementation.
716 }
717 config->queryConfiguration(comp);
718
719 mCallback->onComponentAllocated(componentName.c_str());
720}
721
722void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
723 auto checkAllocated = [this] {
724 Mutexed<State>::Locked state(mState);
725 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
726 };
727 if (tryAndReportOnError(checkAllocated) != OK) {
728 return;
729 }
730
731 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
732 msg->setMessage("format", format);
733 msg->post();
734}
735
736void CCodec::configure(const sp<AMessage> &msg) {
737 std::shared_ptr<Codec2Client::Component> comp;
738 auto checkAllocated = [this, &comp] {
739 Mutexed<State>::Locked state(mState);
740 if (state->get() != ALLOCATED) {
741 state->set(RELEASED);
742 return UNKNOWN_ERROR;
743 }
744 comp = state->comp;
745 return OK;
746 };
747 if (tryAndReportOnError(checkAllocated) != OK) {
748 return;
749 }
750
751 auto doConfig = [msg, comp, this]() -> status_t {
752 AString mime;
753 if (!msg->findString("mime", &mime)) {
754 return BAD_VALUE;
755 }
756
757 int32_t encoder;
758 if (!msg->findInt32("encoder", &encoder)) {
759 encoder = false;
760 }
761
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800762 int32_t flags;
763 if (!msg->findInt32("flags", &flags)) {
764 return BAD_VALUE;
765 }
766
Pawin Vongmasa36653902018-11-15 00:10:25 -0800767 // TODO: read from intf()
768 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
769 return UNKNOWN_ERROR;
770 }
771
772 int32_t storeMeta;
773 if (encoder
774 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
775 && storeMeta != kMetadataBufferTypeInvalid) {
776 if (storeMeta != kMetadataBufferTypeANWBuffer) {
777 ALOGD("Only ANW buffers are supported for legacy metadata mode");
778 return BAD_VALUE;
779 }
780 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
781 }
782
783 sp<RefBase> obj;
784 sp<Surface> surface;
785 if (msg->findObject("native-window", &obj)) {
786 surface = static_cast<Surface *>(obj.get());
787 setSurface(surface);
788 }
789
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700790 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
791 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800792 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800793 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
794 ALOGD("[%s] buffers are %sbound to CCodec for this session",
795 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800796
Wonsik Kim1114eea2019-02-25 14:35:24 -0800797 // Enforce required parameters
798 int32_t i32;
799 float flt;
800 if (config->mDomain & Config::IS_AUDIO) {
801 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
802 ALOGD("sample rate is missing, which is required for audio components.");
803 return BAD_VALUE;
804 }
805 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
806 ALOGD("channel count is missing, which is required for audio components.");
807 return BAD_VALUE;
808 }
809 if ((config->mDomain & Config::IS_ENCODER)
810 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
811 && !msg->findInt32(KEY_BIT_RATE, &i32)
812 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
813 ALOGD("bitrate is missing, which is required for audio encoders.");
814 return BAD_VALUE;
815 }
816 }
817 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
818 if (!msg->findInt32(KEY_WIDTH, &i32)) {
819 ALOGD("width is missing, which is required for image/video components.");
820 return BAD_VALUE;
821 }
822 if (!msg->findInt32(KEY_HEIGHT, &i32)) {
823 ALOGD("height is missing, which is required for image/video components.");
824 return BAD_VALUE;
825 }
826 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700827 int32_t mode = BITRATE_MODE_VBR;
828 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700829 if (!msg->findInt32(KEY_QUALITY, &i32)) {
830 ALOGD("quality is missing, which is required for video encoders in CQ.");
831 return BAD_VALUE;
832 }
833 } else {
834 if (!msg->findInt32(KEY_BIT_RATE, &i32)
835 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
836 ALOGD("bitrate is missing, which is required for video encoders.");
837 return BAD_VALUE;
838 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800839 }
840 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
841 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
842 ALOGD("I frame interval is missing, which is required for video encoders.");
843 return BAD_VALUE;
844 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700845 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
846 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
847 ALOGD("frame rate is missing, which is required for video encoders.");
848 return BAD_VALUE;
849 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800850 }
851 }
852
Pawin Vongmasa36653902018-11-15 00:10:25 -0800853 /*
854 * Handle input surface configuration
855 */
856 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
857 && (config->mDomain & Config::IS_ENCODER)) {
858 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
859 {
860 config->mISConfig->mMinFps = 0;
861 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800862 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800863 config->mISConfig->mMinFps = 1e6 / value;
864 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700865 if (!msg->findFloat(
866 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
867 config->mISConfig->mMaxFps = -1;
868 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800869 config->mISConfig->mMinAdjustedFps = 0;
870 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800871 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800872 if (value < 0 && value >= INT32_MIN) {
873 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700874 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800875 } else if (value > 0 && value <= INT32_MAX) {
876 config->mISConfig->mMinAdjustedFps = 1e6 / value;
877 }
878 }
879 }
880
881 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700882 bool captureFpsFound = false;
883 double timeLapseFps;
884 float captureRate;
885 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
886 config->mISConfig->mCaptureFps = timeLapseFps;
887 captureFpsFound = true;
888 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
889 config->mISConfig->mCaptureFps = captureRate;
890 captureFpsFound = true;
891 }
892 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800893 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
894 }
895 }
896
897 {
898 config->mISConfig->mSuspended = false;
899 config->mISConfig->mSuspendAtUs = -1;
900 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800901 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800902 config->mISConfig->mSuspended = true;
903 }
904 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700905 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800906 }
907
908 /*
909 * Handle desired color format.
910 */
911 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
912 int32_t format = -1;
913 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
914 /*
915 * Also handle default color format (encoders require color format, so this is only
916 * needed for decoders.
917 */
918 if (!(config->mDomain & Config::IS_ENCODER)) {
919 format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
920 }
921 }
922
923 if (format >= 0) {
924 msg->setInt32("android._color-format", format);
925 }
926 }
927
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800928 int32_t subscribeToAllVendorParams;
929 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
930 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
931 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
932 }
933 }
934
Pawin Vongmasa36653902018-11-15 00:10:25 -0800935 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800936 // NOTE: We used to ignore "video-bitrate" at configure; replicate
937 // the behavior here.
938 sp<AMessage> sdkParams = msg;
939 int32_t videoBitrate;
940 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
941 sdkParams = msg->dup();
942 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
943 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800944 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800945 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800946 if (err != OK) {
947 ALOGW("failed to convert configuration to c2 params");
948 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700949
950 int32_t maxBframes = 0;
951 if ((config->mDomain & Config::IS_ENCODER)
952 && (config->mDomain & Config::IS_VIDEO)
953 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
954 && maxBframes > 0) {
955 std::unique_ptr<C2StreamGopTuning::output> gop =
956 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
957 gop->m.values[0] = { P_FRAME, UINT32_MAX };
958 gop->m.values[1] = {
959 C2Config::picture_type_t(P_FRAME | B_FRAME),
960 uint32_t(maxBframes)
961 };
962 configUpdate.push_back(std::move(gop));
963 }
964
Pawin Vongmasa36653902018-11-15 00:10:25 -0800965 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
966 if (err != OK) {
967 ALOGW("failed to configure c2 params");
968 return err;
969 }
970
971 std::vector<std::unique_ptr<C2Param>> params;
972 C2StreamUsageTuning::input usage(0u, 0u);
973 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700974 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800975
976 std::initializer_list<C2Param::Index> indices {
977 };
978 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700979 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -0800980 indices,
981 C2_DONT_BLOCK,
982 &params);
983 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
984 ALOGE("Failed to query component interface: %d", c2err);
985 return UNKNOWN_ERROR;
986 }
987 if (params.size() != indices.size()) {
988 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
989 indices.size(), params.size());
990 return UNKNOWN_ERROR;
991 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700992 if (usage) {
993 if (usage.value & C2MemoryUsage::CPU_READ) {
994 config->mInputFormat->setInt32("using-sw-read-often", true);
995 }
996 if (config->mISConfig) {
997 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
998 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
999 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001000 }
1001
1002 // NOTE: we don't blindly use client specified input size if specified as clients
1003 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1004 // client specified size is only used to ask for bigger buffers than component suggested
1005 // size.
1006 int32_t clientInputSize = 0;
1007 bool clientSpecifiedInputSize =
1008 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1009 // TEMP: enforce minimum buffer size of 1MB for video decoders
1010 // and 16K / 4K for audio encoders/decoders
1011 if (maxInputSize.value == 0) {
1012 if (config->mDomain & Config::IS_AUDIO) {
1013 maxInputSize.value = encoder ? 16384 : 4096;
1014 } else if (!encoder) {
1015 maxInputSize.value = 1048576u;
1016 }
1017 }
1018
1019 // verify that CSD fits into this size (if defined)
1020 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1021 sp<ABuffer> csd;
1022 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1023 if (csd && csd->size() > maxInputSize.value) {
1024 maxInputSize.value = csd->size();
1025 }
1026 }
1027 }
1028
1029 // TODO: do this based on component requiring linear allocator for input
1030 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1031 if (clientSpecifiedInputSize) {
1032 // Warn that we're overriding client's max input size if necessary.
1033 if ((uint32_t)clientInputSize < maxInputSize.value) {
1034 ALOGD("client requested max input size %d, which is smaller than "
1035 "what component recommended (%u); overriding with component "
1036 "recommendation.", clientInputSize, maxInputSize.value);
1037 ALOGW("This behavior is subject to change. It is recommended that "
1038 "app developers double check whether the requested "
1039 "max input size is in reasonable range.");
1040 } else {
1041 maxInputSize.value = clientInputSize;
1042 }
1043 }
1044 // Pass max input size on input format to the buffer channel (if supplied by the
1045 // component or by a default)
1046 if (maxInputSize.value) {
1047 config->mInputFormat->setInt32(
1048 KEY_MAX_INPUT_SIZE,
1049 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1050 }
1051 }
1052
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001053 int32_t clientPrepend;
1054 if ((config->mDomain & Config::IS_VIDEO)
1055 && (config->mDomain & Config::IS_ENCODER)
1056 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1057 && clientPrepend
1058 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1059 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1060 return BAD_VALUE;
1061 }
1062
Pawin Vongmasa36653902018-11-15 00:10:25 -08001063 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1064 // propagate HDR static info to output format for both encoders and decoders
1065 // if component supports this info, we will update from component, but only the raw port,
1066 // so don't propagate if component already filled it in.
1067 sp<ABuffer> hdrInfo;
1068 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1069 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1070 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1071 }
1072
1073 // Set desired color format from configuration parameter
1074 int32_t format;
1075 if (msg->findInt32("android._color-format", &format)) {
1076 if (config->mDomain & Config::IS_ENCODER) {
1077 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
1078 } else {
1079 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
1080 }
1081 }
1082 }
1083
1084 // propagate encoder delay and padding to output format
1085 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1086 int delay = 0;
1087 if (msg->findInt32("encoder-delay", &delay)) {
1088 config->mOutputFormat->setInt32("encoder-delay", delay);
1089 }
1090 int padding = 0;
1091 if (msg->findInt32("encoder-padding", &padding)) {
1092 config->mOutputFormat->setInt32("encoder-padding", padding);
1093 }
1094 }
1095
1096 // set channel-mask
1097 if (config->mDomain & Config::IS_AUDIO) {
1098 int32_t mask;
1099 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1100 if (config->mDomain & Config::IS_ENCODER) {
1101 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1102 } else {
1103 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1104 }
1105 }
1106 }
1107
1108 ALOGD("setup formats input: %s and output: %s",
1109 config->mInputFormat->debugString().c_str(),
1110 config->mOutputFormat->debugString().c_str());
1111 return OK;
1112 };
1113 if (tryAndReportOnError(doConfig) != OK) {
1114 return;
1115 }
1116
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001117 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1118 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001119
1120 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1121}
1122
1123void CCodec::initiateCreateInputSurface() {
1124 status_t err = [this] {
1125 Mutexed<State>::Locked state(mState);
1126 if (state->get() != ALLOCATED) {
1127 return UNKNOWN_ERROR;
1128 }
1129 // TODO: read it from intf() properly.
1130 if (state->comp->getName().find("encoder") == std::string::npos) {
1131 return INVALID_OPERATION;
1132 }
1133 return OK;
1134 }();
1135 if (err != OK) {
1136 mCallback->onInputSurfaceCreationFailed(err);
1137 return;
1138 }
1139
1140 (new AMessage(kWhatCreateInputSurface, this))->post();
1141}
1142
Lajos Molnar47118272019-01-31 16:28:04 -08001143sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1144 using namespace android::hardware::media::omx::V1_0;
1145 using namespace android::hardware::media::omx::V1_0::utils;
1146 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1147 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1148 android::sp<IOmx> omx = IOmx::getService();
1149 typedef android::hardware::graphics::bufferqueue::V1_0::
1150 IGraphicBufferProducer HGraphicBufferProducer;
1151 typedef android::hardware::media::omx::V1_0::
1152 IGraphicBufferSource HGraphicBufferSource;
1153 OmxStatus s;
1154 android::sp<HGraphicBufferProducer> gbp;
1155 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001156
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001157 using ::android::hardware::Return;
1158 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001159 [&s, &gbp, &gbs](
1160 OmxStatus status,
1161 const android::sp<HGraphicBufferProducer>& producer,
1162 const android::sp<HGraphicBufferSource>& source) {
1163 s = status;
1164 gbp = producer;
1165 gbs = source;
1166 });
1167 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001168 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001169 }
1170
1171 return nullptr;
1172}
1173
1174sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1175 sp<PersistentSurface> surface(CreateInputSurface());
1176
1177 if (surface == nullptr) {
1178 surface = CreateOmxInputSurface();
1179 }
1180
1181 return surface;
1182}
1183
Pawin Vongmasa36653902018-11-15 00:10:25 -08001184void CCodec::createInputSurface() {
1185 status_t err;
1186 sp<IGraphicBufferProducer> bufferProducer;
1187
1188 sp<AMessage> inputFormat;
1189 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001190 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001191 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001192 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1193 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001194 inputFormat = config->mInputFormat;
1195 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001196 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001197 }
1198
Lajos Molnar47118272019-01-31 16:28:04 -08001199 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001200 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1201 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1202 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001203
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001204 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001205 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1206 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001207 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001208 inputSurface));
1209 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001210 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001211 int32_t width = 0;
1212 (void)outputFormat->findInt32("width", &width);
1213 int32_t height = 0;
1214 (void)outputFormat->findInt32("height", &height);
1215 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001216 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001217 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001218 } else {
1219 ALOGE("Corrupted input surface");
1220 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1221 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001222 }
1223
1224 if (err != OK) {
1225 ALOGE("Failed to set up input surface: %d", err);
1226 mCallback->onInputSurfaceCreationFailed(err);
1227 return;
1228 }
1229
1230 mCallback->onInputSurfaceCreated(
1231 inputFormat,
1232 outputFormat,
1233 new BufferProducerWrapper(bufferProducer));
1234}
1235
1236status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001237 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1238 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001239 config->mUsingSurface = true;
1240
1241 // we are now using surface - apply default color aspects to input format - as well as
1242 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001243 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001244 ALOGD("input format %s to %s",
1245 inputFormatChanged ? "changed" : "unchanged",
1246 config->mInputFormat->debugString().c_str());
1247
1248 // configure dataspace
1249 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1250 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1251 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1252 surface->setDataSpace(dataSpace);
1253
1254 status_t err = mChannel->setInputSurface(surface);
1255 if (err != OK) {
1256 // undo input format update
1257 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001258 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001259 return err;
1260 }
1261 config->mInputSurface = surface;
1262
1263 if (config->mISConfig) {
1264 surface->configure(*config->mISConfig);
1265 } else {
1266 ALOGD("ISConfig: no configuration");
1267 }
1268
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001269 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001270}
1271
1272void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1273 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1274 msg->setObject("surface", surface);
1275 msg->post();
1276}
1277
1278void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1279 sp<AMessage> inputFormat;
1280 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001281 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001282 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001283 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1284 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001285 inputFormat = config->mInputFormat;
1286 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001287 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001288 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001289 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1290 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1291 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1292 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001293 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1294 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1295 if (err != OK) {
1296 ALOGE("Failed to set up input surface: %d", err);
1297 mCallback->onInputSurfaceDeclined(err);
1298 return;
1299 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001300 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001301 int32_t width = 0;
1302 (void)outputFormat->findInt32("width", &width);
1303 int32_t height = 0;
1304 (void)outputFormat->findInt32("height", &height);
1305 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001306 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001307 if (err != OK) {
1308 ALOGE("Failed to set up input surface: %d", err);
1309 mCallback->onInputSurfaceDeclined(err);
1310 return;
1311 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001312 } else {
1313 ALOGE("Failed to set input surface: Corrupted surface.");
1314 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1315 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001316 }
1317 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1318}
1319
1320void CCodec::initiateStart() {
1321 auto setStarting = [this] {
1322 Mutexed<State>::Locked state(mState);
1323 if (state->get() != ALLOCATED) {
1324 return UNKNOWN_ERROR;
1325 }
1326 state->set(STARTING);
1327 return OK;
1328 };
1329 if (tryAndReportOnError(setStarting) != OK) {
1330 return;
1331 }
1332
1333 (new AMessage(kWhatStart, this))->post();
1334}
1335
1336void CCodec::start() {
1337 std::shared_ptr<Codec2Client::Component> comp;
1338 auto checkStarting = [this, &comp] {
1339 Mutexed<State>::Locked state(mState);
1340 if (state->get() != STARTING) {
1341 return UNKNOWN_ERROR;
1342 }
1343 comp = state->comp;
1344 return OK;
1345 };
1346 if (tryAndReportOnError(checkStarting) != OK) {
1347 return;
1348 }
1349
1350 c2_status_t err = comp->start();
1351 if (err != C2_OK) {
1352 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1353 ACTION_CODE_FATAL);
1354 return;
1355 }
1356 sp<AMessage> inputFormat;
1357 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001358 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001359 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001360 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001361 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1362 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001363 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001364 // start triggers format dup
1365 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001366 if (config->mInputSurface) {
1367 err2 = config->mInputSurface->start();
1368 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001369 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001370 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001371 if (err2 != OK) {
1372 mCallback->onError(err2, ACTION_CODE_FATAL);
1373 return;
1374 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001375 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001376 if (err2 != OK) {
1377 mCallback->onError(err2, ACTION_CODE_FATAL);
1378 return;
1379 }
1380
1381 auto setRunning = [this] {
1382 Mutexed<State>::Locked state(mState);
1383 if (state->get() != STARTING) {
1384 return UNKNOWN_ERROR;
1385 }
1386 state->set(RUNNING);
1387 return OK;
1388 };
1389 if (tryAndReportOnError(setRunning) != OK) {
1390 return;
1391 }
1392 mCallback->onStartCompleted();
1393
1394 (void)mChannel->requestInitialInputBuffers();
1395}
1396
1397void CCodec::initiateShutdown(bool keepComponentAllocated) {
1398 if (keepComponentAllocated) {
1399 initiateStop();
1400 } else {
1401 initiateRelease();
1402 }
1403}
1404
1405void CCodec::initiateStop() {
1406 {
1407 Mutexed<State>::Locked state(mState);
1408 if (state->get() == ALLOCATED
1409 || state->get() == RELEASED
1410 || state->get() == STOPPING
1411 || state->get() == RELEASING) {
1412 // We're already stopped, released, or doing it right now.
1413 state.unlock();
1414 mCallback->onStopCompleted();
1415 state.lock();
1416 return;
1417 }
1418 state->set(STOPPING);
1419 }
1420
Wonsik Kim936a89c2020-05-08 16:07:50 -07001421 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001422 (new AMessage(kWhatStop, this))->post();
1423}
1424
1425void CCodec::stop() {
1426 std::shared_ptr<Codec2Client::Component> comp;
1427 {
1428 Mutexed<State>::Locked state(mState);
1429 if (state->get() == RELEASING) {
1430 state.unlock();
1431 // We're already stopped or release is in progress.
1432 mCallback->onStopCompleted();
1433 state.lock();
1434 return;
1435 } else if (state->get() != STOPPING) {
1436 state.unlock();
1437 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1438 state.lock();
1439 return;
1440 }
1441 comp = state->comp;
1442 }
1443 status_t err = comp->stop();
1444 if (err != C2_OK) {
1445 // TODO: convert err into status_t
1446 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1447 }
1448
1449 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001450 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1451 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001452 if (config->mInputSurface) {
1453 config->mInputSurface->disconnect();
1454 config->mInputSurface = nullptr;
1455 }
1456 }
1457 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001458 Mutexed<State>::Locked state(mState);
1459 if (state->get() == STOPPING) {
1460 state->set(ALLOCATED);
1461 }
1462 }
1463 mCallback->onStopCompleted();
1464}
1465
1466void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001467 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001468 {
1469 Mutexed<State>::Locked state(mState);
1470 if (state->get() == RELEASED || state->get() == RELEASING) {
1471 // We're already released or doing it right now.
1472 if (sendCallback) {
1473 state.unlock();
1474 mCallback->onReleaseCompleted();
1475 state.lock();
1476 }
1477 return;
1478 }
1479 if (state->get() == ALLOCATING) {
1480 state->set(RELEASING);
1481 // With the altered state allocate() would fail and clean up.
1482 if (sendCallback) {
1483 state.unlock();
1484 mCallback->onReleaseCompleted();
1485 state.lock();
1486 }
1487 return;
1488 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001489 if (state->get() == STARTING
1490 || state->get() == RUNNING
1491 || state->get() == STOPPING) {
1492 // Input surface may have been started, so clean up is needed.
1493 clearInputSurfaceIfNeeded = true;
1494 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001495 state->set(RELEASING);
1496 }
1497
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001498 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001499 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1500 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001501 if (config->mInputSurface) {
1502 config->mInputSurface->disconnect();
1503 config->mInputSurface = nullptr;
1504 }
1505 }
1506
Wonsik Kim936a89c2020-05-08 16:07:50 -07001507 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001508 // thiz holds strong ref to this while the thread is running.
1509 sp<CCodec> thiz(this);
1510 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1511}
1512
1513void CCodec::release(bool sendCallback) {
1514 std::shared_ptr<Codec2Client::Component> comp;
1515 {
1516 Mutexed<State>::Locked state(mState);
1517 if (state->get() == RELEASED) {
1518 if (sendCallback) {
1519 state.unlock();
1520 mCallback->onReleaseCompleted();
1521 state.lock();
1522 }
1523 return;
1524 }
1525 comp = state->comp;
1526 }
1527 comp->release();
1528
1529 {
1530 Mutexed<State>::Locked state(mState);
1531 state->set(RELEASED);
1532 state->comp.reset();
1533 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001534 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001535 if (sendCallback) {
1536 mCallback->onReleaseCompleted();
1537 }
1538}
1539
1540status_t CCodec::setSurface(const sp<Surface> &surface) {
1541 return mChannel->setSurface(surface);
1542}
1543
1544void CCodec::signalFlush() {
1545 status_t err = [this] {
1546 Mutexed<State>::Locked state(mState);
1547 if (state->get() == FLUSHED) {
1548 return ALREADY_EXISTS;
1549 }
1550 if (state->get() != RUNNING) {
1551 return UNKNOWN_ERROR;
1552 }
1553 state->set(FLUSHING);
1554 return OK;
1555 }();
1556 switch (err) {
1557 case ALREADY_EXISTS:
1558 mCallback->onFlushCompleted();
1559 return;
1560 case OK:
1561 break;
1562 default:
1563 mCallback->onError(err, ACTION_CODE_FATAL);
1564 return;
1565 }
1566
1567 mChannel->stop();
1568 (new AMessage(kWhatFlush, this))->post();
1569}
1570
1571void CCodec::flush() {
1572 std::shared_ptr<Codec2Client::Component> comp;
1573 auto checkFlushing = [this, &comp] {
1574 Mutexed<State>::Locked state(mState);
1575 if (state->get() != FLUSHING) {
1576 return UNKNOWN_ERROR;
1577 }
1578 comp = state->comp;
1579 return OK;
1580 };
1581 if (tryAndReportOnError(checkFlushing) != OK) {
1582 return;
1583 }
1584
1585 std::list<std::unique_ptr<C2Work>> flushedWork;
1586 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1587 {
1588 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1589 flushedWork.splice(flushedWork.end(), *queue);
1590 }
1591 if (err != C2_OK) {
1592 // TODO: convert err into status_t
1593 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1594 }
1595
1596 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001597
1598 {
1599 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001600 if (state->get() == FLUSHING) {
1601 state->set(FLUSHED);
1602 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001603 }
1604 mCallback->onFlushCompleted();
1605}
1606
1607void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001608 std::shared_ptr<Codec2Client::Component> comp;
1609 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001610 Mutexed<State>::Locked state(mState);
1611 if (state->get() != FLUSHED) {
1612 return UNKNOWN_ERROR;
1613 }
1614 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001615 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001616 return OK;
1617 };
1618 if (tryAndReportOnError(setResuming) != OK) {
1619 return;
1620 }
1621
Wonsik Kime75a5da2020-02-14 17:29:03 -08001622 {
1623 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1624 const std::unique_ptr<Config> &config = *configLocked;
1625 config->queryConfiguration(comp);
1626 }
1627
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001628 (void)mChannel->start(nullptr, nullptr, [&]{
1629 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1630 const std::unique_ptr<Config> &config = *configLocked;
1631 return config->mBuffersBoundToCodec;
1632 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001633
1634 {
1635 Mutexed<State>::Locked state(mState);
1636 if (state->get() != RESUMING) {
1637 state.unlock();
1638 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1639 state.lock();
1640 return;
1641 }
1642 state->set(RUNNING);
1643 }
1644
1645 (void)mChannel->requestInitialInputBuffers();
1646}
1647
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001648void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001649 std::shared_ptr<Codec2Client::Component> comp;
1650 auto checkState = [this, &comp] {
1651 Mutexed<State>::Locked state(mState);
1652 if (state->get() == RELEASED) {
1653 return INVALID_OPERATION;
1654 }
1655 comp = state->comp;
1656 return OK;
1657 };
1658 if (tryAndReportOnError(checkState) != OK) {
1659 return;
1660 }
1661
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001662 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1663 // the behavior here.
1664 sp<AMessage> params = msg;
1665 int32_t bitrate;
1666 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1667 params = msg->dup();
1668 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1669 }
1670
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001671 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1672 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001673
1674 /**
1675 * Handle input surface parameters
1676 */
1677 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001678 && (config->mDomain & Config::IS_ENCODER)
1679 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001680 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001681
1682 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1683 config->mISConfig->mStopped = false;
1684 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1685 config->mISConfig->mStopped = true;
1686 }
1687
1688 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001689 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001690 config->mISConfig->mSuspended = value;
1691 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001692 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001693 }
1694
1695 (void)config->mInputSurface->configure(*config->mISConfig);
1696 if (config->mISConfig->mStopped) {
1697 config->mInputFormat->setInt64(
1698 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1699 }
1700 }
1701
1702 std::vector<std::unique_ptr<C2Param>> configUpdate;
1703 (void)config->getConfigUpdateFromSdkParams(
1704 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1705 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1706 // Parameter synchronization is not defined when using input surface. For now, route
1707 // these directly to the component.
1708 if (config->mInputSurface == nullptr
1709 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1710 || comp->getName().find("c2.android.") == 0)) {
1711 mChannel->setParameters(configUpdate);
1712 } else {
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001713 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001714 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001715 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001716 }
1717}
1718
1719void CCodec::signalEndOfInputStream() {
1720 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1721}
1722
1723void CCodec::signalRequestIDRFrame() {
1724 std::shared_ptr<Codec2Client::Component> comp;
1725 {
1726 Mutexed<State>::Locked state(mState);
1727 if (state->get() == RELEASED) {
1728 ALOGD("no IDR request sent since component is released");
1729 return;
1730 }
1731 comp = state->comp;
1732 }
1733 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001734 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1735 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001736 std::vector<std::unique_ptr<C2Param>> params;
1737 params.push_back(
1738 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1739 config->setParameters(comp, params, C2_MAY_BLOCK);
1740}
1741
Wonsik Kimab34ed62019-01-31 15:28:46 -08001742void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001743 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001744 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1745 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001746 }
1747 (new AMessage(kWhatWorkDone, this))->post();
1748}
1749
Wonsik Kimab34ed62019-01-31 15:28:46 -08001750void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1751 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001752 if (arrayIndex == 0) {
1753 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001754 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1755 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001756 if (config->mInputSurface) {
1757 config->mInputSurface->onInputBufferDone(frameIndex);
1758 }
1759 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001760}
1761
1762void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1763 TimePoint now = std::chrono::steady_clock::now();
1764 CCodecWatchdog::getInstance()->watch(this);
1765 switch (msg->what()) {
1766 case kWhatAllocate: {
1767 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001768 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001769 sp<RefBase> obj;
1770 CHECK(msg->findObject("codecInfo", &obj));
1771 allocate((MediaCodecInfo *)obj.get());
1772 break;
1773 }
1774 case kWhatConfigure: {
1775 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001776 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001777 sp<AMessage> format;
1778 CHECK(msg->findMessage("format", &format));
1779 configure(format);
1780 break;
1781 }
1782 case kWhatStart: {
1783 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001784 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001785 start();
1786 break;
1787 }
1788 case kWhatStop: {
1789 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001790 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001791 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001792 break;
1793 }
1794 case kWhatFlush: {
1795 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001796 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001797 flush();
1798 break;
1799 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001800 case kWhatRelease: {
1801 mChannel->release();
1802 mClient.reset();
1803 mClientListener.reset();
1804 break;
1805 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001806 case kWhatCreateInputSurface: {
1807 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001808 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001809 createInputSurface();
1810 break;
1811 }
1812 case kWhatSetInputSurface: {
1813 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001814 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001815 sp<RefBase> obj;
1816 CHECK(msg->findObject("surface", &obj));
1817 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1818 setInputSurface(surface);
1819 break;
1820 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001821 case kWhatWorkDone: {
1822 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001823 bool shouldPost = false;
1824 {
1825 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1826 if (queue->empty()) {
1827 break;
1828 }
1829 work.swap(queue->front());
1830 queue->pop_front();
1831 shouldPost = !queue->empty();
1832 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001833 if (shouldPost) {
1834 (new AMessage(kWhatWorkDone, this))->post();
1835 }
1836
Pawin Vongmasa36653902018-11-15 00:10:25 -08001837 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001838 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1839 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001840 Config::Watcher<C2StreamInitDataInfo::output> initData =
1841 config->watch<C2StreamInitDataInfo::output>();
1842 if (!work->worklets.empty()
1843 && (work->worklets.front()->output.flags
1844 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1845
1846 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001847 std::vector<std::unique_ptr<C2Param>> updates;
1848 for (const std::unique_ptr<C2Param> &param
1849 : work->worklets.front()->output.configUpdate) {
1850 updates.push_back(C2Param::Copy(*param));
1851 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001852 unsigned stream = 0;
1853 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1854 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1855 // move all info into output-stream #0 domain
1856 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1857 }
George Burgess IVc813a592020-02-22 22:54:44 -08001858
1859 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
1860 // for now only do the first block
1861 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001862 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1863 // block.crop().left, block.crop().top,
1864 // block.crop().width, block.crop().height,
1865 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08001866 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08001867 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1868 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07001869 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001870 }
1871 ++stream;
1872 }
1873
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001874 sp<AMessage> outputFormat = config->mOutputFormat;
1875 config->updateConfiguration(updates, config->mOutputDomain);
1876 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001877
1878 // copy standard infos to graphic buffers if not already present (otherwise, we
1879 // may overwrite the actual intermediate value with a final value)
1880 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07001881 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001882 C2StreamRotationInfo::output::PARAM_TYPE,
1883 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1884 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1885 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001886 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001887 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1888 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1889 };
1890 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1891 if (buf->data().graphicBlocks().size()) {
1892 for (C2Param::Index ix : stdGfxInfos) {
1893 if (!buf->hasInfo(ix)) {
1894 const C2Param *param =
1895 config->getConfigParameterValue(ix.withStream(stream));
1896 if (param) {
1897 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1898 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1899 }
1900 }
1901 }
1902 }
1903 ++stream;
1904 }
1905 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001906 if (config->mInputSurface) {
1907 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
1908 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001909 mChannel->onWorkDone(
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001910 std::move(work), config->mOutputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001911 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001912 break;
1913 }
1914 case kWhatWatch: {
1915 // watch message already posted; no-op.
1916 break;
1917 }
1918 default: {
1919 ALOGE("unrecognized message");
1920 break;
1921 }
1922 }
1923 setDeadline(TimePoint::max(), 0ms, "none");
1924}
1925
1926void CCodec::setDeadline(
1927 const TimePoint &now,
1928 const std::chrono::milliseconds &timeout,
1929 const char *name) {
1930 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1931 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1932 deadline->set(now + (timeout * mult), name);
1933}
1934
1935void CCodec::initiateReleaseIfStuck() {
1936 std::string name;
1937 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001938 {
1939 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001940 if (deadline->get() < std::chrono::steady_clock::now()) {
1941 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001942 }
1943 if (deadline->get() != TimePoint::max()) {
1944 pendingDeadline = true;
1945 }
1946 }
1947 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001948 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1949 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1950 if (elapsed >= kWorkDurationThreshold) {
1951 name = "queue";
1952 }
1953 if (elapsed > 0s) {
1954 pendingDeadline = true;
1955 }
1956 }
1957 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001958 // We're not stuck.
1959 if (pendingDeadline) {
1960 // If we are not stuck yet but still has deadline coming up,
1961 // post watch message to check back later.
1962 (new AMessage(kWhatWatch, this))->post();
1963 }
1964 return;
1965 }
1966
1967 ALOGW("previous call to %s exceeded timeout", name.c_str());
1968 initiateRelease(false);
1969 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1970}
1971
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001972// static
1973PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07001974 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001975 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001976 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07001977 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1978 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001979 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07001980 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
1981 sp<IGraphicBufferProducer> gbp;
1982 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
1983 status_t err = gbs->initCheck();
1984 if (err != OK) {
1985 ALOGE("Failed to create persistent input surface: error %d", err);
1986 return nullptr;
1987 }
1988 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001989 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07001990 } else {
1991 return nullptr;
1992 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001993 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07001994 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001995 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07001996 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08001997 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001998}
1999
Wonsik Kimffb889a2020-05-28 11:32:25 -07002000class IntfCache {
2001public:
2002 IntfCache() = default;
2003
2004 status_t init(const std::string &name) {
2005 std::shared_ptr<Codec2Client::Interface> intf{
2006 Codec2Client::CreateInterfaceByName(name.c_str())};
2007 if (!intf) {
2008 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2009 mInitStatus = NO_INIT;
2010 return NO_INIT;
2011 }
2012 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2013 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2014 C2ParamField{&sUsage, &sUsage.value}));
2015 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2016 if (err != C2_OK) {
2017 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2018 name.c_str(), err);
2019 mFields[0].status = err;
2020 }
2021 std::vector<std::unique_ptr<C2Param>> params;
2022 err = intf->query(
2023 {&mApiFeatures},
2024 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2025 C2_MAY_BLOCK,
2026 &params);
2027 if (err != C2_OK && err != C2_BAD_INDEX) {
2028 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2029 name.c_str(), err);
2030 }
2031 while (!params.empty()) {
2032 C2Param *param = params.back().release();
2033 params.pop_back();
2034 if (!param) {
2035 continue;
2036 }
2037 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2038 mInputAllocators.reset(
2039 C2PortAllocatorsTuning::input::From(params[0].get()));
2040 }
2041 }
2042 mInitStatus = OK;
2043 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002044 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002045
2046 status_t initCheck() const { return mInitStatus; }
2047
2048 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2049 CHECK_EQ(1u, mFields.size());
2050 return mFields[0];
2051 }
2052
2053 const C2ApiFeaturesSetting &getApiFeatures() const {
2054 return mApiFeatures;
2055 }
2056
2057 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2058 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2059 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2060 C2PortAllocatorsTuning::input::AllocUnique(0);
2061 param->invalidate();
2062 return param;
2063 }();
2064 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2065 }
2066
2067private:
2068 status_t mInitStatus{NO_INIT};
2069
2070 std::vector<C2FieldSupportedValuesQuery> mFields;
2071 C2ApiFeaturesSetting mApiFeatures;
2072 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2073};
2074
2075static const IntfCache &GetIntfCache(const std::string &name) {
2076 static IntfCache sNullIntfCache;
2077 static std::mutex sMutex;
2078 static std::map<std::string, IntfCache> sCache;
2079 std::unique_lock<std::mutex> lock{sMutex};
2080 auto it = sCache.find(name);
2081 if (it == sCache.end()) {
2082 lock.unlock();
2083 IntfCache intfCache;
2084 status_t err = intfCache.init(name);
2085 if (err != OK) {
2086 return sNullIntfCache;
2087 }
2088 lock.lock();
2089 it = sCache.insert({name, std::move(intfCache)}).first;
2090 }
2091 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002092}
2093
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002094static status_t GetCommonAllocatorIds(
2095 const std::vector<std::string> &names,
2096 C2Allocator::type_t type,
2097 std::set<C2Allocator::id_t> *ids) {
2098 int poolMask = GetCodec2PoolMask();
2099 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2100 C2Allocator::id_t defaultAllocatorId =
2101 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2102
2103 ids->clear();
2104 if (names.empty()) {
2105 return OK;
2106 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002107 bool firstIteration = true;
2108 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002109 const IntfCache &intfCache = GetIntfCache(name);
2110 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002111 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002112 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002113 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002114 if (firstIteration) {
2115 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002116 if (allocators && allocators.flexCount() > 0) {
2117 ids->insert(allocators.m.values,
2118 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002119 }
2120 if (ids->empty()) {
2121 // The component does not advertise allocators. Use default.
2122 ids->insert(defaultAllocatorId);
2123 }
2124 continue;
2125 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002126 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002127 if (allocators && allocators.flexCount() > 0) {
2128 filtered = true;
2129 for (auto it = ids->begin(); it != ids->end(); ) {
2130 bool found = false;
2131 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2132 if (allocators.m.values[j] == *it) {
2133 found = true;
2134 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002135 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002136 }
2137 if (found) {
2138 ++it;
2139 } else {
2140 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002141 }
2142 }
2143 }
2144 if (!filtered) {
2145 // The component does not advertise supported allocators. Use default.
2146 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2147 if (ids->size() != (containsDefault ? 1 : 0)) {
2148 ids->clear();
2149 if (containsDefault) {
2150 ids->insert(defaultAllocatorId);
2151 }
2152 }
2153 }
2154 }
2155 // Finally, filter with pool masks
2156 for (auto it = ids->begin(); it != ids->end(); ) {
2157 if ((poolMask >> *it) & 1) {
2158 ++it;
2159 } else {
2160 it = ids->erase(it);
2161 }
2162 }
2163 return OK;
2164}
2165
2166static status_t CalculateMinMaxUsage(
2167 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2168 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2169 *minUsage = 0;
2170 *maxUsage = ~0ull;
2171 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002172 const IntfCache &intfCache = GetIntfCache(name);
2173 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002174 continue;
2175 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002176 const C2FieldSupportedValuesQuery &usageSupportedValues =
2177 intfCache.getUsageSupportedValues();
2178 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002179 continue;
2180 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002181 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002182 if (supported.type != C2FieldSupportedValues::FLAGS) {
2183 continue;
2184 }
2185 if (supported.values.empty()) {
2186 *maxUsage = 0;
2187 continue;
2188 }
2189 *minUsage |= supported.values[0].u64;
2190 int64_t currentMaxUsage = 0;
2191 for (const C2Value::Primitive &flags : supported.values) {
2192 currentMaxUsage |= flags.u64;
2193 }
2194 *maxUsage &= currentMaxUsage;
2195 }
2196 return OK;
2197}
2198
2199// static
2200status_t CCodec::CanFetchLinearBlock(
2201 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002202 for (const std::string &name : names) {
2203 const IntfCache &intfCache = GetIntfCache(name);
2204 if (intfCache.initCheck() != OK) {
2205 continue;
2206 }
2207 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2208 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2209 *isCompatible = false;
2210 return OK;
2211 }
2212 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002213 uint64_t minUsage = usage.expected;
2214 uint64_t maxUsage = ~0ull;
2215 std::set<C2Allocator::id_t> allocators;
2216 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2217 if (allocators.empty()) {
2218 *isCompatible = false;
2219 return OK;
2220 }
2221 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2222 *isCompatible = ((maxUsage & minUsage) == minUsage);
2223 return OK;
2224}
2225
2226static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2227 static std::mutex sMutex{};
2228 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2229 std::unique_lock<std::mutex> lock{sMutex};
2230 std::shared_ptr<C2BlockPool> pool;
2231 auto it = sPools.find(allocId);
2232 if (it == sPools.end()) {
2233 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2234 if (err == OK) {
2235 sPools.emplace(allocId, pool);
2236 } else {
2237 pool.reset();
2238 }
2239 } else {
2240 pool = it->second;
2241 }
2242 return pool;
2243}
2244
2245// static
2246std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2247 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
2248 uint64_t minUsage = usage.expected;
2249 uint64_t maxUsage = ~0ull;
2250 std::set<C2Allocator::id_t> allocators;
2251 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2252 if (allocators.empty()) {
2253 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2254 }
2255 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2256 if ((maxUsage & minUsage) != minUsage) {
2257 allocators.clear();
2258 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2259 }
2260 std::shared_ptr<C2LinearBlock> block;
2261 for (C2Allocator::id_t allocId : allocators) {
2262 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2263 if (!pool) {
2264 continue;
2265 }
2266 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2267 if (err != C2_OK || !block) {
2268 block.reset();
2269 continue;
2270 }
2271 break;
2272 }
2273 return block;
2274}
2275
2276// static
2277status_t CCodec::CanFetchGraphicBlock(
2278 const std::vector<std::string> &names, bool *isCompatible) {
2279 uint64_t minUsage = 0;
2280 uint64_t maxUsage = ~0ull;
2281 std::set<C2Allocator::id_t> allocators;
2282 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2283 if (allocators.empty()) {
2284 *isCompatible = false;
2285 return OK;
2286 }
2287 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2288 *isCompatible = ((maxUsage & minUsage) == minUsage);
2289 return OK;
2290}
2291
2292// static
2293std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2294 int32_t width,
2295 int32_t height,
2296 int32_t format,
2297 uint64_t usage,
2298 const std::vector<std::string> &names) {
2299 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2300 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2301 ALOGD("Unrecognized pixel format: %d", format);
2302 return nullptr;
2303 }
2304 uint64_t minUsage = 0;
2305 uint64_t maxUsage = ~0ull;
2306 std::set<C2Allocator::id_t> allocators;
2307 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2308 if (allocators.empty()) {
2309 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2310 }
2311 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2312 minUsage |= usage;
2313 if ((maxUsage & minUsage) != minUsage) {
2314 allocators.clear();
2315 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2316 }
2317 std::shared_ptr<C2GraphicBlock> block;
2318 for (C2Allocator::id_t allocId : allocators) {
2319 std::shared_ptr<C2BlockPool> pool;
2320 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2321 if (err != C2_OK || !pool) {
2322 continue;
2323 }
2324 err = pool->fetchGraphicBlock(
2325 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2326 if (err != C2_OK || !block) {
2327 block.reset();
2328 continue;
2329 }
2330 break;
2331 }
2332 return block;
2333}
2334
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002335} // namespace android
2336