blob: c54af356f3398def694baf6d1e134a7f92495ae6 [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 Kim1f5063d2021-05-03 15:41:17 -070041#include <media/stagefright/foundation/avc_utils.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070042#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
43#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070044#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080045#include <media/stagefright/BufferProducerWrapper.h>
46#include <media/stagefright/MediaCodecConstants.h>
47#include <media/stagefright/PersistentSurface.h>
ted.sun765db4d2020-06-23 14:03:41 +080048#include <utils/NativeHandle.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080049
50#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080051#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070052#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080053#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080054#include "InputSurfaceWrapper.h"
55
56extern "C" android::PersistentSurface *CreateInputSurface();
57
58namespace android {
59
60using namespace std::chrono_literals;
61using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
62using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080063using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080064
Wonsik Kim9917d4a2019-10-24 12:56:38 -070065typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070066typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070067
Pawin Vongmasa36653902018-11-15 00:10:25 -080068namespace {
69
70class CCodecWatchdog : public AHandler {
71private:
72 enum {
73 kWhatWatch,
74 };
75 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
76
77public:
78 static sp<CCodecWatchdog> getInstance() {
79 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
80 static std::once_flag flag;
81 // Call Init() only once.
82 std::call_once(flag, Init, instance);
83 return instance;
84 }
85
86 ~CCodecWatchdog() = default;
87
88 void watch(sp<CCodec> codec) {
89 bool shouldPost = false;
90 {
91 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
92 // If a watch message is in flight, piggy-back this instance as well.
93 // Otherwise, post a new watch message.
94 shouldPost = codecs->empty();
95 codecs->emplace(codec);
96 }
97 if (shouldPost) {
98 ALOGV("posting watch message");
99 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
100 }
101 }
102
103protected:
104 void onMessageReceived(const sp<AMessage> &msg) {
105 switch (msg->what()) {
106 case kWhatWatch: {
107 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
108 ALOGV("watch for %zu codecs", codecs->size());
109 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
110 sp<CCodec> codec = it->promote();
111 if (codec == nullptr) {
112 continue;
113 }
114 codec->initiateReleaseIfStuck();
115 }
116 codecs->clear();
117 break;
118 }
119
120 default: {
121 TRESPASS("CCodecWatchdog: unrecognized message");
122 }
123 }
124 }
125
126private:
127 CCodecWatchdog() : mLooper(new ALooper) {}
128
129 static void Init(const sp<CCodecWatchdog> &thiz) {
130 ALOGV("Init");
131 thiz->mLooper->setName("CCodecWatchdog");
132 thiz->mLooper->registerHandler(thiz);
133 thiz->mLooper->start();
134 }
135
136 sp<ALooper> mLooper;
137
138 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
139};
140
141class C2InputSurfaceWrapper : public InputSurfaceWrapper {
142public:
143 explicit C2InputSurfaceWrapper(
144 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
145 mSurface(surface) {
146 }
147
148 ~C2InputSurfaceWrapper() override = default;
149
150 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
151 if (mConnection != nullptr) {
152 return ALREADY_EXISTS;
153 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800154 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800155 }
156
157 void disconnect() override {
158 if (mConnection != nullptr) {
159 mConnection->disconnect();
160 mConnection = nullptr;
161 }
162 }
163
164 status_t start() override {
165 // InputSurface does not distinguish started state
166 return OK;
167 }
168
169 status_t signalEndOfInputStream() override {
170 C2InputSurfaceEosTuning eos(true);
171 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800172 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800173 if (err != C2_OK) {
174 return UNKNOWN_ERROR;
175 }
176 return OK;
177 }
178
179 status_t configure(Config &config __unused) {
180 // TODO
181 return OK;
182 }
183
184private:
185 std::shared_ptr<Codec2Client::InputSurface> mSurface;
186 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
187};
188
189class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
190public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700191 typedef hardware::media::omx::V1_0::Status OmxStatus;
192
Pawin Vongmasa36653902018-11-15 00:10:25 -0800193 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700194 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800195 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700196 uint32_t height,
197 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800198 : mSource(source), mWidth(width), mHeight(height) {
199 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700200 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800201 }
202 ~GraphicBufferSourceWrapper() override = default;
203
204 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
205 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700206 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800207 mNode->setFrameSize(mWidth, mHeight);
208
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700209 // Usage is queried during configure(), so setting it beforehand.
210 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
211 (void)mNode->setParameter(
212 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
213 &usage, sizeof(usage));
214
Yanqiang Fanc56f3e62021-09-28 16:54:07 +0800215 return GetStatus(mSource->configure(
216 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800217 }
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 Kima1335e12021-04-22 16:28:29 -0700400 // priority
401 if (mConfig.mPriority != config.mPriority) {
402 if (config.mPriority != INT_MAX) {
403 mNode->setPriority(config.mPriority);
404 }
405 mConfig.mPriority = config.mPriority;
406 }
407
Wonsik Kimbd557932019-07-02 15:51:20 -0700408 if (status.str().empty()) {
409 ALOGD("ISConfig not changed");
410 } else {
411 ALOGD("ISConfig%s", status.str().c_str());
412 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800413 return err;
414 }
415
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700416 void onInputBufferDone(c2_cntr64_t index) override {
417 mNode->onInputBufferDone(index);
418 }
419
Wonsik Kim673dd192021-01-29 14:58:12 -0800420 android_dataspace getDataspace() override {
421 return mNode->getDataspace();
422 }
423
Pawin Vongmasa36653902018-11-15 00:10:25 -0800424private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700425 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800426 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700427 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800428 uint32_t mWidth;
429 uint32_t mHeight;
430 Config mConfig;
431};
432
433class Codec2ClientInterfaceWrapper : public C2ComponentStore {
434 std::shared_ptr<Codec2Client> mClient;
435
436public:
437 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
438 : mClient(client) { }
439
440 virtual ~Codec2ClientInterfaceWrapper() = default;
441
442 virtual c2_status_t config_sm(
443 const std::vector<C2Param *> &params,
444 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
445 return mClient->config(params, C2_MAY_BLOCK, failures);
446 };
447
448 virtual c2_status_t copyBuffer(
449 std::shared_ptr<C2GraphicBuffer>,
450 std::shared_ptr<C2GraphicBuffer>) {
451 return C2_OMITTED;
452 }
453
454 virtual c2_status_t createComponent(
455 C2String, std::shared_ptr<C2Component> *const component) {
456 component->reset();
457 return C2_OMITTED;
458 }
459
460 virtual c2_status_t createInterface(
461 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
462 interface->reset();
463 return C2_OMITTED;
464 }
465
466 virtual c2_status_t query_sm(
467 const std::vector<C2Param *> &stackParams,
468 const std::vector<C2Param::Index> &heapParamIndices,
469 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
470 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
471 }
472
473 virtual c2_status_t querySupportedParams_nb(
474 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
475 return mClient->querySupportedParams(params);
476 }
477
478 virtual c2_status_t querySupportedValues_sm(
479 std::vector<C2FieldSupportedValuesQuery> &fields) const {
480 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
481 }
482
483 virtual C2String getName() const {
484 return mClient->getName();
485 }
486
487 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
488 return mClient->getParamReflector();
489 }
490
491 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
492 return std::vector<std::shared_ptr<const C2Component::Traits>>();
493 }
494};
495
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800496void RevertOutputFormatIfNeeded(
497 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
498 // We used to not report changes to these keys to the client.
499 const static std::set<std::string> sIgnoredKeys({
500 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800501 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800502 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800503 KEY_MAX_WIDTH,
504 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800505 "csd-0",
506 "csd-1",
507 "csd-2",
508 });
509 if (currentFormat == oldFormat) {
510 return;
511 }
512 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
513 AMessage::Type type;
514 for (size_t i = diff->countEntries(); i > 0; --i) {
515 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
516 diff->removeEntryAt(i - 1);
517 }
518 }
519 if (diff->countEntries() == 0) {
520 currentFormat = oldFormat;
521 }
522}
523
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700524void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700525 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700526 const sp<AMessage> &outputFormat) {
527 if (mediaType == MIMETYPE_VIDEO_AVC) {
528 // Codec specific data should be SPS and PPS in a single buffer,
529 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
530 // We separate the two and put them into the output format
531 // under the keys "csd-0" and "csd-1".
532
533 unsigned csdIndex = 0;
534
535 const uint8_t *nalStart;
536 size_t nalSize;
537 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
538 sp<ABuffer> csd = new ABuffer(nalSize + 4);
539 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
540 memcpy(csd->data() + 4, nalStart, nalSize);
541
542 outputFormat->setBuffer(
543 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
544
545 ++csdIndex;
546 }
547
548 if (csdIndex != 2) {
549 ALOGW("Expected two NAL units from AVC codec config, but %u found",
550 csdIndex);
551 }
552 } else {
553 // For everything else we just stash the codec specific data into
554 // the output format as a single piece of csd under "csd-0".
555 sp<ABuffer> csd = new ABuffer(size);
556 memcpy(csd->data(), data, size);
557 csd->setRange(0, size);
558 outputFormat->setBuffer("csd-0", csd);
559 }
560}
561
Pawin Vongmasa36653902018-11-15 00:10:25 -0800562} // namespace
563
564// CCodec::ClientListener
565
566struct CCodec::ClientListener : public Codec2Client::Listener {
567
568 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
569
570 virtual void onWorkDone(
571 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800572 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800573 (void)component;
574 sp<CCodec> codec(mCodec.promote());
575 if (!codec) {
576 return;
577 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800578 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800579 }
580
581 virtual void onTripped(
582 const std::weak_ptr<Codec2Client::Component>& component,
583 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
584 ) override {
585 // TODO
586 (void)component;
587 (void)settingResult;
588 }
589
590 virtual void onError(
591 const std::weak_ptr<Codec2Client::Component>& component,
592 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800593 {
594 // Component is only used for reporting as we use a separate listener for each instance
595 std::shared_ptr<Codec2Client::Component> comp = component.lock();
596 if (!comp) {
597 ALOGD("Component died with error: 0x%x", errorCode);
598 } else {
599 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
600 }
601 }
602
603 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800604 // Note: for now we do not propagate the error code to MediaCodec
605 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800606 sp<CCodec> codec(mCodec.promote());
607 if (!codec || !codec->mCallback) {
608 return;
609 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800610 codec->mCallback->onError(
611 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
612 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800613 }
614
615 virtual void onDeath(
616 const std::weak_ptr<Codec2Client::Component>& component) override {
617 { // Log the death of the component.
618 std::shared_ptr<Codec2Client::Component> comp = component.lock();
619 if (!comp) {
620 ALOGE("Codec2 component died.");
621 } else {
622 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
623 }
624 }
625
626 // Report to MediaCodec.
627 sp<CCodec> codec(mCodec.promote());
628 if (!codec || !codec->mCallback) {
629 return;
630 }
631 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
632 }
633
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800634 virtual void onFrameRendered(uint64_t bufferQueueId,
635 int32_t slotId,
636 int64_t timestampNs) override {
637 // TODO: implement
638 (void)bufferQueueId;
639 (void)slotId;
640 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800641 }
642
643 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800644 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800645 sp<CCodec> codec(mCodec.promote());
646 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800647 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800648 }
649 }
650
651private:
652 wp<CCodec> mCodec;
653};
654
655// CCodecCallbackImpl
656
657class CCodecCallbackImpl : public CCodecCallback {
658public:
659 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
660 ~CCodecCallbackImpl() override = default;
661
662 void onError(status_t err, enum ActionCode actionCode) override {
663 mCodec->mCallback->onError(err, actionCode);
664 }
665
666 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
667 mCodec->mCallback->onOutputFramesRendered(
668 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
669 }
670
Pawin Vongmasa36653902018-11-15 00:10:25 -0800671 void onOutputBuffersChanged() override {
672 mCodec->mCallback->onOutputBuffersChanged();
673 }
674
Guillaume Chelfi5ffbcb32021-04-12 14:23:43 +0200675 void onFirstTunnelFrameReady() override {
676 mCodec->mCallback->onFirstTunnelFrameReady();
677 }
678
Pawin Vongmasa36653902018-11-15 00:10:25 -0800679private:
680 CCodec *mCodec;
681};
682
683// CCodec
684
685CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700686 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
687 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800688}
689
690CCodec::~CCodec() {
691}
692
693std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
694 return mChannel;
695}
696
697status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
698 status_t err = job();
699 if (err != C2_OK) {
700 mCallback->onError(err, ACTION_CODE_FATAL);
701 }
702 return err;
703}
704
705void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
706 auto setAllocating = [this] {
707 Mutexed<State>::Locked state(mState);
708 if (state->get() != RELEASED) {
709 return INVALID_OPERATION;
710 }
711 state->set(ALLOCATING);
712 return OK;
713 };
714 if (tryAndReportOnError(setAllocating) != OK) {
715 return;
716 }
717
718 sp<RefBase> codecInfo;
719 CHECK(msg->findObject("codecInfo", &codecInfo));
720 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
721
722 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
723 allocMsg->setObject("codecInfo", codecInfo);
724 allocMsg->post();
725}
726
727void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
728 if (codecInfo == nullptr) {
729 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
730 return;
731 }
732 ALOGD("allocate(%s)", codecInfo->getCodecName());
733 mClientListener.reset(new ClientListener(this));
734
735 AString componentName = codecInfo->getCodecName();
736 std::shared_ptr<Codec2Client> client;
737
738 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700739 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800740 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800741 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800742 SetPreferredCodec2ComponentStore(
743 std::make_shared<Codec2ClientInterfaceWrapper>(client));
744 }
745
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900746 std::shared_ptr<Codec2Client::Component> comp;
747 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748 componentName.c_str(),
749 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900750 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800751 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900752 if (status != C2_OK) {
753 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800754 Mutexed<State>::Locked state(mState);
755 state->set(RELEASED);
756 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900757 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800758 state.lock();
759 return;
760 }
761 ALOGI("Created component [%s]", componentName.c_str());
762 mChannel->setComponent(comp);
763 auto setAllocated = [this, comp, client] {
764 Mutexed<State>::Locked state(mState);
765 if (state->get() != ALLOCATING) {
766 state->set(RELEASED);
767 return UNKNOWN_ERROR;
768 }
769 state->set(ALLOCATED);
770 state->comp = comp;
771 mClient = client;
772 return OK;
773 };
774 if (tryAndReportOnError(setAllocated) != OK) {
775 return;
776 }
777
778 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700779 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
780 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800781 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800782 if (err != OK) {
783 ALOGW("Failed to initialize configuration support");
784 // TODO: report error once we complete implementation.
785 }
786 config->queryConfiguration(comp);
787
788 mCallback->onComponentAllocated(componentName.c_str());
789}
790
791void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
792 auto checkAllocated = [this] {
793 Mutexed<State>::Locked state(mState);
794 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
795 };
796 if (tryAndReportOnError(checkAllocated) != OK) {
797 return;
798 }
799
800 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
801 msg->setMessage("format", format);
802 msg->post();
803}
804
805void CCodec::configure(const sp<AMessage> &msg) {
806 std::shared_ptr<Codec2Client::Component> comp;
807 auto checkAllocated = [this, &comp] {
808 Mutexed<State>::Locked state(mState);
809 if (state->get() != ALLOCATED) {
810 state->set(RELEASED);
811 return UNKNOWN_ERROR;
812 }
813 comp = state->comp;
814 return OK;
815 };
816 if (tryAndReportOnError(checkAllocated) != OK) {
817 return;
818 }
819
820 auto doConfig = [msg, comp, this]() -> status_t {
821 AString mime;
822 if (!msg->findString("mime", &mime)) {
823 return BAD_VALUE;
824 }
825
826 int32_t encoder;
827 if (!msg->findInt32("encoder", &encoder)) {
828 encoder = false;
829 }
830
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800831 int32_t flags;
832 if (!msg->findInt32("flags", &flags)) {
833 return BAD_VALUE;
834 }
835
Pawin Vongmasa36653902018-11-15 00:10:25 -0800836 // TODO: read from intf()
837 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
838 return UNKNOWN_ERROR;
839 }
840
841 int32_t storeMeta;
842 if (encoder
843 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
844 && storeMeta != kMetadataBufferTypeInvalid) {
845 if (storeMeta != kMetadataBufferTypeANWBuffer) {
846 ALOGD("Only ANW buffers are supported for legacy metadata mode");
847 return BAD_VALUE;
848 }
849 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
850 }
851
ted.sun765db4d2020-06-23 14:03:41 +0800852 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800853 sp<RefBase> obj;
854 sp<Surface> surface;
855 if (msg->findObject("native-window", &obj)) {
856 surface = static_cast<Surface *>(obj.get());
ted.sun765db4d2020-06-23 14:03:41 +0800857 // setup tunneled playback
858 if (surface != nullptr) {
859 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
860 const std::unique_ptr<Config> &config = *configLocked;
861 if ((config->mDomain & Config::IS_DECODER)
862 && (config->mDomain & Config::IS_VIDEO)) {
863 int32_t tunneled;
864 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
865 ALOGI("Configuring TUNNELED video playback.");
866
867 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
868 if (err != OK) {
869 ALOGE("configureTunneledVideoPlayback failed!");
870 return err;
871 }
872 config->mTunneled = true;
873 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +0100874
875 int32_t pushBlankBuffersOnStop = 0;
876 if (msg->findInt32(KEY_PUSH_BLANK_BUFFERS_ON_STOP, &pushBlankBuffersOnStop)) {
877 config->mPushBlankBuffersOnStop = pushBlankBuffersOnStop == 1;
878 }
ted.sun765db4d2020-06-23 14:03:41 +0800879 }
880 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800881 setSurface(surface);
882 }
883
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700884 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
885 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800886 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800887 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
888 ALOGD("[%s] buffers are %sbound to CCodec for this session",
889 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800890
Wonsik Kim1114eea2019-02-25 14:35:24 -0800891 // Enforce required parameters
892 int32_t i32;
893 float flt;
894 if (config->mDomain & Config::IS_AUDIO) {
895 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
896 ALOGD("sample rate is missing, which is required for audio components.");
897 return BAD_VALUE;
898 }
899 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
900 ALOGD("channel count is missing, which is required for audio components.");
901 return BAD_VALUE;
902 }
903 if ((config->mDomain & Config::IS_ENCODER)
904 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
905 && !msg->findInt32(KEY_BIT_RATE, &i32)
906 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
907 ALOGD("bitrate is missing, which is required for audio encoders.");
908 return BAD_VALUE;
909 }
910 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800911 int32_t width = 0;
912 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800913 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800914 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800915 ALOGD("width is missing, which is required for image/video components.");
916 return BAD_VALUE;
917 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800918 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800919 ALOGD("height is missing, which is required for image/video components.");
920 return BAD_VALUE;
921 }
922 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700923 int32_t mode = BITRATE_MODE_VBR;
924 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700925 if (!msg->findInt32(KEY_QUALITY, &i32)) {
926 ALOGD("quality is missing, which is required for video encoders in CQ.");
927 return BAD_VALUE;
928 }
929 } else {
930 if (!msg->findInt32(KEY_BIT_RATE, &i32)
931 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
932 ALOGD("bitrate is missing, which is required for video encoders.");
933 return BAD_VALUE;
934 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800935 }
936 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
937 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
938 ALOGD("I frame interval is missing, which is required for video encoders.");
939 return BAD_VALUE;
940 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700941 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
942 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
943 ALOGD("frame rate is missing, which is required for video encoders.");
944 return BAD_VALUE;
945 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800946 }
947 }
948
Pawin Vongmasa36653902018-11-15 00:10:25 -0800949 /*
950 * Handle input surface configuration
951 */
952 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
953 && (config->mDomain & Config::IS_ENCODER)) {
954 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
955 {
956 config->mISConfig->mMinFps = 0;
957 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800958 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800959 config->mISConfig->mMinFps = 1e6 / value;
960 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700961 if (!msg->findFloat(
962 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
963 config->mISConfig->mMaxFps = -1;
964 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800965 config->mISConfig->mMinAdjustedFps = 0;
966 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800967 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800968 if (value < 0 && value >= INT32_MIN) {
969 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700970 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800971 } else if (value > 0 && value <= INT32_MAX) {
972 config->mISConfig->mMinAdjustedFps = 1e6 / value;
973 }
974 }
975 }
976
977 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700978 bool captureFpsFound = false;
979 double timeLapseFps;
980 float captureRate;
981 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
982 config->mISConfig->mCaptureFps = timeLapseFps;
983 captureFpsFound = true;
984 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
985 config->mISConfig->mCaptureFps = captureRate;
986 captureFpsFound = true;
987 }
988 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800989 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
990 }
991 }
992
993 {
994 config->mISConfig->mSuspended = false;
995 config->mISConfig->mSuspendAtUs = -1;
996 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800997 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800998 config->mISConfig->mSuspended = true;
999 }
1000 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001001 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -07001002 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001003 }
1004
1005 /*
1006 * Handle desired color format.
1007 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001008 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001009 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001010 int32_t format = 0;
1011 // Query vendor format for Flexible YUV
1012 std::vector<std::unique_ptr<C2Param>> heapParams;
1013 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
1014 if (mClient->query(
1015 {},
1016 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1017 C2_MAY_BLOCK,
1018 &heapParams) == C2_OK
1019 && heapParams.size() == 1u) {
1020 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1021 heapParams[0].get());
1022 } else {
1023 pixelFormatInfo = nullptr;
1024 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001025 // bit depth -> format
1026 std::map<uint32_t, uint32_t> flexPixelFormat;
1027 std::map<uint32_t, uint32_t> flexPlanarPixelFormat;
1028 std::map<uint32_t, uint32_t> flexSemiPlanarPixelFormat;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001029 if (pixelFormatInfo && *pixelFormatInfo) {
1030 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1031 const C2FlexiblePixelFormatDescriptorStruct &desc =
1032 pixelFormatInfo->m.values[i];
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001033 if (desc.subsampling != C2Color::YUV_420
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001034 // TODO(b/180076105): some device report wrong layout
1035 // || desc.layout == C2Color::INTERLEAVED_PACKED
1036 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1037 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1038 continue;
1039 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001040 if (flexPixelFormat.count(desc.bitDepth) == 0) {
1041 flexPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001042 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001043 if (desc.layout == C2Color::PLANAR_PACKED
1044 && flexPlanarPixelFormat.count(desc.bitDepth) == 0) {
1045 flexPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001046 }
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001047 if (desc.layout == C2Color::SEMIPLANAR_PACKED
1048 && flexSemiPlanarPixelFormat.count(desc.bitDepth) == 0) {
1049 flexSemiPlanarPixelFormat.emplace(desc.bitDepth, desc.pixelFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001050 }
1051 }
1052 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001053 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001054 // Also handle default color format (encoders require color format, so this is only
1055 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001056 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001057 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001058 const char *prefix = "";
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001059 if (flexSemiPlanarPixelFormat.count(8) != 0) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001060 format = COLOR_FormatYUV420SemiPlanar;
1061 prefix = "semi-";
1062 } else {
1063 format = COLOR_FormatYUV420Planar;
1064 }
1065 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1066 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001067 } else {
1068 format = COLOR_FormatSurface;
1069 }
1070 defaultColorFormat = format;
1071 }
1072 } else {
1073 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
1074 switch (format) {
1075 case COLOR_FormatYUV420Flexible:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001076 format = COLOR_FormatYUV420Planar;
1077 if (flexPixelFormat.count(8) != 0) {
1078 format = flexPixelFormat[8];
1079 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001080 break;
1081 case COLOR_FormatYUV420Planar:
1082 case COLOR_FormatYUV420PackedPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001083 if (flexPlanarPixelFormat.count(8) != 0) {
1084 format = flexPlanarPixelFormat[8];
1085 } else if (flexPixelFormat.count(8) != 0) {
1086 format = flexPixelFormat[8];
1087 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001088 break;
1089 case COLOR_FormatYUV420SemiPlanar:
1090 case COLOR_FormatYUV420PackedSemiPlanar:
Wonsik Kim08a8a2b2021-05-10 19:03:47 -07001091 if (flexSemiPlanarPixelFormat.count(8) != 0) {
1092 format = flexSemiPlanarPixelFormat[8];
1093 } else if (flexPixelFormat.count(8) != 0) {
1094 format = flexPixelFormat[8];
1095 }
1096 break;
1097 case COLOR_FormatYUVP010:
1098 format = COLOR_FormatYUVP010;
1099 if (flexSemiPlanarPixelFormat.count(10) != 0) {
1100 format = flexSemiPlanarPixelFormat[10];
1101 } else if (flexPixelFormat.count(10) != 0) {
1102 format = flexPixelFormat[10];
1103 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001104 break;
1105 default:
1106 // No-op
1107 break;
1108 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001109 }
1110 }
1111
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001112 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001113 msg->setInt32("android._color-format", format);
1114 }
1115 }
1116
Wonsik Kim77e97c72021-01-20 10:33:22 -08001117 /*
1118 * Handle dataspace
1119 */
1120 int32_t usingRecorder;
1121 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1122 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1123 int32_t width, height;
1124 if (msg->findInt32("width", &width)
1125 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001126 ColorAspects aspects;
1127 getColorAspectsFromFormat(msg, aspects);
1128 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001129 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001130 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1131 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001132 }
1133 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1134 ALOGD("setting dataspace to %x", dataSpace);
1135 }
1136
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001137 int32_t subscribeToAllVendorParams;
1138 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1139 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1140 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1141 }
1142 }
1143
Pawin Vongmasa36653902018-11-15 00:10:25 -08001144 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001145 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1146 // the behavior here.
1147 sp<AMessage> sdkParams = msg;
1148 int32_t videoBitrate;
1149 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1150 sdkParams = msg->dup();
1151 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1152 }
ted.sun765db4d2020-06-23 14:03:41 +08001153 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001154 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001155 if (err != OK) {
1156 ALOGW("failed to convert configuration to c2 params");
1157 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001158
1159 int32_t maxBframes = 0;
1160 if ((config->mDomain & Config::IS_ENCODER)
1161 && (config->mDomain & Config::IS_VIDEO)
1162 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1163 && maxBframes > 0) {
1164 std::unique_ptr<C2StreamGopTuning::output> gop =
1165 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1166 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1167 gop->m.values[1] = {
1168 C2Config::picture_type_t(P_FRAME | B_FRAME),
1169 uint32_t(maxBframes)
1170 };
1171 configUpdate.push_back(std::move(gop));
1172 }
1173
Ray Essicka0ae6972021-03-10 19:40:01 -08001174 if ((config->mDomain & Config::IS_ENCODER)
1175 && (config->mDomain & Config::IS_VIDEO)) {
1176 // we may not use all 3 of these entries
1177 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1178 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1179 0u /* stream */);
1180
1181 int ix = 0;
1182
1183 int32_t iMax = INT32_MAX;
1184 int32_t iMin = INT32_MIN;
1185 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1186 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1187 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1188 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1189 }
1190
1191 int32_t pMax = INT32_MAX;
1192 int32_t pMin = INT32_MIN;
1193 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1194 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1195 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1196 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1197 }
1198
1199 int32_t bMax = INT32_MAX;
1200 int32_t bMin = INT32_MIN;
1201 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1202 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1203 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1204 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1205 }
1206
1207 // adjust to reflect actual use.
1208 qp->setFlexCount(ix);
1209
1210 configUpdate.push_back(std::move(qp));
1211 }
1212
Wonsik Kima1335e12021-04-22 16:28:29 -07001213 int32_t background = 0;
1214 if ((config->mDomain & Config::IS_VIDEO)
1215 && msg->findInt32("android._background-mode", &background)
1216 && background) {
1217 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1218 if (config->mISConfig) {
1219 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1220 }
1221 }
1222
Pawin Vongmasa36653902018-11-15 00:10:25 -08001223 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1224 if (err != OK) {
1225 ALOGW("failed to configure c2 params");
1226 return err;
1227 }
1228
1229 std::vector<std::unique_ptr<C2Param>> params;
1230 C2StreamUsageTuning::input usage(0u, 0u);
1231 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001232 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001233
Wonsik Kim3baecda2021-02-07 22:19:56 -08001234 C2Param::Index colorAspectsRequestIndex =
1235 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001236 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001237 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001238 };
Chaejung Lim86c22dc2021-12-23 00:41:05 -08001239 int32_t colorTransferRequest = 0;
1240 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1241 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1242 colorTransferRequest = 0;
1243 }
1244 c2_status_t c2err = C2_OK;
1245 if (colorTransferRequest != 0) {
1246 c2err = comp->query(
1247 { &usage, &maxInputSize, &prepend },
1248 indices,
1249 C2_DONT_BLOCK,
1250 &params);
1251 } else {
1252 c2err = comp->query(
1253 { &usage, &maxInputSize, &prepend },
1254 {},
1255 C2_DONT_BLOCK,
1256 &params);
1257 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001258 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1259 ALOGE("Failed to query component interface: %d", c2err);
1260 return UNKNOWN_ERROR;
1261 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001262 if (usage) {
1263 if (usage.value & C2MemoryUsage::CPU_READ) {
1264 config->mInputFormat->setInt32("using-sw-read-often", true);
1265 }
1266 if (config->mISConfig) {
1267 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1268 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1269 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001270 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001271 }
1272
1273 // NOTE: we don't blindly use client specified input size if specified as clients
1274 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1275 // client specified size is only used to ask for bigger buffers than component suggested
1276 // size.
1277 int32_t clientInputSize = 0;
1278 bool clientSpecifiedInputSize =
1279 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1280 // TEMP: enforce minimum buffer size of 1MB for video decoders
1281 // and 16K / 4K for audio encoders/decoders
1282 if (maxInputSize.value == 0) {
1283 if (config->mDomain & Config::IS_AUDIO) {
1284 maxInputSize.value = encoder ? 16384 : 4096;
1285 } else if (!encoder) {
1286 maxInputSize.value = 1048576u;
1287 }
1288 }
1289
1290 // verify that CSD fits into this size (if defined)
1291 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1292 sp<ABuffer> csd;
1293 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1294 if (csd && csd->size() > maxInputSize.value) {
1295 maxInputSize.value = csd->size();
1296 }
1297 }
1298 }
1299
1300 // TODO: do this based on component requiring linear allocator for input
1301 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1302 if (clientSpecifiedInputSize) {
1303 // Warn that we're overriding client's max input size if necessary.
1304 if ((uint32_t)clientInputSize < maxInputSize.value) {
1305 ALOGD("client requested max input size %d, which is smaller than "
1306 "what component recommended (%u); overriding with component "
1307 "recommendation.", clientInputSize, maxInputSize.value);
1308 ALOGW("This behavior is subject to change. It is recommended that "
1309 "app developers double check whether the requested "
1310 "max input size is in reasonable range.");
1311 } else {
1312 maxInputSize.value = clientInputSize;
1313 }
1314 }
1315 // Pass max input size on input format to the buffer channel (if supplied by the
1316 // component or by a default)
1317 if (maxInputSize.value) {
1318 config->mInputFormat->setInt32(
1319 KEY_MAX_INPUT_SIZE,
1320 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1321 }
1322 }
1323
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001324 int32_t clientPrepend;
1325 if ((config->mDomain & Config::IS_VIDEO)
1326 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001327 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001328 && clientPrepend
1329 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001330 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001331 return BAD_VALUE;
1332 }
1333
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001334 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001335 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1336 // propagate HDR static info to output format for both encoders and decoders
1337 // if component supports this info, we will update from component, but only the raw port,
1338 // so don't propagate if component already filled it in.
1339 sp<ABuffer> hdrInfo;
1340 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1341 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1342 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1343 }
1344
1345 // Set desired color format from configuration parameter
1346 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001347 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1348 format = defaultColorFormat;
1349 }
1350 if (config->mDomain & Config::IS_ENCODER) {
1351 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001352 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1353 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001354 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001355 } else {
1356 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001357 }
1358 }
1359
1360 // propagate encoder delay and padding to output format
1361 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1362 int delay = 0;
1363 if (msg->findInt32("encoder-delay", &delay)) {
1364 config->mOutputFormat->setInt32("encoder-delay", delay);
1365 }
1366 int padding = 0;
1367 if (msg->findInt32("encoder-padding", &padding)) {
1368 config->mOutputFormat->setInt32("encoder-padding", padding);
1369 }
1370 }
1371
Pawin Vongmasa36653902018-11-15 00:10:25 -08001372 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001373 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001374 int32_t mask;
1375 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1376 if (config->mDomain & Config::IS_ENCODER) {
1377 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1378 } else {
1379 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1380 }
1381 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001382
1383 // set PCM encoding
1384 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1385 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1386 if (encoder) {
1387 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1388 } else {
1389 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1390 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001391 }
1392
Wonsik Kim3baecda2021-02-07 22:19:56 -08001393 std::unique_ptr<C2Param> colorTransferRequestParam;
1394 for (std::unique_ptr<C2Param> &param : params) {
1395 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1396 ALOGI("found color transfer request param");
1397 colorTransferRequestParam = std::move(param);
1398 }
1399 }
Wonsik Kim3baecda2021-02-07 22:19:56 -08001400
1401 if (colorTransferRequest != 0) {
1402 if (colorTransferRequestParam && *colorTransferRequestParam) {
1403 C2StreamColorAspectsInfo::output *info =
1404 static_cast<C2StreamColorAspectsInfo::output *>(
1405 colorTransferRequestParam.get());
1406 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1407 colorTransferRequest = 0;
1408 }
1409 } else {
1410 colorTransferRequest = 0;
1411 }
1412 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1413 }
1414
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001415 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1416 // Need to get stride/vstride
1417 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1418 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1419 // TODO: retrieve these values without allocating a buffer.
1420 // Currently allocating a buffer is necessary to retrieve the layout.
1421 int64_t blockUsage =
1422 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1423 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1424 width, height, pixelFormat, blockUsage, {comp->getName()});
1425 sp<GraphicBlockBuffer> buffer;
1426 if (block) {
1427 buffer = GraphicBlockBuffer::Allocate(
1428 config->mInputFormat,
1429 block,
1430 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1431 } else {
1432 ALOGD("Failed to allocate a graphic block "
1433 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1434 width, height, pixelFormat, (long long)blockUsage);
1435 // This means that byte buffer mode is not supported in this configuration
1436 // anyway. Skip setting stride/vstride to input format.
1437 }
1438 if (buffer) {
1439 sp<ABuffer> imageData = buffer->getImageData();
1440 MediaImage2 *img = nullptr;
1441 if (imageData && imageData->data()
1442 && imageData->size() >= sizeof(MediaImage2)) {
1443 img = (MediaImage2*)imageData->data();
1444 }
1445 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1446 int32_t stride = img->mPlane[0].mRowInc;
1447 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1448 if (img->mNumPlanes > 1 && stride > 0) {
1449 int64_t offsetDelta =
1450 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1451 if (offsetDelta % stride == 0) {
1452 int32_t vstride = int32_t(offsetDelta / stride);
1453 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1454 } else {
1455 ALOGD("Cannot report accurate slice height: "
1456 "offsetDelta = %lld stride = %d",
1457 (long long)offsetDelta, stride);
1458 }
1459 }
1460 }
1461 }
1462 }
1463 }
1464
Wonsik Kimec585c32021-10-01 01:11:00 -07001465 if (config->mTunneled) {
1466 config->mOutputFormat->setInt32("android._tunneled", 1);
1467 }
1468
Yushin Cho91873b52021-12-21 04:08:35 -08001469 // Convert an encoding statistics level to corresponding encoding statistics
1470 // kinds
1471 int32_t encodingStatisticsLevel = VIDEO_ENCODING_STATISTICS_LEVEL_NONE;
1472 if ((config->mDomain & Config::IS_ENCODER)
1473 && (config->mDomain & Config::IS_VIDEO)
1474 && msg->findInt32(KEY_VIDEO_ENCODING_STATISTICS_LEVEL, &encodingStatisticsLevel)) {
1475 // Higher level include all the enc stats belong to lower level.
1476 switch (encodingStatisticsLevel) {
1477 // case VIDEO_ENCODING_STATISTICS_LEVEL_2: // reserved for the future level 2
1478 // with more enc stat kinds
1479 // Future extended encoding statistics for the level 2 should be added here
1480 case VIDEO_ENCODING_STATISTICS_LEVEL_1:
1481 config->subscribeToConfigUpdate(comp,
1482 {kParamIndexAverageBlockQuantization, kParamIndexPictureType});
1483 break;
1484 case VIDEO_ENCODING_STATISTICS_LEVEL_NONE:
1485 break;
1486 }
1487 }
1488 ALOGD("encoding statistics level = %d", encodingStatisticsLevel);
1489
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001490 ALOGD("setup formats input: %s",
1491 config->mInputFormat->debugString().c_str());
1492 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001493 config->mOutputFormat->debugString().c_str());
1494 return OK;
1495 };
1496 if (tryAndReportOnError(doConfig) != OK) {
1497 return;
1498 }
1499
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001500 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1501 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001502
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001503 config->queryConfiguration(comp);
1504
Pawin Vongmasa36653902018-11-15 00:10:25 -08001505 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1506}
1507
1508void CCodec::initiateCreateInputSurface() {
1509 status_t err = [this] {
1510 Mutexed<State>::Locked state(mState);
1511 if (state->get() != ALLOCATED) {
1512 return UNKNOWN_ERROR;
1513 }
1514 // TODO: read it from intf() properly.
1515 if (state->comp->getName().find("encoder") == std::string::npos) {
1516 return INVALID_OPERATION;
1517 }
1518 return OK;
1519 }();
1520 if (err != OK) {
1521 mCallback->onInputSurfaceCreationFailed(err);
1522 return;
1523 }
1524
1525 (new AMessage(kWhatCreateInputSurface, this))->post();
1526}
1527
Lajos Molnar47118272019-01-31 16:28:04 -08001528sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1529 using namespace android::hardware::media::omx::V1_0;
1530 using namespace android::hardware::media::omx::V1_0::utils;
1531 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1532 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1533 android::sp<IOmx> omx = IOmx::getService();
1534 typedef android::hardware::graphics::bufferqueue::V1_0::
1535 IGraphicBufferProducer HGraphicBufferProducer;
1536 typedef android::hardware::media::omx::V1_0::
1537 IGraphicBufferSource HGraphicBufferSource;
1538 OmxStatus s;
1539 android::sp<HGraphicBufferProducer> gbp;
1540 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001541
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001542 using ::android::hardware::Return;
1543 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001544 [&s, &gbp, &gbs](
1545 OmxStatus status,
1546 const android::sp<HGraphicBufferProducer>& producer,
1547 const android::sp<HGraphicBufferSource>& source) {
1548 s = status;
1549 gbp = producer;
1550 gbs = source;
1551 });
1552 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001553 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001554 }
1555
1556 return nullptr;
1557}
1558
1559sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1560 sp<PersistentSurface> surface(CreateInputSurface());
1561
1562 if (surface == nullptr) {
1563 surface = CreateOmxInputSurface();
1564 }
1565
1566 return surface;
1567}
1568
Pawin Vongmasa36653902018-11-15 00:10:25 -08001569void CCodec::createInputSurface() {
1570 status_t err;
1571 sp<IGraphicBufferProducer> bufferProducer;
1572
Pawin Vongmasa36653902018-11-15 00:10:25 -08001573 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001574 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001575 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001576 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1577 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001578 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001579 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001580 }
1581
Lajos Molnar47118272019-01-31 16:28:04 -08001582 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001583 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1584 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1585 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001586
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001587 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001588 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1589 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001590 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001591 inputSurface));
1592 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001593 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001594 int32_t width = 0;
1595 (void)outputFormat->findInt32("width", &width);
1596 int32_t height = 0;
1597 (void)outputFormat->findInt32("height", &height);
1598 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001599 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001600 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001601 } else {
1602 ALOGE("Corrupted input surface");
1603 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1604 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001605 }
1606
1607 if (err != OK) {
1608 ALOGE("Failed to set up input surface: %d", err);
1609 mCallback->onInputSurfaceCreationFailed(err);
1610 return;
1611 }
1612
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001613 // Formats can change after setupInputSurface
1614 sp<AMessage> inputFormat;
1615 {
1616 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1617 const std::unique_ptr<Config> &config = *configLocked;
1618 inputFormat = config->mInputFormat;
1619 outputFormat = config->mOutputFormat;
1620 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001621 mCallback->onInputSurfaceCreated(
1622 inputFormat,
1623 outputFormat,
1624 new BufferProducerWrapper(bufferProducer));
1625}
1626
1627status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001628 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1629 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001630 config->mUsingSurface = true;
1631
1632 // we are now using surface - apply default color aspects to input format - as well as
1633 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001634 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001635
1636 // configure dataspace
1637 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
Wonsik Kim66b19552021-08-02 16:07:49 -07001638
1639 // The output format contains app-configured color aspects, and the input format
1640 // has the default color aspects. Use the default for the unspecified params.
1641 ColorAspects inputColorAspects, colorAspects;
1642 getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
1643 getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
1644 if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
1645 colorAspects.mRange = inputColorAspects.mRange;
1646 }
1647 if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
1648 colorAspects.mPrimaries = inputColorAspects.mPrimaries;
1649 }
1650 if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
1651 colorAspects.mTransfer = inputColorAspects.mTransfer;
1652 }
1653 if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
1654 colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
1655 }
1656 android_dataspace dataSpace = getDataSpaceForColorAspects(
1657 colorAspects, /* mayExtend = */ false);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001658 surface->setDataSpace(dataSpace);
Wonsik Kim66b19552021-08-02 16:07:49 -07001659 setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
1660 config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
1661
1662 ALOGD("input format %s to %s",
1663 inputFormatChanged ? "changed" : "unchanged",
1664 config->mInputFormat->debugString().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001665
1666 status_t err = mChannel->setInputSurface(surface);
1667 if (err != OK) {
1668 // undo input format update
1669 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001670 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001671 return err;
1672 }
1673 config->mInputSurface = surface;
1674
1675 if (config->mISConfig) {
1676 surface->configure(*config->mISConfig);
1677 } else {
1678 ALOGD("ISConfig: no configuration");
1679 }
1680
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001681 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001682}
1683
1684void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1685 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1686 msg->setObject("surface", surface);
1687 msg->post();
1688}
1689
1690void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001691 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001692 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001693 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001694 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1695 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001696 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001697 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001698 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001699 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1700 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1701 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1702 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001703 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1704 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1705 if (err != OK) {
1706 ALOGE("Failed to set up input surface: %d", err);
1707 mCallback->onInputSurfaceDeclined(err);
1708 return;
1709 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001710 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001711 int32_t width = 0;
1712 (void)outputFormat->findInt32("width", &width);
1713 int32_t height = 0;
1714 (void)outputFormat->findInt32("height", &height);
1715 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001716 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001717 if (err != OK) {
1718 ALOGE("Failed to set up input surface: %d", err);
1719 mCallback->onInputSurfaceDeclined(err);
1720 return;
1721 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001722 } else {
1723 ALOGE("Failed to set input surface: Corrupted surface.");
1724 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1725 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001726 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001727 // Formats can change after setupInputSurface
1728 sp<AMessage> inputFormat;
1729 {
1730 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1731 const std::unique_ptr<Config> &config = *configLocked;
1732 inputFormat = config->mInputFormat;
1733 outputFormat = config->mOutputFormat;
1734 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001735 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1736}
1737
1738void CCodec::initiateStart() {
1739 auto setStarting = [this] {
1740 Mutexed<State>::Locked state(mState);
1741 if (state->get() != ALLOCATED) {
1742 return UNKNOWN_ERROR;
1743 }
1744 state->set(STARTING);
1745 return OK;
1746 };
1747 if (tryAndReportOnError(setStarting) != OK) {
1748 return;
1749 }
1750
1751 (new AMessage(kWhatStart, this))->post();
1752}
1753
1754void CCodec::start() {
1755 std::shared_ptr<Codec2Client::Component> comp;
1756 auto checkStarting = [this, &comp] {
1757 Mutexed<State>::Locked state(mState);
1758 if (state->get() != STARTING) {
1759 return UNKNOWN_ERROR;
1760 }
1761 comp = state->comp;
1762 return OK;
1763 };
1764 if (tryAndReportOnError(checkStarting) != OK) {
1765 return;
1766 }
1767
1768 c2_status_t err = comp->start();
1769 if (err != C2_OK) {
1770 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1771 ACTION_CODE_FATAL);
1772 return;
1773 }
1774 sp<AMessage> inputFormat;
1775 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001776 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001777 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001778 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001779 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1780 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001781 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001782 // start triggers format dup
1783 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001784 if (config->mInputSurface) {
1785 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001786 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001787 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001788 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001789 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001790 if (err2 != OK) {
1791 mCallback->onError(err2, ACTION_CODE_FATAL);
1792 return;
1793 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001794 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001795 if (err2 != OK) {
1796 mCallback->onError(err2, ACTION_CODE_FATAL);
1797 return;
1798 }
1799
1800 auto setRunning = [this] {
1801 Mutexed<State>::Locked state(mState);
1802 if (state->get() != STARTING) {
1803 return UNKNOWN_ERROR;
1804 }
1805 state->set(RUNNING);
1806 return OK;
1807 };
1808 if (tryAndReportOnError(setRunning) != OK) {
1809 return;
1810 }
1811 mCallback->onStartCompleted();
1812
1813 (void)mChannel->requestInitialInputBuffers();
1814}
1815
1816void CCodec::initiateShutdown(bool keepComponentAllocated) {
1817 if (keepComponentAllocated) {
1818 initiateStop();
1819 } else {
1820 initiateRelease();
1821 }
1822}
1823
1824void CCodec::initiateStop() {
1825 {
1826 Mutexed<State>::Locked state(mState);
1827 if (state->get() == ALLOCATED
1828 || state->get() == RELEASED
1829 || state->get() == STOPPING
1830 || state->get() == RELEASING) {
1831 // We're already stopped, released, or doing it right now.
1832 state.unlock();
1833 mCallback->onStopCompleted();
1834 state.lock();
1835 return;
1836 }
1837 state->set(STOPPING);
1838 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +01001839 {
1840 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1841 const std::unique_ptr<Config> &config = *configLocked;
1842 if (config->mPushBlankBuffersOnStop) {
1843 mChannel->pushBlankBufferToOutputSurface();
1844 }
1845 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001846 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001847 (new AMessage(kWhatStop, this))->post();
1848}
1849
1850void CCodec::stop() {
1851 std::shared_ptr<Codec2Client::Component> comp;
1852 {
1853 Mutexed<State>::Locked state(mState);
1854 if (state->get() == RELEASING) {
1855 state.unlock();
1856 // We're already stopped or release is in progress.
1857 mCallback->onStopCompleted();
1858 state.lock();
1859 return;
1860 } else if (state->get() != STOPPING) {
1861 state.unlock();
1862 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1863 state.lock();
1864 return;
1865 }
1866 comp = state->comp;
1867 }
1868 status_t err = comp->stop();
1869 if (err != C2_OK) {
1870 // TODO: convert err into status_t
1871 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1872 }
1873
1874 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001875 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1876 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001877 if (config->mInputSurface) {
1878 config->mInputSurface->disconnect();
1879 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001880 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001881 }
1882 }
1883 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001884 Mutexed<State>::Locked state(mState);
1885 if (state->get() == STOPPING) {
1886 state->set(ALLOCATED);
1887 }
1888 }
1889 mCallback->onStopCompleted();
1890}
1891
1892void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001893 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001894 {
1895 Mutexed<State>::Locked state(mState);
1896 if (state->get() == RELEASED || state->get() == RELEASING) {
1897 // We're already released or doing it right now.
1898 if (sendCallback) {
1899 state.unlock();
1900 mCallback->onReleaseCompleted();
1901 state.lock();
1902 }
1903 return;
1904 }
1905 if (state->get() == ALLOCATING) {
1906 state->set(RELEASING);
1907 // With the altered state allocate() would fail and clean up.
1908 if (sendCallback) {
1909 state.unlock();
1910 mCallback->onReleaseCompleted();
1911 state.lock();
1912 }
1913 return;
1914 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001915 if (state->get() == STARTING
1916 || state->get() == RUNNING
1917 || state->get() == STOPPING) {
1918 // Input surface may have been started, so clean up is needed.
1919 clearInputSurfaceIfNeeded = true;
1920 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001921 state->set(RELEASING);
1922 }
1923
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001924 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001925 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1926 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001927 if (config->mInputSurface) {
1928 config->mInputSurface->disconnect();
1929 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001930 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001931 }
1932 }
Guillaume Chelfi2d4c9db2022-03-18 13:43:49 +01001933 {
1934 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1935 const std::unique_ptr<Config> &config = *configLocked;
1936 if (config->mPushBlankBuffersOnStop) {
1937 mChannel->pushBlankBufferToOutputSurface();
1938 }
1939 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001940
Wonsik Kim936a89c2020-05-08 16:07:50 -07001941 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001942 // thiz holds strong ref to this while the thread is running.
1943 sp<CCodec> thiz(this);
1944 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1945}
1946
1947void CCodec::release(bool sendCallback) {
1948 std::shared_ptr<Codec2Client::Component> comp;
1949 {
1950 Mutexed<State>::Locked state(mState);
1951 if (state->get() == RELEASED) {
1952 if (sendCallback) {
1953 state.unlock();
1954 mCallback->onReleaseCompleted();
1955 state.lock();
1956 }
1957 return;
1958 }
1959 comp = state->comp;
1960 }
1961 comp->release();
1962
1963 {
1964 Mutexed<State>::Locked state(mState);
1965 state->set(RELEASED);
1966 state->comp.reset();
1967 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001968 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001969 if (sendCallback) {
1970 mCallback->onReleaseCompleted();
1971 }
1972}
1973
1974status_t CCodec::setSurface(const sp<Surface> &surface) {
Wonsik Kim75e22f42021-04-14 23:34:51 -07001975 {
1976 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1977 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08001978 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
1979 status_t err = OK;
1980
Wonsik Kim75e22f42021-04-14 23:34:51 -07001981 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08001982 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07001983 nativeWindow.get(),
1984 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
1985 if (err != OK) {
1986 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
1987 nativeWindow.get(), config->mSidebandHandle->handle(), err);
1988 return err;
1989 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08001990 } else {
1991 // Explicitly reset the sideband handle of the window for
1992 // non-tunneled video in case the window was previously used
1993 // for a tunneled video playback.
1994 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
1995 if (err != OK) {
1996 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
1997 return err;
1998 }
ted.sun765db4d2020-06-23 14:03:41 +08001999 }
2000 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002001 return mChannel->setSurface(surface);
2002}
2003
2004void CCodec::signalFlush() {
2005 status_t err = [this] {
2006 Mutexed<State>::Locked state(mState);
2007 if (state->get() == FLUSHED) {
2008 return ALREADY_EXISTS;
2009 }
2010 if (state->get() != RUNNING) {
2011 return UNKNOWN_ERROR;
2012 }
2013 state->set(FLUSHING);
2014 return OK;
2015 }();
2016 switch (err) {
2017 case ALREADY_EXISTS:
2018 mCallback->onFlushCompleted();
2019 return;
2020 case OK:
2021 break;
2022 default:
2023 mCallback->onError(err, ACTION_CODE_FATAL);
2024 return;
2025 }
2026
2027 mChannel->stop();
2028 (new AMessage(kWhatFlush, this))->post();
2029}
2030
2031void CCodec::flush() {
2032 std::shared_ptr<Codec2Client::Component> comp;
2033 auto checkFlushing = [this, &comp] {
2034 Mutexed<State>::Locked state(mState);
2035 if (state->get() != FLUSHING) {
2036 return UNKNOWN_ERROR;
2037 }
2038 comp = state->comp;
2039 return OK;
2040 };
2041 if (tryAndReportOnError(checkFlushing) != OK) {
2042 return;
2043 }
2044
2045 std::list<std::unique_ptr<C2Work>> flushedWork;
2046 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
2047 {
2048 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2049 flushedWork.splice(flushedWork.end(), *queue);
2050 }
2051 if (err != C2_OK) {
2052 // TODO: convert err into status_t
2053 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2054 }
2055
2056 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002057
2058 {
2059 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08002060 if (state->get() == FLUSHING) {
2061 state->set(FLUSHED);
2062 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002063 }
2064 mCallback->onFlushCompleted();
2065}
2066
2067void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08002068 std::shared_ptr<Codec2Client::Component> comp;
2069 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002070 Mutexed<State>::Locked state(mState);
2071 if (state->get() != FLUSHED) {
2072 return UNKNOWN_ERROR;
2073 }
2074 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002075 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002076 return OK;
2077 };
2078 if (tryAndReportOnError(setResuming) != OK) {
2079 return;
2080 }
2081
Wonsik Kime75a5da2020-02-14 17:29:03 -08002082 {
2083 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2084 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002085 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08002086 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002087 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002088 }
2089
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002090 (void)mChannel->start(nullptr, nullptr, [&]{
2091 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2092 const std::unique_ptr<Config> &config = *configLocked;
2093 return config->mBuffersBoundToCodec;
2094 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002095
2096 {
2097 Mutexed<State>::Locked state(mState);
2098 if (state->get() != RESUMING) {
2099 state.unlock();
2100 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2101 state.lock();
2102 return;
2103 }
2104 state->set(RUNNING);
2105 }
2106
2107 (void)mChannel->requestInitialInputBuffers();
2108}
2109
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002110void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002111 std::shared_ptr<Codec2Client::Component> comp;
2112 auto checkState = [this, &comp] {
2113 Mutexed<State>::Locked state(mState);
2114 if (state->get() == RELEASED) {
2115 return INVALID_OPERATION;
2116 }
2117 comp = state->comp;
2118 return OK;
2119 };
2120 if (tryAndReportOnError(checkState) != OK) {
2121 return;
2122 }
2123
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002124 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2125 // the behavior here.
2126 sp<AMessage> params = msg;
2127 int32_t bitrate;
2128 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2129 params = msg->dup();
2130 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2131 }
2132
Houxiang Dai5a97b472021-03-22 17:56:04 +08002133 int32_t syncId = 0;
2134 if (params->findInt32("audio-hw-sync", &syncId)
2135 || params->findInt32("hw-av-sync-id", &syncId)) {
2136 configureTunneledVideoPlayback(comp, nullptr, params);
2137 }
2138
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002139 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2140 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002141
2142 /**
2143 * Handle input surface parameters
2144 */
2145 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002146 && (config->mDomain & Config::IS_ENCODER)
2147 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002148 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002149
2150 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2151 config->mISConfig->mStopped = false;
2152 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2153 config->mISConfig->mStopped = true;
2154 }
2155
2156 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002157 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002158 config->mISConfig->mSuspended = value;
2159 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002160 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002161 }
2162
2163 (void)config->mInputSurface->configure(*config->mISConfig);
2164 if (config->mISConfig->mStopped) {
2165 config->mInputFormat->setInt64(
2166 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2167 }
2168 }
2169
2170 std::vector<std::unique_ptr<C2Param>> configUpdate;
2171 (void)config->getConfigUpdateFromSdkParams(
2172 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2173 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2174 // Parameter synchronization is not defined when using input surface. For now, route
2175 // these directly to the component.
2176 if (config->mInputSurface == nullptr
2177 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2178 || comp->getName().find("c2.android.") == 0)) {
2179 mChannel->setParameters(configUpdate);
2180 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002181 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002182 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002183 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002184 }
2185}
2186
2187void CCodec::signalEndOfInputStream() {
2188 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2189}
2190
2191void CCodec::signalRequestIDRFrame() {
2192 std::shared_ptr<Codec2Client::Component> comp;
2193 {
2194 Mutexed<State>::Locked state(mState);
2195 if (state->get() == RELEASED) {
2196 ALOGD("no IDR request sent since component is released");
2197 return;
2198 }
2199 comp = state->comp;
2200 }
2201 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002202 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2203 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002204 std::vector<std::unique_ptr<C2Param>> params;
2205 params.push_back(
2206 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2207 config->setParameters(comp, params, C2_MAY_BLOCK);
2208}
2209
Wonsik Kim874ad382021-03-12 09:59:36 -08002210status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2211 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2212 const std::unique_ptr<Config> &config = *configLocked;
2213 return config->querySupportedParameters(names);
2214}
2215
2216status_t CCodec::describeParameter(
2217 const std::string &name, CodecParameterDescriptor *desc) {
2218 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2219 const std::unique_ptr<Config> &config = *configLocked;
2220 return config->describe(name, desc);
2221}
2222
2223status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2224 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2225 if (!comp) {
2226 return INVALID_OPERATION;
2227 }
2228 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2229 const std::unique_ptr<Config> &config = *configLocked;
2230 return config->subscribeToVendorConfigUpdate(comp, names);
2231}
2232
2233status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2234 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2235 if (!comp) {
2236 return INVALID_OPERATION;
2237 }
2238 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2239 const std::unique_ptr<Config> &config = *configLocked;
2240 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2241}
2242
Wonsik Kimab34ed62019-01-31 15:28:46 -08002243void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002244 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002245 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2246 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002247 }
2248 (new AMessage(kWhatWorkDone, this))->post();
2249}
2250
Wonsik Kimab34ed62019-01-31 15:28:46 -08002251void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2252 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002253 if (arrayIndex == 0) {
2254 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002255 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2256 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002257 if (config->mInputSurface) {
2258 config->mInputSurface->onInputBufferDone(frameIndex);
2259 }
2260 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002261}
2262
2263void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2264 TimePoint now = std::chrono::steady_clock::now();
2265 CCodecWatchdog::getInstance()->watch(this);
2266 switch (msg->what()) {
2267 case kWhatAllocate: {
2268 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002269 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002270 sp<RefBase> obj;
2271 CHECK(msg->findObject("codecInfo", &obj));
2272 allocate((MediaCodecInfo *)obj.get());
2273 break;
2274 }
2275 case kWhatConfigure: {
2276 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002277 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002278 sp<AMessage> format;
2279 CHECK(msg->findMessage("format", &format));
2280 configure(format);
2281 break;
2282 }
2283 case kWhatStart: {
2284 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002285 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002286 start();
2287 break;
2288 }
2289 case kWhatStop: {
2290 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002291 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002292 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002293 break;
2294 }
2295 case kWhatFlush: {
2296 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002297 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002298 flush();
2299 break;
2300 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002301 case kWhatRelease: {
2302 mChannel->release();
2303 mClient.reset();
2304 mClientListener.reset();
2305 break;
2306 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002307 case kWhatCreateInputSurface: {
2308 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002309 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002310 createInputSurface();
2311 break;
2312 }
2313 case kWhatSetInputSurface: {
2314 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002315 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002316 sp<RefBase> obj;
2317 CHECK(msg->findObject("surface", &obj));
2318 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2319 setInputSurface(surface);
2320 break;
2321 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002322 case kWhatWorkDone: {
2323 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002324 bool shouldPost = false;
2325 {
2326 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2327 if (queue->empty()) {
2328 break;
2329 }
2330 work.swap(queue->front());
2331 queue->pop_front();
2332 shouldPost = !queue->empty();
2333 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002334 if (shouldPost) {
2335 (new AMessage(kWhatWorkDone, this))->post();
2336 }
2337
Pawin Vongmasa36653902018-11-15 00:10:25 -08002338 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002339 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002340 sp<AMessage> outputFormat = nullptr;
2341 {
2342 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2343 const std::unique_ptr<Config> &config = *configLocked;
2344 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2345 config->watch<C2StreamInitDataInfo::output>();
2346 if (!work->worklets.empty()
2347 && (work->worklets.front()->output.flags
2348 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002349
Wonsik Kim75e22f42021-04-14 23:34:51 -07002350 // copy buffer info to config
2351 std::vector<std::unique_ptr<C2Param>> updates;
2352 for (const std::unique_ptr<C2Param> &param
2353 : work->worklets.front()->output.configUpdate) {
2354 updates.push_back(C2Param::Copy(*param));
2355 }
2356 unsigned stream = 0;
2357 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2358 work->worklets.front()->output.buffers;
2359 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2360 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2361 // move all info into output-stream #0 domain
2362 updates.emplace_back(
2363 C2Param::CopyAsStream(*info, true /* output */, stream));
2364 }
2365
2366 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2367 // for now only do the first block
2368 if (!blocks.empty()) {
2369 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2370 // block.crop().left, block.crop().top,
2371 // block.crop().width, block.crop().height,
2372 // block.width(), block.height());
2373 const C2ConstGraphicBlock &block = blocks[0];
2374 updates.emplace_back(new C2StreamCropRectInfo::output(
2375 stream, block.crop()));
Wonsik Kim75e22f42021-04-14 23:34:51 -07002376 }
2377 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002378 }
George Burgess IVc813a592020-02-22 22:54:44 -08002379
Wonsik Kim75e22f42021-04-14 23:34:51 -07002380 sp<AMessage> oldFormat = config->mOutputFormat;
2381 config->updateConfiguration(updates, config->mOutputDomain);
2382 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002383
Wonsik Kim75e22f42021-04-14 23:34:51 -07002384 // copy standard infos to graphic buffers if not already present (otherwise, we
2385 // may overwrite the actual intermediate value with a final value)
2386 stream = 0;
2387 const static C2Param::Index stdGfxInfos[] = {
2388 C2StreamRotationInfo::output::PARAM_TYPE,
2389 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2390 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2391 C2StreamHdrStaticInfo::output::PARAM_TYPE,
2392 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
2393 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2394 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2395 };
2396 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2397 if (buf->data().graphicBlocks().size()) {
2398 for (C2Param::Index ix : stdGfxInfos) {
2399 if (!buf->hasInfo(ix)) {
2400 const C2Param *param =
2401 config->getConfigParameterValue(ix.withStream(stream));
2402 if (param) {
2403 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2404 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2405 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002406 }
2407 }
2408 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002409 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002410 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002411 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002412 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302413 if (work->worklets.empty()
2414 || !work->worklets.back()
2415 || (work->worklets.back()->output.flags
2416 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2417 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2418 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002419 }
2420 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002421 initData = initDataWatcher.update();
2422 AmendOutputFormatWithCodecSpecificData(
2423 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2424 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002425 }
2426 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002427 }
2428 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002429 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002430 break;
2431 }
2432 case kWhatWatch: {
2433 // watch message already posted; no-op.
2434 break;
2435 }
2436 default: {
2437 ALOGE("unrecognized message");
2438 break;
2439 }
2440 }
2441 setDeadline(TimePoint::max(), 0ms, "none");
2442}
2443
2444void CCodec::setDeadline(
2445 const TimePoint &now,
2446 const std::chrono::milliseconds &timeout,
2447 const char *name) {
2448 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2449 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2450 deadline->set(now + (timeout * mult), name);
2451}
2452
ted.sun765db4d2020-06-23 14:03:41 +08002453status_t CCodec::configureTunneledVideoPlayback(
2454 std::shared_ptr<Codec2Client::Component> comp,
2455 sp<NativeHandle> *sidebandHandle,
2456 const sp<AMessage> &msg) {
2457 std::vector<std::unique_ptr<C2SettingResult>> failures;
2458
2459 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2460 C2PortTunneledModeTuning::output::AllocUnique(
2461 1,
2462 C2PortTunneledModeTuning::Struct::SIDEBAND,
2463 C2PortTunneledModeTuning::Struct::REALTIME,
2464 0);
2465 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2466 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2467 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2468 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2469 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2470 } else {
2471 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2472 tunneledPlayback->setFlexCount(0);
2473 }
2474 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2475 if (c2err != C2_OK) {
2476 return UNKNOWN_ERROR;
2477 }
2478
Houxiang Dai5a97b472021-03-22 17:56:04 +08002479 if (sidebandHandle == nullptr) {
2480 return OK;
2481 }
2482
ted.sun765db4d2020-06-23 14:03:41 +08002483 std::vector<std::unique_ptr<C2Param>> params;
2484 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2485 if (c2err == C2_OK && params.size() == 1u) {
2486 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2487 C2PortTunnelHandleTuning::output::From(params[0].get());
2488 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2489 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2490 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2491 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2492 memcpy(handle->data, videoTunnelSideband->m.values,
2493 sizeof(int32_t) * videoTunnelSideband->flexCount());
2494 return OK;
2495 } else {
2496 return NO_MEMORY;
2497 }
2498 }
2499 return UNKNOWN_ERROR;
2500}
2501
Pawin Vongmasa36653902018-11-15 00:10:25 -08002502void CCodec::initiateReleaseIfStuck() {
2503 std::string name;
2504 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002505 {
2506 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002507 if (deadline->get() < std::chrono::steady_clock::now()) {
2508 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002509 }
2510 if (deadline->get() != TimePoint::max()) {
2511 pendingDeadline = true;
2512 }
2513 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002514 bool tunneled = false;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002515 bool isMediaTypeKnown = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002516 {
Wonsik Kimabca11e2021-04-30 13:11:41 -07002517 static const std::set<std::string> kKnownMediaTypes{
2518 MIMETYPE_VIDEO_VP8,
2519 MIMETYPE_VIDEO_VP9,
2520 MIMETYPE_VIDEO_AV1,
2521 MIMETYPE_VIDEO_AVC,
2522 MIMETYPE_VIDEO_HEVC,
2523 MIMETYPE_VIDEO_MPEG4,
2524 MIMETYPE_VIDEO_H263,
2525 MIMETYPE_VIDEO_MPEG2,
2526 MIMETYPE_VIDEO_RAW,
2527 MIMETYPE_VIDEO_DOLBY_VISION,
2528
2529 MIMETYPE_AUDIO_AMR_NB,
2530 MIMETYPE_AUDIO_AMR_WB,
2531 MIMETYPE_AUDIO_MPEG,
2532 MIMETYPE_AUDIO_AAC,
2533 MIMETYPE_AUDIO_QCELP,
2534 MIMETYPE_AUDIO_VORBIS,
2535 MIMETYPE_AUDIO_OPUS,
2536 MIMETYPE_AUDIO_G711_ALAW,
2537 MIMETYPE_AUDIO_G711_MLAW,
2538 MIMETYPE_AUDIO_RAW,
2539 MIMETYPE_AUDIO_FLAC,
2540 MIMETYPE_AUDIO_MSGSM,
2541 MIMETYPE_AUDIO_AC3,
2542 MIMETYPE_AUDIO_EAC3,
2543
2544 MIMETYPE_IMAGE_ANDROID_HEIC,
2545 };
Wonsik Kim75e22f42021-04-14 23:34:51 -07002546 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2547 const std::unique_ptr<Config> &config = *configLocked;
2548 tunneled = config->mTunneled;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002549 isMediaTypeKnown = (kKnownMediaTypes.count(config->mCodingMediaType) != 0);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002550 }
Wonsik Kimabca11e2021-04-30 13:11:41 -07002551 if (!tunneled && isMediaTypeKnown && name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002552 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2553 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2554 if (elapsed >= kWorkDurationThreshold) {
2555 name = "queue";
2556 }
2557 if (elapsed > 0s) {
2558 pendingDeadline = true;
2559 }
2560 }
2561 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002562 // We're not stuck.
2563 if (pendingDeadline) {
2564 // If we are not stuck yet but still has deadline coming up,
2565 // post watch message to check back later.
2566 (new AMessage(kWhatWatch, this))->post();
2567 }
2568 return;
2569 }
2570
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002571 C2String compName;
2572 {
2573 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002574 if (!state->comp) {
2575 ALOGD("previous call to %s exceeded timeout "
2576 "and the component is already released", name.c_str());
2577 return;
2578 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002579 compName = state->comp->getName();
2580 }
2581 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2582
Pawin Vongmasa36653902018-11-15 00:10:25 -08002583 initiateRelease(false);
2584 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2585}
2586
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002587// static
2588PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002589 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002590 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002591 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002592 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2593 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002594 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002595 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2596 sp<IGraphicBufferProducer> gbp;
2597 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2598 status_t err = gbs->initCheck();
2599 if (err != OK) {
2600 ALOGE("Failed to create persistent input surface: error %d", err);
2601 return nullptr;
2602 }
2603 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002604 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002605 } else {
2606 return nullptr;
2607 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002608 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002609 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002610 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002611 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002612 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002613}
2614
Wonsik Kimffb889a2020-05-28 11:32:25 -07002615class IntfCache {
2616public:
2617 IntfCache() = default;
2618
2619 status_t init(const std::string &name) {
2620 std::shared_ptr<Codec2Client::Interface> intf{
2621 Codec2Client::CreateInterfaceByName(name.c_str())};
2622 if (!intf) {
2623 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2624 mInitStatus = NO_INIT;
2625 return NO_INIT;
2626 }
2627 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2628 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2629 C2ParamField{&sUsage, &sUsage.value}));
2630 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2631 if (err != C2_OK) {
2632 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2633 name.c_str(), err);
2634 mFields[0].status = err;
2635 }
2636 std::vector<std::unique_ptr<C2Param>> params;
2637 err = intf->query(
2638 {&mApiFeatures},
Taehwan Kim900b49c2021-12-13 11:16:22 +09002639 {
2640 C2StreamBufferTypeSetting::input::PARAM_TYPE,
2641 C2PortAllocatorsTuning::input::PARAM_TYPE
2642 },
Wonsik Kimffb889a2020-05-28 11:32:25 -07002643 C2_MAY_BLOCK,
2644 &params);
2645 if (err != C2_OK && err != C2_BAD_INDEX) {
2646 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2647 name.c_str(), err);
2648 }
2649 while (!params.empty()) {
2650 C2Param *param = params.back().release();
2651 params.pop_back();
2652 if (!param) {
2653 continue;
2654 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002655 if (param->type() == C2StreamBufferTypeSetting::input::PARAM_TYPE) {
2656 mInputStreamFormat.reset(
2657 C2StreamBufferTypeSetting::input::From(param));
2658 } else if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002659 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002660 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002661 }
2662 }
2663 mInitStatus = OK;
2664 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002665 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002666
2667 status_t initCheck() const { return mInitStatus; }
2668
2669 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2670 CHECK_EQ(1u, mFields.size());
2671 return mFields[0];
2672 }
2673
2674 const C2ApiFeaturesSetting &getApiFeatures() const {
2675 return mApiFeatures;
2676 }
2677
Taehwan Kim900b49c2021-12-13 11:16:22 +09002678 const C2StreamBufferTypeSetting::input &getInputStreamFormat() const {
2679 static std::unique_ptr<C2StreamBufferTypeSetting::input> sInvalidated = []{
2680 std::unique_ptr<C2StreamBufferTypeSetting::input> param;
2681 param.reset(new C2StreamBufferTypeSetting::input(0u, C2BufferData::INVALID));
2682 param->invalidate();
2683 return param;
2684 }();
2685 return mInputStreamFormat ? *mInputStreamFormat : *sInvalidated;
2686 }
2687
Wonsik Kimffb889a2020-05-28 11:32:25 -07002688 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2689 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2690 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2691 C2PortAllocatorsTuning::input::AllocUnique(0);
2692 param->invalidate();
2693 return param;
2694 }();
2695 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2696 }
2697
2698private:
2699 status_t mInitStatus{NO_INIT};
2700
2701 std::vector<C2FieldSupportedValuesQuery> mFields;
2702 C2ApiFeaturesSetting mApiFeatures;
Taehwan Kim900b49c2021-12-13 11:16:22 +09002703 std::unique_ptr<C2StreamBufferTypeSetting::input> mInputStreamFormat;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002704 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2705};
2706
2707static const IntfCache &GetIntfCache(const std::string &name) {
2708 static IntfCache sNullIntfCache;
2709 static std::mutex sMutex;
2710 static std::map<std::string, IntfCache> sCache;
2711 std::unique_lock<std::mutex> lock{sMutex};
2712 auto it = sCache.find(name);
2713 if (it == sCache.end()) {
2714 lock.unlock();
2715 IntfCache intfCache;
2716 status_t err = intfCache.init(name);
2717 if (err != OK) {
2718 return sNullIntfCache;
2719 }
2720 lock.lock();
2721 it = sCache.insert({name, std::move(intfCache)}).first;
2722 }
2723 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002724}
2725
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002726static status_t GetCommonAllocatorIds(
2727 const std::vector<std::string> &names,
2728 C2Allocator::type_t type,
2729 std::set<C2Allocator::id_t> *ids) {
2730 int poolMask = GetCodec2PoolMask();
2731 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2732 C2Allocator::id_t defaultAllocatorId =
2733 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2734
2735 ids->clear();
2736 if (names.empty()) {
2737 return OK;
2738 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002739 bool firstIteration = true;
2740 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002741 const IntfCache &intfCache = GetIntfCache(name);
2742 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002743 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002744 }
Taehwan Kim900b49c2021-12-13 11:16:22 +09002745 const C2StreamBufferTypeSetting::input &streamFormat = intfCache.getInputStreamFormat();
2746 if (streamFormat) {
2747 C2Allocator::type_t allocatorType = C2Allocator::LINEAR;
2748 if (streamFormat.value == C2BufferData::GRAPHIC
2749 || streamFormat.value == C2BufferData::GRAPHIC_CHUNKS) {
2750 allocatorType = C2Allocator::GRAPHIC;
2751 }
2752
2753 if (type != allocatorType) {
2754 // requested type is not supported at input allocators
2755 ids->clear();
2756 ids->insert(defaultAllocatorId);
2757 ALOGV("name(%s) does not support a type(0x%x) as input allocator."
2758 " uses default allocator id(%d)", name.c_str(), type, defaultAllocatorId);
2759 break;
2760 }
2761 }
2762
Wonsik Kimffb889a2020-05-28 11:32:25 -07002763 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002764 if (firstIteration) {
2765 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002766 if (allocators && allocators.flexCount() > 0) {
2767 ids->insert(allocators.m.values,
2768 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002769 }
2770 if (ids->empty()) {
2771 // The component does not advertise allocators. Use default.
2772 ids->insert(defaultAllocatorId);
2773 }
2774 continue;
2775 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002776 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002777 if (allocators && allocators.flexCount() > 0) {
2778 filtered = true;
2779 for (auto it = ids->begin(); it != ids->end(); ) {
2780 bool found = false;
2781 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2782 if (allocators.m.values[j] == *it) {
2783 found = true;
2784 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002785 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002786 }
2787 if (found) {
2788 ++it;
2789 } else {
2790 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002791 }
2792 }
2793 }
2794 if (!filtered) {
2795 // The component does not advertise supported allocators. Use default.
2796 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2797 if (ids->size() != (containsDefault ? 1 : 0)) {
2798 ids->clear();
2799 if (containsDefault) {
2800 ids->insert(defaultAllocatorId);
2801 }
2802 }
2803 }
2804 }
2805 // Finally, filter with pool masks
2806 for (auto it = ids->begin(); it != ids->end(); ) {
2807 if ((poolMask >> *it) & 1) {
2808 ++it;
2809 } else {
2810 it = ids->erase(it);
2811 }
2812 }
2813 return OK;
2814}
2815
2816static status_t CalculateMinMaxUsage(
2817 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2818 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2819 *minUsage = 0;
2820 *maxUsage = ~0ull;
2821 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002822 const IntfCache &intfCache = GetIntfCache(name);
2823 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002824 continue;
2825 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002826 const C2FieldSupportedValuesQuery &usageSupportedValues =
2827 intfCache.getUsageSupportedValues();
2828 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002829 continue;
2830 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002831 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002832 if (supported.type != C2FieldSupportedValues::FLAGS) {
2833 continue;
2834 }
2835 if (supported.values.empty()) {
2836 *maxUsage = 0;
2837 continue;
2838 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08002839 if (supported.values.size() > 1) {
2840 *minUsage |= supported.values[1].u64;
2841 } else {
2842 *minUsage |= supported.values[0].u64;
2843 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002844 int64_t currentMaxUsage = 0;
2845 for (const C2Value::Primitive &flags : supported.values) {
2846 currentMaxUsage |= flags.u64;
2847 }
2848 *maxUsage &= currentMaxUsage;
2849 }
2850 return OK;
2851}
2852
2853// static
2854status_t CCodec::CanFetchLinearBlock(
2855 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002856 for (const std::string &name : names) {
2857 const IntfCache &intfCache = GetIntfCache(name);
2858 if (intfCache.initCheck() != OK) {
2859 continue;
2860 }
2861 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2862 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2863 *isCompatible = false;
2864 return OK;
2865 }
2866 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002867 std::set<C2Allocator::id_t> allocators;
2868 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2869 if (allocators.empty()) {
2870 *isCompatible = false;
2871 return OK;
2872 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002873
2874 uint64_t minUsage = 0;
2875 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002876 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002877 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002878 *isCompatible = ((maxUsage & minUsage) == minUsage);
2879 return OK;
2880}
2881
2882static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2883 static std::mutex sMutex{};
2884 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2885 std::unique_lock<std::mutex> lock{sMutex};
2886 std::shared_ptr<C2BlockPool> pool;
2887 auto it = sPools.find(allocId);
2888 if (it == sPools.end()) {
2889 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2890 if (err == OK) {
2891 sPools.emplace(allocId, pool);
2892 } else {
2893 pool.reset();
2894 }
2895 } else {
2896 pool = it->second;
2897 }
2898 return pool;
2899}
2900
2901// static
2902std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2903 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002904 std::set<C2Allocator::id_t> allocators;
2905 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2906 if (allocators.empty()) {
2907 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2908 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002909
2910 uint64_t minUsage = 0;
2911 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002912 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002913 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002914 if ((maxUsage & minUsage) != minUsage) {
2915 allocators.clear();
2916 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2917 }
2918 std::shared_ptr<C2LinearBlock> block;
2919 for (C2Allocator::id_t allocId : allocators) {
2920 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2921 if (!pool) {
2922 continue;
2923 }
2924 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2925 if (err != C2_OK || !block) {
2926 block.reset();
2927 continue;
2928 }
2929 break;
2930 }
2931 return block;
2932}
2933
2934// static
2935status_t CCodec::CanFetchGraphicBlock(
2936 const std::vector<std::string> &names, bool *isCompatible) {
2937 uint64_t minUsage = 0;
2938 uint64_t maxUsage = ~0ull;
2939 std::set<C2Allocator::id_t> allocators;
2940 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2941 if (allocators.empty()) {
2942 *isCompatible = false;
2943 return OK;
2944 }
2945 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2946 *isCompatible = ((maxUsage & minUsage) == minUsage);
2947 return OK;
2948}
2949
2950// static
2951std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2952 int32_t width,
2953 int32_t height,
2954 int32_t format,
2955 uint64_t usage,
2956 const std::vector<std::string> &names) {
2957 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2958 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2959 ALOGD("Unrecognized pixel format: %d", format);
2960 return nullptr;
2961 }
2962 uint64_t minUsage = 0;
2963 uint64_t maxUsage = ~0ull;
2964 std::set<C2Allocator::id_t> allocators;
2965 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2966 if (allocators.empty()) {
2967 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2968 }
2969 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2970 minUsage |= usage;
2971 if ((maxUsage & minUsage) != minUsage) {
2972 allocators.clear();
2973 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2974 }
2975 std::shared_ptr<C2GraphicBlock> block;
2976 for (C2Allocator::id_t allocId : allocators) {
2977 std::shared_ptr<C2BlockPool> pool;
2978 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2979 if (err != C2_OK || !pool) {
2980 continue;
2981 }
2982 err = pool->fetchGraphicBlock(
2983 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2984 if (err != C2_OK || !block) {
2985 block.reset();
2986 continue;
2987 }
2988 break;
2989 }
2990 return block;
2991}
2992
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002993} // namespace android