blob: 5c387b3d8f3b44ce9c13a69fa227f2c7df6da9ba [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>
ted.sun765db4d2020-06-23 14:03:41 +080047#include <utils/NativeHandle.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080048
49#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080050#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070051#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080052#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080053#include "InputSurfaceWrapper.h"
54
55extern "C" android::PersistentSurface *CreateInputSurface();
56
57namespace android {
58
59using namespace std::chrono_literals;
60using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
61using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080062using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080063
Wonsik Kim9917d4a2019-10-24 12:56:38 -070064typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070065typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070066
Pawin Vongmasa36653902018-11-15 00:10:25 -080067namespace {
68
69class CCodecWatchdog : public AHandler {
70private:
71 enum {
72 kWhatWatch,
73 };
74 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
75
76public:
77 static sp<CCodecWatchdog> getInstance() {
78 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
79 static std::once_flag flag;
80 // Call Init() only once.
81 std::call_once(flag, Init, instance);
82 return instance;
83 }
84
85 ~CCodecWatchdog() = default;
86
87 void watch(sp<CCodec> codec) {
88 bool shouldPost = false;
89 {
90 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
91 // If a watch message is in flight, piggy-back this instance as well.
92 // Otherwise, post a new watch message.
93 shouldPost = codecs->empty();
94 codecs->emplace(codec);
95 }
96 if (shouldPost) {
97 ALOGV("posting watch message");
98 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
99 }
100 }
101
102protected:
103 void onMessageReceived(const sp<AMessage> &msg) {
104 switch (msg->what()) {
105 case kWhatWatch: {
106 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
107 ALOGV("watch for %zu codecs", codecs->size());
108 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
109 sp<CCodec> codec = it->promote();
110 if (codec == nullptr) {
111 continue;
112 }
113 codec->initiateReleaseIfStuck();
114 }
115 codecs->clear();
116 break;
117 }
118
119 default: {
120 TRESPASS("CCodecWatchdog: unrecognized message");
121 }
122 }
123 }
124
125private:
126 CCodecWatchdog() : mLooper(new ALooper) {}
127
128 static void Init(const sp<CCodecWatchdog> &thiz) {
129 ALOGV("Init");
130 thiz->mLooper->setName("CCodecWatchdog");
131 thiz->mLooper->registerHandler(thiz);
132 thiz->mLooper->start();
133 }
134
135 sp<ALooper> mLooper;
136
137 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
138};
139
140class C2InputSurfaceWrapper : public InputSurfaceWrapper {
141public:
142 explicit C2InputSurfaceWrapper(
143 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
144 mSurface(surface) {
145 }
146
147 ~C2InputSurfaceWrapper() override = default;
148
149 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
150 if (mConnection != nullptr) {
151 return ALREADY_EXISTS;
152 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800153 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800154 }
155
156 void disconnect() override {
157 if (mConnection != nullptr) {
158 mConnection->disconnect();
159 mConnection = nullptr;
160 }
161 }
162
163 status_t start() override {
164 // InputSurface does not distinguish started state
165 return OK;
166 }
167
168 status_t signalEndOfInputStream() override {
169 C2InputSurfaceEosTuning eos(true);
170 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800171 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800172 if (err != C2_OK) {
173 return UNKNOWN_ERROR;
174 }
175 return OK;
176 }
177
178 status_t configure(Config &config __unused) {
179 // TODO
180 return OK;
181 }
182
183private:
184 std::shared_ptr<Codec2Client::InputSurface> mSurface;
185 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
186};
187
188class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
189public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700190 typedef hardware::media::omx::V1_0::Status OmxStatus;
191
Pawin Vongmasa36653902018-11-15 00:10:25 -0800192 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700193 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800194 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700195 uint32_t height,
196 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800197 : mSource(source), mWidth(width), mHeight(height) {
198 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700199 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800200 }
201 ~GraphicBufferSourceWrapper() override = default;
202
203 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
204 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700205 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800206 mNode->setFrameSize(mWidth, mHeight);
207
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700208 // Usage is queried during configure(), so setting it beforehand.
209 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
210 (void)mNode->setParameter(
211 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
212 &usage, sizeof(usage));
213
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700214 mSource->configure(
215 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800216 return OK;
217 }
218
219 void disconnect() override {
220 if (mNode == nullptr) {
221 return;
222 }
223 sp<IOMXBufferSource> source = mNode->getSource();
224 if (source == nullptr) {
225 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
226 return;
227 }
228 source->onOmxIdle();
229 source->onOmxLoaded();
230 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700231 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800232 }
233
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700234 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
235 if (status.isOk()) {
236 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
237 } else if (status.isDeadObject()) {
238 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800239 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700240 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800241 }
242
243 status_t start() override {
244 sp<IOMXBufferSource> source = mNode->getSource();
245 if (source == nullptr) {
246 return NO_INIT;
247 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900248
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800249 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800250 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900251
Wonsik Kim34d66012021-03-01 16:40:33 -0800252 OMX_PARAM_PORTDEFINITIONTYPE param;
253 param.nPortIndex = kPortIndexInput;
254 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
255 &param, sizeof(param));
256 if (err == OK) {
257 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900258 }
259
260 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800261 source->onInputBufferAdded(i);
262 }
263
264 source->onOmxExecuting();
265 return OK;
266 }
267
268 status_t signalEndOfInputStream() override {
269 return GetStatus(mSource->signalEndOfInputStream());
270 }
271
272 status_t configure(Config &config) {
273 std::stringstream status;
274 status_t err = OK;
275
276 // handle each configuration granually, in case we need to handle part of the configuration
277 // elsewhere
278
279 // TRICKY: we do not unset frame delay repeating
280 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
281 int64_t us = 1e6 / config.mMinFps + 0.5;
282 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
283 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
284 if (res != OK) {
285 status << " (=> " << asString(res) << ")";
286 err = res;
287 }
288 mConfig.mMinFps = config.mMinFps;
289 }
290
291 // pts gap
292 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
293 if (mNode != nullptr) {
294 OMX_PARAM_U32TYPE ptrGapParam = {};
295 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700296 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800297 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
298 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700299 // float -> uint32_t is undefined if the value is negative.
300 // First convert to int32_t to ensure the expected behavior.
301 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800302 (void)mNode->setParameter(
303 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
304 &ptrGapParam, sizeof(ptrGapParam));
305 }
306 }
307
308 // max fps
309 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700310 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800311 && config.mMaxFps != mConfig.mMaxFps) {
312 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
313 status << " maxFps=" << config.mMaxFps;
314 if (res != OK) {
315 status << " (=> " << asString(res) << ")";
316 err = res;
317 }
318 mConfig.mMaxFps = config.mMaxFps;
319 }
320
321 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
322 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
323 status << " timeOffset " << config.mTimeOffsetUs << "us";
324 if (res != OK) {
325 status << " (=> " << asString(res) << ")";
326 err = res;
327 }
328 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
329 }
330
331 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
332 status_t res =
333 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
334 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
335 if (res != OK) {
336 status << " (=> " << asString(res) << ")";
337 err = res;
338 }
339 mConfig.mCaptureFps = config.mCaptureFps;
340 mConfig.mCodedFps = config.mCodedFps;
341 }
342
343 if (config.mStartAtUs != mConfig.mStartAtUs
344 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
345 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
346 status << " start at " << config.mStartAtUs << "us";
347 if (res != OK) {
348 status << " (=> " << asString(res) << ")";
349 err = res;
350 }
351 mConfig.mStartAtUs = config.mStartAtUs;
352 mConfig.mStopped = config.mStopped;
353 }
354
355 // suspend-resume
356 if (config.mSuspended != mConfig.mSuspended) {
357 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
358 status << " " << (config.mSuspended ? "suspend" : "resume")
359 << " at " << config.mSuspendAtUs << "us";
360 if (res != OK) {
361 status << " (=> " << asString(res) << ")";
362 err = res;
363 }
364 mConfig.mSuspended = config.mSuspended;
365 mConfig.mSuspendAtUs = config.mSuspendAtUs;
366 }
367
368 if (config.mStopped != mConfig.mStopped && config.mStopped) {
369 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
370 status << " stop at " << config.mStopAtUs << "us";
371 if (res != OK) {
372 status << " (=> " << asString(res) << ")";
373 err = res;
374 } else {
375 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700376 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
377 [&res, &delayUs = config.mInputDelayUs](
378 auto status, auto stopTimeOffsetUs) {
379 res = static_cast<status_t>(status);
380 delayUs = stopTimeOffsetUs;
381 });
382 if (!trans.isOk()) {
383 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
384 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800385 if (res != OK) {
386 status << " (=> " << asString(res) << ")";
387 } else {
388 status << "=" << config.mInputDelayUs << "us";
389 }
390 mConfig.mInputDelayUs = config.mInputDelayUs;
391 }
392 mConfig.mStopAtUs = config.mStopAtUs;
393 mConfig.mStopped = config.mStopped;
394 }
395
396 // color aspects (android._color-aspects)
397
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700398 // consumer usage is queried earlier.
399
Wonsik Kimbd557932019-07-02 15:51:20 -0700400 if (status.str().empty()) {
401 ALOGD("ISConfig not changed");
402 } else {
403 ALOGD("ISConfig%s", status.str().c_str());
404 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800405 return err;
406 }
407
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700408 void onInputBufferDone(c2_cntr64_t index) override {
409 mNode->onInputBufferDone(index);
410 }
411
Wonsik Kim673dd192021-01-29 14:58:12 -0800412 android_dataspace getDataspace() override {
413 return mNode->getDataspace();
414 }
415
Pawin Vongmasa36653902018-11-15 00:10:25 -0800416private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700417 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800418 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700419 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800420 uint32_t mWidth;
421 uint32_t mHeight;
422 Config mConfig;
423};
424
425class Codec2ClientInterfaceWrapper : public C2ComponentStore {
426 std::shared_ptr<Codec2Client> mClient;
427
428public:
429 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
430 : mClient(client) { }
431
432 virtual ~Codec2ClientInterfaceWrapper() = default;
433
434 virtual c2_status_t config_sm(
435 const std::vector<C2Param *> &params,
436 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
437 return mClient->config(params, C2_MAY_BLOCK, failures);
438 };
439
440 virtual c2_status_t copyBuffer(
441 std::shared_ptr<C2GraphicBuffer>,
442 std::shared_ptr<C2GraphicBuffer>) {
443 return C2_OMITTED;
444 }
445
446 virtual c2_status_t createComponent(
447 C2String, std::shared_ptr<C2Component> *const component) {
448 component->reset();
449 return C2_OMITTED;
450 }
451
452 virtual c2_status_t createInterface(
453 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
454 interface->reset();
455 return C2_OMITTED;
456 }
457
458 virtual c2_status_t query_sm(
459 const std::vector<C2Param *> &stackParams,
460 const std::vector<C2Param::Index> &heapParamIndices,
461 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
462 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
463 }
464
465 virtual c2_status_t querySupportedParams_nb(
466 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
467 return mClient->querySupportedParams(params);
468 }
469
470 virtual c2_status_t querySupportedValues_sm(
471 std::vector<C2FieldSupportedValuesQuery> &fields) const {
472 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
473 }
474
475 virtual C2String getName() const {
476 return mClient->getName();
477 }
478
479 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
480 return mClient->getParamReflector();
481 }
482
483 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
484 return std::vector<std::shared_ptr<const C2Component::Traits>>();
485 }
486};
487
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800488void RevertOutputFormatIfNeeded(
489 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
490 // We used to not report changes to these keys to the client.
491 const static std::set<std::string> sIgnoredKeys({
492 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800493 KEY_FRAME_RATE,
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800494 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800495 KEY_MAX_WIDTH,
496 KEY_MAX_HEIGHT,
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800497 "csd-0",
498 "csd-1",
499 "csd-2",
500 });
501 if (currentFormat == oldFormat) {
502 return;
503 }
504 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
505 AMessage::Type type;
506 for (size_t i = diff->countEntries(); i > 0; --i) {
507 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
508 diff->removeEntryAt(i - 1);
509 }
510 }
511 if (diff->countEntries() == 0) {
512 currentFormat = oldFormat;
513 }
514}
515
Pawin Vongmasa36653902018-11-15 00:10:25 -0800516} // namespace
517
518// CCodec::ClientListener
519
520struct CCodec::ClientListener : public Codec2Client::Listener {
521
522 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
523
524 virtual void onWorkDone(
525 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800526 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800527 (void)component;
528 sp<CCodec> codec(mCodec.promote());
529 if (!codec) {
530 return;
531 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800532 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800533 }
534
535 virtual void onTripped(
536 const std::weak_ptr<Codec2Client::Component>& component,
537 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
538 ) override {
539 // TODO
540 (void)component;
541 (void)settingResult;
542 }
543
544 virtual void onError(
545 const std::weak_ptr<Codec2Client::Component>& component,
546 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800547 {
548 // Component is only used for reporting as we use a separate listener for each instance
549 std::shared_ptr<Codec2Client::Component> comp = component.lock();
550 if (!comp) {
551 ALOGD("Component died with error: 0x%x", errorCode);
552 } else {
553 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
554 }
555 }
556
557 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800558 // Note: for now we do not propagate the error code to MediaCodec
559 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800560 sp<CCodec> codec(mCodec.promote());
561 if (!codec || !codec->mCallback) {
562 return;
563 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800564 codec->mCallback->onError(
565 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
566 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800567 }
568
569 virtual void onDeath(
570 const std::weak_ptr<Codec2Client::Component>& component) override {
571 { // Log the death of the component.
572 std::shared_ptr<Codec2Client::Component> comp = component.lock();
573 if (!comp) {
574 ALOGE("Codec2 component died.");
575 } else {
576 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
577 }
578 }
579
580 // Report to MediaCodec.
581 sp<CCodec> codec(mCodec.promote());
582 if (!codec || !codec->mCallback) {
583 return;
584 }
585 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
586 }
587
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800588 virtual void onFrameRendered(uint64_t bufferQueueId,
589 int32_t slotId,
590 int64_t timestampNs) override {
591 // TODO: implement
592 (void)bufferQueueId;
593 (void)slotId;
594 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800595 }
596
597 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800598 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800599 sp<CCodec> codec(mCodec.promote());
600 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800601 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800602 }
603 }
604
605private:
606 wp<CCodec> mCodec;
607};
608
609// CCodecCallbackImpl
610
611class CCodecCallbackImpl : public CCodecCallback {
612public:
613 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
614 ~CCodecCallbackImpl() override = default;
615
616 void onError(status_t err, enum ActionCode actionCode) override {
617 mCodec->mCallback->onError(err, actionCode);
618 }
619
620 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
621 mCodec->mCallback->onOutputFramesRendered(
622 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
623 }
624
Pawin Vongmasa36653902018-11-15 00:10:25 -0800625 void onOutputBuffersChanged() override {
626 mCodec->mCallback->onOutputBuffersChanged();
627 }
628
629private:
630 CCodec *mCodec;
631};
632
633// CCodec
634
635CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700636 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
637 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800638}
639
640CCodec::~CCodec() {
641}
642
643std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
644 return mChannel;
645}
646
647status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
648 status_t err = job();
649 if (err != C2_OK) {
650 mCallback->onError(err, ACTION_CODE_FATAL);
651 }
652 return err;
653}
654
655void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
656 auto setAllocating = [this] {
657 Mutexed<State>::Locked state(mState);
658 if (state->get() != RELEASED) {
659 return INVALID_OPERATION;
660 }
661 state->set(ALLOCATING);
662 return OK;
663 };
664 if (tryAndReportOnError(setAllocating) != OK) {
665 return;
666 }
667
668 sp<RefBase> codecInfo;
669 CHECK(msg->findObject("codecInfo", &codecInfo));
670 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
671
672 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
673 allocMsg->setObject("codecInfo", codecInfo);
674 allocMsg->post();
675}
676
677void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
678 if (codecInfo == nullptr) {
679 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
680 return;
681 }
682 ALOGD("allocate(%s)", codecInfo->getCodecName());
683 mClientListener.reset(new ClientListener(this));
684
685 AString componentName = codecInfo->getCodecName();
686 std::shared_ptr<Codec2Client> client;
687
688 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700689 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800690 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800691 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800692 SetPreferredCodec2ComponentStore(
693 std::make_shared<Codec2ClientInterfaceWrapper>(client));
694 }
695
696 std::shared_ptr<Codec2Client::Component> comp =
697 Codec2Client::CreateComponentByName(
698 componentName.c_str(),
699 mClientListener,
700 &client);
701 if (!comp) {
702 ALOGE("Failed Create component: %s", componentName.c_str());
703 Mutexed<State>::Locked state(mState);
704 state->set(RELEASED);
705 state.unlock();
706 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
707 state.lock();
708 return;
709 }
710 ALOGI("Created component [%s]", componentName.c_str());
711 mChannel->setComponent(comp);
712 auto setAllocated = [this, comp, client] {
713 Mutexed<State>::Locked state(mState);
714 if (state->get() != ALLOCATING) {
715 state->set(RELEASED);
716 return UNKNOWN_ERROR;
717 }
718 state->set(ALLOCATED);
719 state->comp = comp;
720 mClient = client;
721 return OK;
722 };
723 if (tryAndReportOnError(setAllocated) != OK) {
724 return;
725 }
726
727 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700728 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
729 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800730 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800731 if (err != OK) {
732 ALOGW("Failed to initialize configuration support");
733 // TODO: report error once we complete implementation.
734 }
735 config->queryConfiguration(comp);
736
737 mCallback->onComponentAllocated(componentName.c_str());
738}
739
740void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
741 auto checkAllocated = [this] {
742 Mutexed<State>::Locked state(mState);
743 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
744 };
745 if (tryAndReportOnError(checkAllocated) != OK) {
746 return;
747 }
748
749 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
750 msg->setMessage("format", format);
751 msg->post();
752}
753
754void CCodec::configure(const sp<AMessage> &msg) {
755 std::shared_ptr<Codec2Client::Component> comp;
756 auto checkAllocated = [this, &comp] {
757 Mutexed<State>::Locked state(mState);
758 if (state->get() != ALLOCATED) {
759 state->set(RELEASED);
760 return UNKNOWN_ERROR;
761 }
762 comp = state->comp;
763 return OK;
764 };
765 if (tryAndReportOnError(checkAllocated) != OK) {
766 return;
767 }
768
769 auto doConfig = [msg, comp, this]() -> status_t {
770 AString mime;
771 if (!msg->findString("mime", &mime)) {
772 return BAD_VALUE;
773 }
774
775 int32_t encoder;
776 if (!msg->findInt32("encoder", &encoder)) {
777 encoder = false;
778 }
779
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800780 int32_t flags;
781 if (!msg->findInt32("flags", &flags)) {
782 return BAD_VALUE;
783 }
784
Pawin Vongmasa36653902018-11-15 00:10:25 -0800785 // TODO: read from intf()
786 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
787 return UNKNOWN_ERROR;
788 }
789
790 int32_t storeMeta;
791 if (encoder
792 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
793 && storeMeta != kMetadataBufferTypeInvalid) {
794 if (storeMeta != kMetadataBufferTypeANWBuffer) {
795 ALOGD("Only ANW buffers are supported for legacy metadata mode");
796 return BAD_VALUE;
797 }
798 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
799 }
800
ted.sun765db4d2020-06-23 14:03:41 +0800801 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800802 sp<RefBase> obj;
803 sp<Surface> surface;
804 if (msg->findObject("native-window", &obj)) {
805 surface = static_cast<Surface *>(obj.get());
ted.sun765db4d2020-06-23 14:03:41 +0800806 // setup tunneled playback
807 if (surface != nullptr) {
808 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
809 const std::unique_ptr<Config> &config = *configLocked;
810 if ((config->mDomain & Config::IS_DECODER)
811 && (config->mDomain & Config::IS_VIDEO)) {
812 int32_t tunneled;
813 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
814 ALOGI("Configuring TUNNELED video playback.");
815
816 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
817 if (err != OK) {
818 ALOGE("configureTunneledVideoPlayback failed!");
819 return err;
820 }
821 config->mTunneled = true;
822 }
823 }
824 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800825 setSurface(surface);
826 }
827
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700828 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
829 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800830 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800831 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
832 ALOGD("[%s] buffers are %sbound to CCodec for this session",
833 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800834
Wonsik Kim1114eea2019-02-25 14:35:24 -0800835 // Enforce required parameters
836 int32_t i32;
837 float flt;
838 if (config->mDomain & Config::IS_AUDIO) {
839 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
840 ALOGD("sample rate is missing, which is required for audio components.");
841 return BAD_VALUE;
842 }
843 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
844 ALOGD("channel count is missing, which is required for audio components.");
845 return BAD_VALUE;
846 }
847 if ((config->mDomain & Config::IS_ENCODER)
848 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
849 && !msg->findInt32(KEY_BIT_RATE, &i32)
850 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
851 ALOGD("bitrate is missing, which is required for audio encoders.");
852 return BAD_VALUE;
853 }
854 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800855 int32_t width = 0;
856 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800857 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800858 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800859 ALOGD("width is missing, which is required for image/video components.");
860 return BAD_VALUE;
861 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800862 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800863 ALOGD("height is missing, which is required for image/video components.");
864 return BAD_VALUE;
865 }
866 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700867 int32_t mode = BITRATE_MODE_VBR;
868 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700869 if (!msg->findInt32(KEY_QUALITY, &i32)) {
870 ALOGD("quality is missing, which is required for video encoders in CQ.");
871 return BAD_VALUE;
872 }
873 } else {
874 if (!msg->findInt32(KEY_BIT_RATE, &i32)
875 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
876 ALOGD("bitrate is missing, which is required for video encoders.");
877 return BAD_VALUE;
878 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800879 }
880 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
881 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
882 ALOGD("I frame interval is missing, which is required for video encoders.");
883 return BAD_VALUE;
884 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700885 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
886 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
887 ALOGD("frame rate is missing, which is required for video encoders.");
888 return BAD_VALUE;
889 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800890 }
891 }
892
Pawin Vongmasa36653902018-11-15 00:10:25 -0800893 /*
894 * Handle input surface configuration
895 */
896 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
897 && (config->mDomain & Config::IS_ENCODER)) {
898 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
899 {
900 config->mISConfig->mMinFps = 0;
901 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800902 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800903 config->mISConfig->mMinFps = 1e6 / value;
904 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700905 if (!msg->findFloat(
906 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
907 config->mISConfig->mMaxFps = -1;
908 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800909 config->mISConfig->mMinAdjustedFps = 0;
910 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800911 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800912 if (value < 0 && value >= INT32_MIN) {
913 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700914 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800915 } else if (value > 0 && value <= INT32_MAX) {
916 config->mISConfig->mMinAdjustedFps = 1e6 / value;
917 }
918 }
919 }
920
921 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700922 bool captureFpsFound = false;
923 double timeLapseFps;
924 float captureRate;
925 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
926 config->mISConfig->mCaptureFps = timeLapseFps;
927 captureFpsFound = true;
928 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
929 config->mISConfig->mCaptureFps = captureRate;
930 captureFpsFound = true;
931 }
932 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800933 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
934 }
935 }
936
937 {
938 config->mISConfig->mSuspended = false;
939 config->mISConfig->mSuspendAtUs = -1;
940 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800941 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800942 config->mISConfig->mSuspended = true;
943 }
944 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700945 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800946 }
947
948 /*
949 * Handle desired color format.
950 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700951 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800952 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700953 int32_t format = 0;
954 // Query vendor format for Flexible YUV
955 std::vector<std::unique_ptr<C2Param>> heapParams;
956 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
957 if (mClient->query(
958 {},
959 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
960 C2_MAY_BLOCK,
961 &heapParams) == C2_OK
962 && heapParams.size() == 1u) {
963 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
964 heapParams[0].get());
965 } else {
966 pixelFormatInfo = nullptr;
967 }
968 std::optional<uint32_t> flexPixelFormat{};
969 std::optional<uint32_t> flexPlanarPixelFormat{};
970 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
971 if (pixelFormatInfo && *pixelFormatInfo) {
972 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
973 const C2FlexiblePixelFormatDescriptorStruct &desc =
974 pixelFormatInfo->m.values[i];
975 if (desc.bitDepth != 8
976 || desc.subsampling != C2Color::YUV_420
977 // TODO(b/180076105): some device report wrong layout
978 // || desc.layout == C2Color::INTERLEAVED_PACKED
979 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
980 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
981 continue;
982 }
983 if (!flexPixelFormat) {
984 flexPixelFormat = desc.pixelFormat;
985 }
986 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
987 flexPlanarPixelFormat = desc.pixelFormat;
988 }
989 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
990 flexSemiPlanarPixelFormat = desc.pixelFormat;
991 }
992 }
993 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800994 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700995 // Also handle default color format (encoders require color format, so this is only
996 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -0800997 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700998 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -0700999 const char *prefix = "";
1000 if (flexSemiPlanarPixelFormat) {
1001 format = COLOR_FormatYUV420SemiPlanar;
1002 prefix = "semi-";
1003 } else {
1004 format = COLOR_FormatYUV420Planar;
1005 }
1006 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1007 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001008 } else {
1009 format = COLOR_FormatSurface;
1010 }
1011 defaultColorFormat = format;
1012 }
1013 } else {
1014 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
1015 switch (format) {
1016 case COLOR_FormatYUV420Flexible:
1017 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
1018 break;
1019 case COLOR_FormatYUV420Planar:
1020 case COLOR_FormatYUV420PackedPlanar:
1021 format = flexPlanarPixelFormat.value_or(
1022 flexPixelFormat.value_or(format));
1023 break;
1024 case COLOR_FormatYUV420SemiPlanar:
1025 case COLOR_FormatYUV420PackedSemiPlanar:
1026 format = flexSemiPlanarPixelFormat.value_or(
1027 flexPixelFormat.value_or(format));
1028 break;
1029 default:
1030 // No-op
1031 break;
1032 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001033 }
1034 }
1035
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001036 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001037 msg->setInt32("android._color-format", format);
1038 }
1039 }
1040
Wonsik Kim77e97c72021-01-20 10:33:22 -08001041 /*
1042 * Handle dataspace
1043 */
1044 int32_t usingRecorder;
1045 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1046 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1047 int32_t width, height;
1048 if (msg->findInt32("width", &width)
1049 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001050 ColorAspects aspects;
1051 getColorAspectsFromFormat(msg, aspects);
1052 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001053 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001054 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1055 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001056 }
1057 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1058 ALOGD("setting dataspace to %x", dataSpace);
1059 }
1060
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001061 int32_t subscribeToAllVendorParams;
1062 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1063 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1064 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1065 }
1066 }
1067
Pawin Vongmasa36653902018-11-15 00:10:25 -08001068 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001069 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1070 // the behavior here.
1071 sp<AMessage> sdkParams = msg;
1072 int32_t videoBitrate;
1073 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1074 sdkParams = msg->dup();
1075 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1076 }
ted.sun765db4d2020-06-23 14:03:41 +08001077 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001078 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001079 if (err != OK) {
1080 ALOGW("failed to convert configuration to c2 params");
1081 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001082
1083 int32_t maxBframes = 0;
1084 if ((config->mDomain & Config::IS_ENCODER)
1085 && (config->mDomain & Config::IS_VIDEO)
1086 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1087 && maxBframes > 0) {
1088 std::unique_ptr<C2StreamGopTuning::output> gop =
1089 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1090 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1091 gop->m.values[1] = {
1092 C2Config::picture_type_t(P_FRAME | B_FRAME),
1093 uint32_t(maxBframes)
1094 };
1095 configUpdate.push_back(std::move(gop));
1096 }
1097
Ray Essicka9a724a2021-03-10 19:40:01 -08001098 if ((config->mDomain & Config::IS_ENCODER)
1099 && (config->mDomain & Config::IS_VIDEO)) {
1100 // we may not use all 3 of these entries
1101 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1102 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1103 0u /* stream */);
1104
1105 int ix = 0;
1106
1107 int32_t iMax = INT32_MAX;
1108 int32_t iMin = INT32_MIN;
1109 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1110 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1111 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1112 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1113 }
1114
1115 int32_t pMax = INT32_MAX;
1116 int32_t pMin = INT32_MIN;
1117 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1118 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1119 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1120 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1121 }
1122
1123 int32_t bMax = INT32_MAX;
1124 int32_t bMin = INT32_MIN;
1125 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1126 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1127 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1128 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1129 }
1130
1131 // adjust to reflect actual use.
1132 qp->setFlexCount(ix);
1133
1134 configUpdate.push_back(std::move(qp));
1135 }
1136
Pawin Vongmasa36653902018-11-15 00:10:25 -08001137 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1138 if (err != OK) {
1139 ALOGW("failed to configure c2 params");
1140 return err;
1141 }
1142
1143 std::vector<std::unique_ptr<C2Param>> params;
1144 C2StreamUsageTuning::input usage(0u, 0u);
1145 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001146 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001147
Wonsik Kim58d83332021-02-07 22:19:56 -08001148 C2Param::Index colorAspectsRequestIndex =
1149 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001150 std::initializer_list<C2Param::Index> indices {
Wonsik Kim58d83332021-02-07 22:19:56 -08001151 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001152 };
1153 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001154 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001155 indices,
1156 C2_DONT_BLOCK,
1157 &params);
1158 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1159 ALOGE("Failed to query component interface: %d", c2err);
1160 return UNKNOWN_ERROR;
1161 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001162 if (usage) {
1163 if (usage.value & C2MemoryUsage::CPU_READ) {
1164 config->mInputFormat->setInt32("using-sw-read-often", true);
1165 }
1166 if (config->mISConfig) {
1167 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1168 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1169 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001170 }
1171
1172 // NOTE: we don't blindly use client specified input size if specified as clients
1173 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1174 // client specified size is only used to ask for bigger buffers than component suggested
1175 // size.
1176 int32_t clientInputSize = 0;
1177 bool clientSpecifiedInputSize =
1178 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1179 // TEMP: enforce minimum buffer size of 1MB for video decoders
1180 // and 16K / 4K for audio encoders/decoders
1181 if (maxInputSize.value == 0) {
1182 if (config->mDomain & Config::IS_AUDIO) {
1183 maxInputSize.value = encoder ? 16384 : 4096;
1184 } else if (!encoder) {
1185 maxInputSize.value = 1048576u;
1186 }
1187 }
1188
1189 // verify that CSD fits into this size (if defined)
1190 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1191 sp<ABuffer> csd;
1192 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1193 if (csd && csd->size() > maxInputSize.value) {
1194 maxInputSize.value = csd->size();
1195 }
1196 }
1197 }
1198
1199 // TODO: do this based on component requiring linear allocator for input
1200 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1201 if (clientSpecifiedInputSize) {
1202 // Warn that we're overriding client's max input size if necessary.
1203 if ((uint32_t)clientInputSize < maxInputSize.value) {
1204 ALOGD("client requested max input size %d, which is smaller than "
1205 "what component recommended (%u); overriding with component "
1206 "recommendation.", clientInputSize, maxInputSize.value);
1207 ALOGW("This behavior is subject to change. It is recommended that "
1208 "app developers double check whether the requested "
1209 "max input size is in reasonable range.");
1210 } else {
1211 maxInputSize.value = clientInputSize;
1212 }
1213 }
1214 // Pass max input size on input format to the buffer channel (if supplied by the
1215 // component or by a default)
1216 if (maxInputSize.value) {
1217 config->mInputFormat->setInt32(
1218 KEY_MAX_INPUT_SIZE,
1219 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1220 }
1221 }
1222
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001223 int32_t clientPrepend;
1224 if ((config->mDomain & Config::IS_VIDEO)
1225 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001226 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001227 && clientPrepend
1228 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001229 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001230 return BAD_VALUE;
1231 }
1232
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001233 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001234 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1235 // propagate HDR static info to output format for both encoders and decoders
1236 // if component supports this info, we will update from component, but only the raw port,
1237 // so don't propagate if component already filled it in.
1238 sp<ABuffer> hdrInfo;
1239 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1240 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1241 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1242 }
1243
1244 // Set desired color format from configuration parameter
1245 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001246 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1247 format = defaultColorFormat;
1248 }
1249 if (config->mDomain & Config::IS_ENCODER) {
1250 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001251 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1252 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001253 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001254 } else {
1255 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001256 }
1257 }
1258
1259 // propagate encoder delay and padding to output format
1260 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1261 int delay = 0;
1262 if (msg->findInt32("encoder-delay", &delay)) {
1263 config->mOutputFormat->setInt32("encoder-delay", delay);
1264 }
1265 int padding = 0;
1266 if (msg->findInt32("encoder-padding", &padding)) {
1267 config->mOutputFormat->setInt32("encoder-padding", padding);
1268 }
1269 }
1270
1271 // set channel-mask
1272 if (config->mDomain & Config::IS_AUDIO) {
1273 int32_t mask;
1274 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1275 if (config->mDomain & Config::IS_ENCODER) {
1276 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1277 } else {
1278 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1279 }
1280 }
1281 }
1282
Wonsik Kim58d83332021-02-07 22:19:56 -08001283 std::unique_ptr<C2Param> colorTransferRequestParam;
1284 for (std::unique_ptr<C2Param> &param : params) {
1285 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1286 ALOGI("found color transfer request param");
1287 colorTransferRequestParam = std::move(param);
1288 }
1289 }
1290 int32_t colorTransferRequest = 0;
1291 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1292 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1293 colorTransferRequest = 0;
1294 }
1295
1296 if (colorTransferRequest != 0) {
1297 if (colorTransferRequestParam && *colorTransferRequestParam) {
1298 C2StreamColorAspectsInfo::output *info =
1299 static_cast<C2StreamColorAspectsInfo::output *>(
1300 colorTransferRequestParam.get());
1301 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1302 colorTransferRequest = 0;
1303 }
1304 } else {
1305 colorTransferRequest = 0;
1306 }
1307 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1308 }
1309
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001310 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1311 // Need to get stride/vstride
1312 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1313 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1314 // TODO: retrieve these values without allocating a buffer.
1315 // Currently allocating a buffer is necessary to retrieve the layout.
1316 int64_t blockUsage =
1317 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1318 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1319 width, height, pixelFormat, blockUsage, {comp->getName()});
1320 sp<GraphicBlockBuffer> buffer;
1321 if (block) {
1322 buffer = GraphicBlockBuffer::Allocate(
1323 config->mInputFormat,
1324 block,
1325 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1326 } else {
1327 ALOGD("Failed to allocate a graphic block "
1328 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1329 width, height, pixelFormat, (long long)blockUsage);
1330 // This means that byte buffer mode is not supported in this configuration
1331 // anyway. Skip setting stride/vstride to input format.
1332 }
1333 if (buffer) {
1334 sp<ABuffer> imageData = buffer->getImageData();
1335 MediaImage2 *img = nullptr;
1336 if (imageData && imageData->data()
1337 && imageData->size() >= sizeof(MediaImage2)) {
1338 img = (MediaImage2*)imageData->data();
1339 }
1340 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1341 int32_t stride = img->mPlane[0].mRowInc;
1342 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1343 if (img->mNumPlanes > 1 && stride > 0) {
1344 int64_t offsetDelta =
1345 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1346 if (offsetDelta % stride == 0) {
1347 int32_t vstride = int32_t(offsetDelta / stride);
1348 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1349 } else {
1350 ALOGD("Cannot report accurate slice height: "
1351 "offsetDelta = %lld stride = %d",
1352 (long long)offsetDelta, stride);
1353 }
1354 }
1355 }
1356 }
1357 }
1358 }
1359
1360 ALOGD("setup formats input: %s",
1361 config->mInputFormat->debugString().c_str());
1362 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001363 config->mOutputFormat->debugString().c_str());
1364 return OK;
1365 };
1366 if (tryAndReportOnError(doConfig) != OK) {
1367 return;
1368 }
1369
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001370 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1371 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001372
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001373 config->queryConfiguration(comp);
1374
Pawin Vongmasa36653902018-11-15 00:10:25 -08001375 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1376}
1377
1378void CCodec::initiateCreateInputSurface() {
1379 status_t err = [this] {
1380 Mutexed<State>::Locked state(mState);
1381 if (state->get() != ALLOCATED) {
1382 return UNKNOWN_ERROR;
1383 }
1384 // TODO: read it from intf() properly.
1385 if (state->comp->getName().find("encoder") == std::string::npos) {
1386 return INVALID_OPERATION;
1387 }
1388 return OK;
1389 }();
1390 if (err != OK) {
1391 mCallback->onInputSurfaceCreationFailed(err);
1392 return;
1393 }
1394
1395 (new AMessage(kWhatCreateInputSurface, this))->post();
1396}
1397
Lajos Molnar47118272019-01-31 16:28:04 -08001398sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1399 using namespace android::hardware::media::omx::V1_0;
1400 using namespace android::hardware::media::omx::V1_0::utils;
1401 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1402 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1403 android::sp<IOmx> omx = IOmx::getService();
1404 typedef android::hardware::graphics::bufferqueue::V1_0::
1405 IGraphicBufferProducer HGraphicBufferProducer;
1406 typedef android::hardware::media::omx::V1_0::
1407 IGraphicBufferSource HGraphicBufferSource;
1408 OmxStatus s;
1409 android::sp<HGraphicBufferProducer> gbp;
1410 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001411
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001412 using ::android::hardware::Return;
1413 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001414 [&s, &gbp, &gbs](
1415 OmxStatus status,
1416 const android::sp<HGraphicBufferProducer>& producer,
1417 const android::sp<HGraphicBufferSource>& source) {
1418 s = status;
1419 gbp = producer;
1420 gbs = source;
1421 });
1422 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001423 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001424 }
1425
1426 return nullptr;
1427}
1428
1429sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1430 sp<PersistentSurface> surface(CreateInputSurface());
1431
1432 if (surface == nullptr) {
1433 surface = CreateOmxInputSurface();
1434 }
1435
1436 return surface;
1437}
1438
Pawin Vongmasa36653902018-11-15 00:10:25 -08001439void CCodec::createInputSurface() {
1440 status_t err;
1441 sp<IGraphicBufferProducer> bufferProducer;
1442
1443 sp<AMessage> inputFormat;
1444 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001445 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001446 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001447 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1448 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001449 inputFormat = config->mInputFormat;
1450 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001451 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001452 }
1453
Lajos Molnar47118272019-01-31 16:28:04 -08001454 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001455 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1456 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1457 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001458
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001459 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001460 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1461 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001462 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001463 inputSurface));
1464 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001465 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001466 int32_t width = 0;
1467 (void)outputFormat->findInt32("width", &width);
1468 int32_t height = 0;
1469 (void)outputFormat->findInt32("height", &height);
1470 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001471 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001472 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001473 } else {
1474 ALOGE("Corrupted input surface");
1475 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1476 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001477 }
1478
1479 if (err != OK) {
1480 ALOGE("Failed to set up input surface: %d", err);
1481 mCallback->onInputSurfaceCreationFailed(err);
1482 return;
1483 }
1484
1485 mCallback->onInputSurfaceCreated(
1486 inputFormat,
1487 outputFormat,
1488 new BufferProducerWrapper(bufferProducer));
1489}
1490
1491status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001492 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1493 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001494 config->mUsingSurface = true;
1495
1496 // we are now using surface - apply default color aspects to input format - as well as
1497 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001498 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001499 ALOGD("input format %s to %s",
1500 inputFormatChanged ? "changed" : "unchanged",
1501 config->mInputFormat->debugString().c_str());
1502
1503 // configure dataspace
1504 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1505 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1506 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1507 surface->setDataSpace(dataSpace);
1508
1509 status_t err = mChannel->setInputSurface(surface);
1510 if (err != OK) {
1511 // undo input format update
1512 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001513 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001514 return err;
1515 }
1516 config->mInputSurface = surface;
1517
1518 if (config->mISConfig) {
1519 surface->configure(*config->mISConfig);
1520 } else {
1521 ALOGD("ISConfig: no configuration");
1522 }
1523
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001524 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001525}
1526
1527void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1528 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1529 msg->setObject("surface", surface);
1530 msg->post();
1531}
1532
1533void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1534 sp<AMessage> inputFormat;
1535 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001536 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001537 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001538 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1539 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001540 inputFormat = config->mInputFormat;
1541 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001542 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001543 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001544 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1545 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1546 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1547 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001548 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1549 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1550 if (err != OK) {
1551 ALOGE("Failed to set up input surface: %d", err);
1552 mCallback->onInputSurfaceDeclined(err);
1553 return;
1554 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001555 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001556 int32_t width = 0;
1557 (void)outputFormat->findInt32("width", &width);
1558 int32_t height = 0;
1559 (void)outputFormat->findInt32("height", &height);
1560 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001561 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001562 if (err != OK) {
1563 ALOGE("Failed to set up input surface: %d", err);
1564 mCallback->onInputSurfaceDeclined(err);
1565 return;
1566 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001567 } else {
1568 ALOGE("Failed to set input surface: Corrupted surface.");
1569 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1570 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001571 }
1572 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1573}
1574
1575void CCodec::initiateStart() {
1576 auto setStarting = [this] {
1577 Mutexed<State>::Locked state(mState);
1578 if (state->get() != ALLOCATED) {
1579 return UNKNOWN_ERROR;
1580 }
1581 state->set(STARTING);
1582 return OK;
1583 };
1584 if (tryAndReportOnError(setStarting) != OK) {
1585 return;
1586 }
1587
1588 (new AMessage(kWhatStart, this))->post();
1589}
1590
1591void CCodec::start() {
1592 std::shared_ptr<Codec2Client::Component> comp;
1593 auto checkStarting = [this, &comp] {
1594 Mutexed<State>::Locked state(mState);
1595 if (state->get() != STARTING) {
1596 return UNKNOWN_ERROR;
1597 }
1598 comp = state->comp;
1599 return OK;
1600 };
1601 if (tryAndReportOnError(checkStarting) != OK) {
1602 return;
1603 }
1604
1605 c2_status_t err = comp->start();
1606 if (err != C2_OK) {
1607 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1608 ACTION_CODE_FATAL);
1609 return;
1610 }
1611 sp<AMessage> inputFormat;
1612 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001613 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001614 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001615 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001616 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1617 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001618 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001619 // start triggers format dup
1620 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001621 if (config->mInputSurface) {
1622 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001623 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001624 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001625 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001626 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001627 if (err2 != OK) {
1628 mCallback->onError(err2, ACTION_CODE_FATAL);
1629 return;
1630 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001631 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001632 if (err2 != OK) {
1633 mCallback->onError(err2, ACTION_CODE_FATAL);
1634 return;
1635 }
1636
1637 auto setRunning = [this] {
1638 Mutexed<State>::Locked state(mState);
1639 if (state->get() != STARTING) {
1640 return UNKNOWN_ERROR;
1641 }
1642 state->set(RUNNING);
1643 return OK;
1644 };
1645 if (tryAndReportOnError(setRunning) != OK) {
1646 return;
1647 }
1648 mCallback->onStartCompleted();
1649
1650 (void)mChannel->requestInitialInputBuffers();
1651}
1652
1653void CCodec::initiateShutdown(bool keepComponentAllocated) {
1654 if (keepComponentAllocated) {
1655 initiateStop();
1656 } else {
1657 initiateRelease();
1658 }
1659}
1660
1661void CCodec::initiateStop() {
1662 {
1663 Mutexed<State>::Locked state(mState);
1664 if (state->get() == ALLOCATED
1665 || state->get() == RELEASED
1666 || state->get() == STOPPING
1667 || state->get() == RELEASING) {
1668 // We're already stopped, released, or doing it right now.
1669 state.unlock();
1670 mCallback->onStopCompleted();
1671 state.lock();
1672 return;
1673 }
1674 state->set(STOPPING);
1675 }
1676
Wonsik Kim936a89c2020-05-08 16:07:50 -07001677 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001678 (new AMessage(kWhatStop, this))->post();
1679}
1680
1681void CCodec::stop() {
1682 std::shared_ptr<Codec2Client::Component> comp;
1683 {
1684 Mutexed<State>::Locked state(mState);
1685 if (state->get() == RELEASING) {
1686 state.unlock();
1687 // We're already stopped or release is in progress.
1688 mCallback->onStopCompleted();
1689 state.lock();
1690 return;
1691 } else if (state->get() != STOPPING) {
1692 state.unlock();
1693 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1694 state.lock();
1695 return;
1696 }
1697 comp = state->comp;
1698 }
1699 status_t err = comp->stop();
1700 if (err != C2_OK) {
1701 // TODO: convert err into status_t
1702 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1703 }
1704
1705 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001706 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1707 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001708 if (config->mInputSurface) {
1709 config->mInputSurface->disconnect();
1710 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001711 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001712 }
1713 }
1714 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001715 Mutexed<State>::Locked state(mState);
1716 if (state->get() == STOPPING) {
1717 state->set(ALLOCATED);
1718 }
1719 }
1720 mCallback->onStopCompleted();
1721}
1722
1723void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001724 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001725 {
1726 Mutexed<State>::Locked state(mState);
1727 if (state->get() == RELEASED || state->get() == RELEASING) {
1728 // We're already released or doing it right now.
1729 if (sendCallback) {
1730 state.unlock();
1731 mCallback->onReleaseCompleted();
1732 state.lock();
1733 }
1734 return;
1735 }
1736 if (state->get() == ALLOCATING) {
1737 state->set(RELEASING);
1738 // With the altered state allocate() would fail and clean up.
1739 if (sendCallback) {
1740 state.unlock();
1741 mCallback->onReleaseCompleted();
1742 state.lock();
1743 }
1744 return;
1745 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001746 if (state->get() == STARTING
1747 || state->get() == RUNNING
1748 || state->get() == STOPPING) {
1749 // Input surface may have been started, so clean up is needed.
1750 clearInputSurfaceIfNeeded = true;
1751 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001752 state->set(RELEASING);
1753 }
1754
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001755 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001756 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1757 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001758 if (config->mInputSurface) {
1759 config->mInputSurface->disconnect();
1760 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001761 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001762 }
1763 }
1764
Wonsik Kim936a89c2020-05-08 16:07:50 -07001765 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001766 // thiz holds strong ref to this while the thread is running.
1767 sp<CCodec> thiz(this);
1768 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1769}
1770
1771void CCodec::release(bool sendCallback) {
1772 std::shared_ptr<Codec2Client::Component> comp;
1773 {
1774 Mutexed<State>::Locked state(mState);
1775 if (state->get() == RELEASED) {
1776 if (sendCallback) {
1777 state.unlock();
1778 mCallback->onReleaseCompleted();
1779 state.lock();
1780 }
1781 return;
1782 }
1783 comp = state->comp;
1784 }
1785 comp->release();
1786
1787 {
1788 Mutexed<State>::Locked state(mState);
1789 state->set(RELEASED);
1790 state->comp.reset();
1791 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001792 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001793 if (sendCallback) {
1794 mCallback->onReleaseCompleted();
1795 }
1796}
1797
1798status_t CCodec::setSurface(const sp<Surface> &surface) {
Wonsik Kim9c387412021-04-19 21:03:53 +00001799 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1800 const std::unique_ptr<Config> &config = *configLocked;
1801 if (config->mTunneled && config->mSidebandHandle != nullptr) {
1802 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
1803 status_t err = native_window_set_sideband_stream(
1804 nativeWindow.get(),
1805 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
1806 if (err != OK) {
1807 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
1808 nativeWindow.get(), config->mSidebandHandle->handle(), err);
1809 return err;
ted.sun765db4d2020-06-23 14:03:41 +08001810 }
1811 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001812 return mChannel->setSurface(surface);
1813}
1814
1815void CCodec::signalFlush() {
1816 status_t err = [this] {
1817 Mutexed<State>::Locked state(mState);
1818 if (state->get() == FLUSHED) {
1819 return ALREADY_EXISTS;
1820 }
1821 if (state->get() != RUNNING) {
1822 return UNKNOWN_ERROR;
1823 }
1824 state->set(FLUSHING);
1825 return OK;
1826 }();
1827 switch (err) {
1828 case ALREADY_EXISTS:
1829 mCallback->onFlushCompleted();
1830 return;
1831 case OK:
1832 break;
1833 default:
1834 mCallback->onError(err, ACTION_CODE_FATAL);
1835 return;
1836 }
1837
1838 mChannel->stop();
1839 (new AMessage(kWhatFlush, this))->post();
1840}
1841
1842void CCodec::flush() {
1843 std::shared_ptr<Codec2Client::Component> comp;
1844 auto checkFlushing = [this, &comp] {
1845 Mutexed<State>::Locked state(mState);
1846 if (state->get() != FLUSHING) {
1847 return UNKNOWN_ERROR;
1848 }
1849 comp = state->comp;
1850 return OK;
1851 };
1852 if (tryAndReportOnError(checkFlushing) != OK) {
1853 return;
1854 }
1855
1856 std::list<std::unique_ptr<C2Work>> flushedWork;
1857 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1858 {
1859 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1860 flushedWork.splice(flushedWork.end(), *queue);
1861 }
1862 if (err != C2_OK) {
1863 // TODO: convert err into status_t
1864 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1865 }
1866
1867 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001868
1869 {
1870 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001871 if (state->get() == FLUSHING) {
1872 state->set(FLUSHED);
1873 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001874 }
1875 mCallback->onFlushCompleted();
1876}
1877
1878void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001879 std::shared_ptr<Codec2Client::Component> comp;
1880 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001881 Mutexed<State>::Locked state(mState);
1882 if (state->get() != FLUSHED) {
1883 return UNKNOWN_ERROR;
1884 }
1885 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001886 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001887 return OK;
1888 };
1889 if (tryAndReportOnError(setResuming) != OK) {
1890 return;
1891 }
1892
Wonsik Kime75a5da2020-02-14 17:29:03 -08001893 {
1894 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1895 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001896 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001897 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001898 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001899 }
1900
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001901 (void)mChannel->start(nullptr, nullptr, [&]{
1902 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1903 const std::unique_ptr<Config> &config = *configLocked;
1904 return config->mBuffersBoundToCodec;
1905 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001906
1907 {
1908 Mutexed<State>::Locked state(mState);
1909 if (state->get() != RESUMING) {
1910 state.unlock();
1911 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1912 state.lock();
1913 return;
1914 }
1915 state->set(RUNNING);
1916 }
1917
1918 (void)mChannel->requestInitialInputBuffers();
1919}
1920
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001921void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001922 std::shared_ptr<Codec2Client::Component> comp;
1923 auto checkState = [this, &comp] {
1924 Mutexed<State>::Locked state(mState);
1925 if (state->get() == RELEASED) {
1926 return INVALID_OPERATION;
1927 }
1928 comp = state->comp;
1929 return OK;
1930 };
1931 if (tryAndReportOnError(checkState) != OK) {
1932 return;
1933 }
1934
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001935 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1936 // the behavior here.
1937 sp<AMessage> params = msg;
1938 int32_t bitrate;
1939 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1940 params = msg->dup();
1941 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1942 }
1943
Houxiang Dai5a97b472021-03-22 17:56:04 +08001944 int32_t syncId = 0;
1945 if (params->findInt32("audio-hw-sync", &syncId)
1946 || params->findInt32("hw-av-sync-id", &syncId)) {
1947 configureTunneledVideoPlayback(comp, nullptr, params);
1948 }
1949
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001950 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1951 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001952
1953 /**
1954 * Handle input surface parameters
1955 */
1956 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001957 && (config->mDomain & Config::IS_ENCODER)
1958 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001959 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001960
1961 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1962 config->mISConfig->mStopped = false;
1963 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1964 config->mISConfig->mStopped = true;
1965 }
1966
1967 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001968 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001969 config->mISConfig->mSuspended = value;
1970 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001971 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001972 }
1973
1974 (void)config->mInputSurface->configure(*config->mISConfig);
1975 if (config->mISConfig->mStopped) {
1976 config->mInputFormat->setInt64(
1977 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1978 }
1979 }
1980
1981 std::vector<std::unique_ptr<C2Param>> configUpdate;
1982 (void)config->getConfigUpdateFromSdkParams(
1983 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1984 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1985 // Parameter synchronization is not defined when using input surface. For now, route
1986 // these directly to the component.
1987 if (config->mInputSurface == nullptr
1988 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1989 || comp->getName().find("c2.android.") == 0)) {
1990 mChannel->setParameters(configUpdate);
1991 } else {
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001992 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001993 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim970bf0b2020-11-10 11:54:15 -08001994 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001995 }
1996}
1997
1998void CCodec::signalEndOfInputStream() {
1999 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2000}
2001
2002void CCodec::signalRequestIDRFrame() {
2003 std::shared_ptr<Codec2Client::Component> comp;
2004 {
2005 Mutexed<State>::Locked state(mState);
2006 if (state->get() == RELEASED) {
2007 ALOGD("no IDR request sent since component is released");
2008 return;
2009 }
2010 comp = state->comp;
2011 }
2012 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002013 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2014 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002015 std::vector<std::unique_ptr<C2Param>> params;
2016 params.push_back(
2017 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2018 config->setParameters(comp, params, C2_MAY_BLOCK);
2019}
2020
Wonsik Kim874ad382021-03-12 09:59:36 -08002021status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2022 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2023 const std::unique_ptr<Config> &config = *configLocked;
2024 return config->querySupportedParameters(names);
2025}
2026
2027status_t CCodec::describeParameter(
2028 const std::string &name, CodecParameterDescriptor *desc) {
2029 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2030 const std::unique_ptr<Config> &config = *configLocked;
2031 return config->describe(name, desc);
2032}
2033
2034status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2035 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2036 if (!comp) {
2037 return INVALID_OPERATION;
2038 }
2039 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2040 const std::unique_ptr<Config> &config = *configLocked;
2041 return config->subscribeToVendorConfigUpdate(comp, names);
2042}
2043
2044status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2045 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2046 if (!comp) {
2047 return INVALID_OPERATION;
2048 }
2049 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2050 const std::unique_ptr<Config> &config = *configLocked;
2051 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2052}
2053
Wonsik Kimab34ed62019-01-31 15:28:46 -08002054void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002055 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002056 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2057 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002058 }
2059 (new AMessage(kWhatWorkDone, this))->post();
2060}
2061
Wonsik Kimab34ed62019-01-31 15:28:46 -08002062void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2063 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002064 if (arrayIndex == 0) {
2065 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002066 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2067 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002068 if (config->mInputSurface) {
2069 config->mInputSurface->onInputBufferDone(frameIndex);
2070 }
2071 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002072}
2073
2074void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2075 TimePoint now = std::chrono::steady_clock::now();
2076 CCodecWatchdog::getInstance()->watch(this);
2077 switch (msg->what()) {
2078 case kWhatAllocate: {
2079 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002080 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002081 sp<RefBase> obj;
2082 CHECK(msg->findObject("codecInfo", &obj));
2083 allocate((MediaCodecInfo *)obj.get());
2084 break;
2085 }
2086 case kWhatConfigure: {
2087 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002088 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002089 sp<AMessage> format;
2090 CHECK(msg->findMessage("format", &format));
2091 configure(format);
2092 break;
2093 }
2094 case kWhatStart: {
2095 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002096 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002097 start();
2098 break;
2099 }
2100 case kWhatStop: {
2101 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002102 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002103 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002104 break;
2105 }
2106 case kWhatFlush: {
2107 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002108 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002109 flush();
2110 break;
2111 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002112 case kWhatRelease: {
2113 mChannel->release();
2114 mClient.reset();
2115 mClientListener.reset();
2116 break;
2117 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002118 case kWhatCreateInputSurface: {
2119 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002120 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002121 createInputSurface();
2122 break;
2123 }
2124 case kWhatSetInputSurface: {
2125 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002126 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002127 sp<RefBase> obj;
2128 CHECK(msg->findObject("surface", &obj));
2129 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2130 setInputSurface(surface);
2131 break;
2132 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002133 case kWhatWorkDone: {
2134 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002135 bool shouldPost = false;
2136 {
2137 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2138 if (queue->empty()) {
2139 break;
2140 }
2141 work.swap(queue->front());
2142 queue->pop_front();
2143 shouldPost = !queue->empty();
2144 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002145 if (shouldPost) {
2146 (new AMessage(kWhatWorkDone, this))->post();
2147 }
2148
Pawin Vongmasa36653902018-11-15 00:10:25 -08002149 // handle configuration changes in work done
Wonsik Kim9c387412021-04-19 21:03:53 +00002150 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2151 const std::unique_ptr<Config> &config = *configLocked;
2152 Config::Watcher<C2StreamInitDataInfo::output> initData =
2153 config->watch<C2StreamInitDataInfo::output>();
2154 if (!work->worklets.empty()
2155 && (work->worklets.front()->output.flags
2156 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002157
Wonsik Kim9c387412021-04-19 21:03:53 +00002158 // copy buffer info to config
2159 std::vector<std::unique_ptr<C2Param>> updates;
2160 for (const std::unique_ptr<C2Param> &param
2161 : work->worklets.front()->output.configUpdate) {
2162 updates.push_back(C2Param::Copy(*param));
2163 }
2164 unsigned stream = 0;
2165 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2166 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2167 // move all info into output-stream #0 domain
2168 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002169 }
George Burgess IVc813a592020-02-22 22:54:44 -08002170
Wonsik Kim9c387412021-04-19 21:03:53 +00002171 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2172 // for now only do the first block
2173 if (!blocks.empty()) {
2174 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2175 // block.crop().left, block.crop().top,
2176 // block.crop().width, block.crop().height,
2177 // block.width(), block.height());
2178 const C2ConstGraphicBlock &block = blocks[0];
2179 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
2180 updates.emplace_back(new C2StreamPictureSizeInfo::output(
2181 stream, block.crop().width, block.crop().height));
2182 }
2183 ++stream;
2184 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002185
Wonsik Kim9c387412021-04-19 21:03:53 +00002186 sp<AMessage> outputFormat = config->mOutputFormat;
2187 config->updateConfiguration(updates, config->mOutputDomain);
2188 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
2189
2190 // copy standard infos to graphic buffers if not already present (otherwise, we
2191 // may overwrite the actual intermediate value with a final value)
2192 stream = 0;
2193 const static C2Param::Index stdGfxInfos[] = {
2194 C2StreamRotationInfo::output::PARAM_TYPE,
2195 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2196 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2197 C2StreamHdrStaticInfo::output::PARAM_TYPE,
2198 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
2199 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2200 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2201 };
2202 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
2203 if (buf->data().graphicBlocks().size()) {
2204 for (C2Param::Index ix : stdGfxInfos) {
2205 if (!buf->hasInfo(ix)) {
2206 const C2Param *param =
2207 config->getConfigParameterValue(ix.withStream(stream));
2208 if (param) {
2209 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2210 buf->setInfo(std::static_pointer_cast<C2Info>(info));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002211 }
2212 }
2213 }
2214 }
Wonsik Kim9c387412021-04-19 21:03:53 +00002215 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002216 }
2217 }
Wonsik Kim9c387412021-04-19 21:03:53 +00002218 if (config->mInputSurface) {
2219 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2220 }
2221 mChannel->onWorkDone(
2222 std::move(work), config->mOutputFormat,
2223 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002224 break;
2225 }
2226 case kWhatWatch: {
2227 // watch message already posted; no-op.
2228 break;
2229 }
2230 default: {
2231 ALOGE("unrecognized message");
2232 break;
2233 }
2234 }
2235 setDeadline(TimePoint::max(), 0ms, "none");
2236}
2237
2238void CCodec::setDeadline(
2239 const TimePoint &now,
2240 const std::chrono::milliseconds &timeout,
2241 const char *name) {
2242 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2243 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2244 deadline->set(now + (timeout * mult), name);
2245}
2246
ted.sun765db4d2020-06-23 14:03:41 +08002247status_t CCodec::configureTunneledVideoPlayback(
2248 std::shared_ptr<Codec2Client::Component> comp,
2249 sp<NativeHandle> *sidebandHandle,
2250 const sp<AMessage> &msg) {
2251 std::vector<std::unique_ptr<C2SettingResult>> failures;
2252
2253 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2254 C2PortTunneledModeTuning::output::AllocUnique(
2255 1,
2256 C2PortTunneledModeTuning::Struct::SIDEBAND,
2257 C2PortTunneledModeTuning::Struct::REALTIME,
2258 0);
2259 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2260 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2261 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2262 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2263 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2264 } else {
2265 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2266 tunneledPlayback->setFlexCount(0);
2267 }
2268 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2269 if (c2err != C2_OK) {
2270 return UNKNOWN_ERROR;
2271 }
2272
Houxiang Dai5a97b472021-03-22 17:56:04 +08002273 if (sidebandHandle == nullptr) {
2274 return OK;
2275 }
2276
ted.sun765db4d2020-06-23 14:03:41 +08002277 std::vector<std::unique_ptr<C2Param>> params;
2278 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2279 if (c2err == C2_OK && params.size() == 1u) {
2280 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2281 C2PortTunnelHandleTuning::output::From(params[0].get());
2282 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2283 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2284 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2285 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2286 memcpy(handle->data, videoTunnelSideband->m.values,
2287 sizeof(int32_t) * videoTunnelSideband->flexCount());
2288 return OK;
2289 } else {
2290 return NO_MEMORY;
2291 }
2292 }
2293 return UNKNOWN_ERROR;
2294}
2295
Pawin Vongmasa36653902018-11-15 00:10:25 -08002296void CCodec::initiateReleaseIfStuck() {
2297 std::string name;
2298 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002299 {
2300 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002301 if (deadline->get() < std::chrono::steady_clock::now()) {
2302 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002303 }
2304 if (deadline->get() != TimePoint::max()) {
2305 pendingDeadline = true;
2306 }
2307 }
Wonsik Kim9c387412021-04-19 21:03:53 +00002308 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2309 const std::unique_ptr<Config> &config = *configLocked;
2310 if (config->mTunneled == false && name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002311 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2312 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2313 if (elapsed >= kWorkDurationThreshold) {
2314 name = "queue";
2315 }
2316 if (elapsed > 0s) {
2317 pendingDeadline = true;
2318 }
2319 }
2320 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002321 // We're not stuck.
2322 if (pendingDeadline) {
2323 // If we are not stuck yet but still has deadline coming up,
2324 // post watch message to check back later.
2325 (new AMessage(kWhatWatch, this))->post();
2326 }
2327 return;
2328 }
2329
2330 ALOGW("previous call to %s exceeded timeout", name.c_str());
2331 initiateRelease(false);
2332 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2333}
2334
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002335// static
2336PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002337 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002338 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002339 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002340 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2341 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002342 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002343 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2344 sp<IGraphicBufferProducer> gbp;
2345 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2346 status_t err = gbs->initCheck();
2347 if (err != OK) {
2348 ALOGE("Failed to create persistent input surface: error %d", err);
2349 return nullptr;
2350 }
2351 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002352 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002353 } else {
2354 return nullptr;
2355 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002356 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002357 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002358 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002359 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002360 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002361}
2362
Wonsik Kimffb889a2020-05-28 11:32:25 -07002363class IntfCache {
2364public:
2365 IntfCache() = default;
2366
2367 status_t init(const std::string &name) {
2368 std::shared_ptr<Codec2Client::Interface> intf{
2369 Codec2Client::CreateInterfaceByName(name.c_str())};
2370 if (!intf) {
2371 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2372 mInitStatus = NO_INIT;
2373 return NO_INIT;
2374 }
2375 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2376 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2377 C2ParamField{&sUsage, &sUsage.value}));
2378 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2379 if (err != C2_OK) {
2380 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2381 name.c_str(), err);
2382 mFields[0].status = err;
2383 }
2384 std::vector<std::unique_ptr<C2Param>> params;
2385 err = intf->query(
2386 {&mApiFeatures},
2387 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2388 C2_MAY_BLOCK,
2389 &params);
2390 if (err != C2_OK && err != C2_BAD_INDEX) {
2391 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2392 name.c_str(), err);
2393 }
2394 while (!params.empty()) {
2395 C2Param *param = params.back().release();
2396 params.pop_back();
2397 if (!param) {
2398 continue;
2399 }
2400 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2401 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002402 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002403 }
2404 }
2405 mInitStatus = OK;
2406 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002407 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002408
2409 status_t initCheck() const { return mInitStatus; }
2410
2411 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2412 CHECK_EQ(1u, mFields.size());
2413 return mFields[0];
2414 }
2415
2416 const C2ApiFeaturesSetting &getApiFeatures() const {
2417 return mApiFeatures;
2418 }
2419
2420 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2421 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2422 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2423 C2PortAllocatorsTuning::input::AllocUnique(0);
2424 param->invalidate();
2425 return param;
2426 }();
2427 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2428 }
2429
2430private:
2431 status_t mInitStatus{NO_INIT};
2432
2433 std::vector<C2FieldSupportedValuesQuery> mFields;
2434 C2ApiFeaturesSetting mApiFeatures;
2435 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2436};
2437
2438static const IntfCache &GetIntfCache(const std::string &name) {
2439 static IntfCache sNullIntfCache;
2440 static std::mutex sMutex;
2441 static std::map<std::string, IntfCache> sCache;
2442 std::unique_lock<std::mutex> lock{sMutex};
2443 auto it = sCache.find(name);
2444 if (it == sCache.end()) {
2445 lock.unlock();
2446 IntfCache intfCache;
2447 status_t err = intfCache.init(name);
2448 if (err != OK) {
2449 return sNullIntfCache;
2450 }
2451 lock.lock();
2452 it = sCache.insert({name, std::move(intfCache)}).first;
2453 }
2454 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002455}
2456
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002457static status_t GetCommonAllocatorIds(
2458 const std::vector<std::string> &names,
2459 C2Allocator::type_t type,
2460 std::set<C2Allocator::id_t> *ids) {
2461 int poolMask = GetCodec2PoolMask();
2462 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2463 C2Allocator::id_t defaultAllocatorId =
2464 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2465
2466 ids->clear();
2467 if (names.empty()) {
2468 return OK;
2469 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002470 bool firstIteration = true;
2471 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002472 const IntfCache &intfCache = GetIntfCache(name);
2473 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002474 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002475 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002476 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002477 if (firstIteration) {
2478 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002479 if (allocators && allocators.flexCount() > 0) {
2480 ids->insert(allocators.m.values,
2481 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002482 }
2483 if (ids->empty()) {
2484 // The component does not advertise allocators. Use default.
2485 ids->insert(defaultAllocatorId);
2486 }
2487 continue;
2488 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002489 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002490 if (allocators && allocators.flexCount() > 0) {
2491 filtered = true;
2492 for (auto it = ids->begin(); it != ids->end(); ) {
2493 bool found = false;
2494 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2495 if (allocators.m.values[j] == *it) {
2496 found = true;
2497 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002498 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002499 }
2500 if (found) {
2501 ++it;
2502 } else {
2503 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002504 }
2505 }
2506 }
2507 if (!filtered) {
2508 // The component does not advertise supported allocators. Use default.
2509 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2510 if (ids->size() != (containsDefault ? 1 : 0)) {
2511 ids->clear();
2512 if (containsDefault) {
2513 ids->insert(defaultAllocatorId);
2514 }
2515 }
2516 }
2517 }
2518 // Finally, filter with pool masks
2519 for (auto it = ids->begin(); it != ids->end(); ) {
2520 if ((poolMask >> *it) & 1) {
2521 ++it;
2522 } else {
2523 it = ids->erase(it);
2524 }
2525 }
2526 return OK;
2527}
2528
2529static status_t CalculateMinMaxUsage(
2530 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2531 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2532 *minUsage = 0;
2533 *maxUsage = ~0ull;
2534 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002535 const IntfCache &intfCache = GetIntfCache(name);
2536 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002537 continue;
2538 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002539 const C2FieldSupportedValuesQuery &usageSupportedValues =
2540 intfCache.getUsageSupportedValues();
2541 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002542 continue;
2543 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002544 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002545 if (supported.type != C2FieldSupportedValues::FLAGS) {
2546 continue;
2547 }
2548 if (supported.values.empty()) {
2549 *maxUsage = 0;
2550 continue;
2551 }
2552 *minUsage |= supported.values[0].u64;
2553 int64_t currentMaxUsage = 0;
2554 for (const C2Value::Primitive &flags : supported.values) {
2555 currentMaxUsage |= flags.u64;
2556 }
2557 *maxUsage &= currentMaxUsage;
2558 }
2559 return OK;
2560}
2561
2562// static
2563status_t CCodec::CanFetchLinearBlock(
2564 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002565 for (const std::string &name : names) {
2566 const IntfCache &intfCache = GetIntfCache(name);
2567 if (intfCache.initCheck() != OK) {
2568 continue;
2569 }
2570 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2571 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2572 *isCompatible = false;
2573 return OK;
2574 }
2575 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002576 uint64_t minUsage = usage.expected;
2577 uint64_t maxUsage = ~0ull;
2578 std::set<C2Allocator::id_t> allocators;
2579 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2580 if (allocators.empty()) {
2581 *isCompatible = false;
2582 return OK;
2583 }
2584 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2585 *isCompatible = ((maxUsage & minUsage) == minUsage);
2586 return OK;
2587}
2588
2589static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2590 static std::mutex sMutex{};
2591 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2592 std::unique_lock<std::mutex> lock{sMutex};
2593 std::shared_ptr<C2BlockPool> pool;
2594 auto it = sPools.find(allocId);
2595 if (it == sPools.end()) {
2596 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2597 if (err == OK) {
2598 sPools.emplace(allocId, pool);
2599 } else {
2600 pool.reset();
2601 }
2602 } else {
2603 pool = it->second;
2604 }
2605 return pool;
2606}
2607
2608// static
2609std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2610 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
2611 uint64_t minUsage = usage.expected;
2612 uint64_t maxUsage = ~0ull;
2613 std::set<C2Allocator::id_t> allocators;
2614 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2615 if (allocators.empty()) {
2616 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2617 }
2618 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2619 if ((maxUsage & minUsage) != minUsage) {
2620 allocators.clear();
2621 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2622 }
2623 std::shared_ptr<C2LinearBlock> block;
2624 for (C2Allocator::id_t allocId : allocators) {
2625 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2626 if (!pool) {
2627 continue;
2628 }
2629 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2630 if (err != C2_OK || !block) {
2631 block.reset();
2632 continue;
2633 }
2634 break;
2635 }
2636 return block;
2637}
2638
2639// static
2640status_t CCodec::CanFetchGraphicBlock(
2641 const std::vector<std::string> &names, bool *isCompatible) {
2642 uint64_t minUsage = 0;
2643 uint64_t maxUsage = ~0ull;
2644 std::set<C2Allocator::id_t> allocators;
2645 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2646 if (allocators.empty()) {
2647 *isCompatible = false;
2648 return OK;
2649 }
2650 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2651 *isCompatible = ((maxUsage & minUsage) == minUsage);
2652 return OK;
2653}
2654
2655// static
2656std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2657 int32_t width,
2658 int32_t height,
2659 int32_t format,
2660 uint64_t usage,
2661 const std::vector<std::string> &names) {
2662 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2663 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2664 ALOGD("Unrecognized pixel format: %d", format);
2665 return nullptr;
2666 }
2667 uint64_t minUsage = 0;
2668 uint64_t maxUsage = ~0ull;
2669 std::set<C2Allocator::id_t> allocators;
2670 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2671 if (allocators.empty()) {
2672 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2673 }
2674 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2675 minUsage |= usage;
2676 if ((maxUsage & minUsage) != minUsage) {
2677 allocators.clear();
2678 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2679 }
2680 std::shared_ptr<C2GraphicBlock> block;
2681 for (C2Allocator::id_t allocId : allocators) {
2682 std::shared_ptr<C2BlockPool> pool;
2683 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2684 if (err != C2_OK || !pool) {
2685 continue;
2686 }
2687 err = pool->fetchGraphicBlock(
2688 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2689 if (err != C2_OK || !block) {
2690 block.reset();
2691 continue;
2692 }
2693 break;
2694 }
2695 return block;
2696}
2697
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002698} // namespace android