blob: 7b55b63fe0471c3a07645d5047294b90836f929f [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
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700215 mSource->configure(
216 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800217 return OK;
218 }
219
220 void disconnect() override {
221 if (mNode == nullptr) {
222 return;
223 }
224 sp<IOMXBufferSource> source = mNode->getSource();
225 if (source == nullptr) {
226 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
227 return;
228 }
229 source->onOmxIdle();
230 source->onOmxLoaded();
231 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700232 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800233 }
234
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700235 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
236 if (status.isOk()) {
237 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
238 } else if (status.isDeadObject()) {
239 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800240 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700241 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800242 }
243
244 status_t start() override {
245 sp<IOMXBufferSource> source = mNode->getSource();
246 if (source == nullptr) {
247 return NO_INIT;
248 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900249
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800250 size_t numSlots = 16;
Wonsik Kim34d66012021-03-01 16:40:33 -0800251 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900252
Wonsik Kim34d66012021-03-01 16:40:33 -0800253 OMX_PARAM_PORTDEFINITIONTYPE param;
254 param.nPortIndex = kPortIndexInput;
255 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
256 &param, sizeof(param));
257 if (err == OK) {
258 numSlots = param.nBufferCountActual;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900259 }
260
261 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800262 source->onInputBufferAdded(i);
263 }
264
265 source->onOmxExecuting();
266 return OK;
267 }
268
269 status_t signalEndOfInputStream() override {
270 return GetStatus(mSource->signalEndOfInputStream());
271 }
272
273 status_t configure(Config &config) {
274 std::stringstream status;
275 status_t err = OK;
276
277 // handle each configuration granually, in case we need to handle part of the configuration
278 // elsewhere
279
280 // TRICKY: we do not unset frame delay repeating
281 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
282 int64_t us = 1e6 / config.mMinFps + 0.5;
283 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
284 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
285 if (res != OK) {
286 status << " (=> " << asString(res) << ")";
287 err = res;
288 }
289 mConfig.mMinFps = config.mMinFps;
290 }
291
292 // pts gap
293 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
294 if (mNode != nullptr) {
295 OMX_PARAM_U32TYPE ptrGapParam = {};
296 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700297 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800298 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
299 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700300 // float -> uint32_t is undefined if the value is negative.
301 // First convert to int32_t to ensure the expected behavior.
302 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800303 (void)mNode->setParameter(
304 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
305 &ptrGapParam, sizeof(ptrGapParam));
306 }
307 }
308
309 // max fps
310 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700311 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800312 && config.mMaxFps != mConfig.mMaxFps) {
313 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
314 status << " maxFps=" << config.mMaxFps;
315 if (res != OK) {
316 status << " (=> " << asString(res) << ")";
317 err = res;
318 }
319 mConfig.mMaxFps = config.mMaxFps;
320 }
321
322 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
323 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
324 status << " timeOffset " << config.mTimeOffsetUs << "us";
325 if (res != OK) {
326 status << " (=> " << asString(res) << ")";
327 err = res;
328 }
329 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
330 }
331
332 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
333 status_t res =
334 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
335 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
336 if (res != OK) {
337 status << " (=> " << asString(res) << ")";
338 err = res;
339 }
340 mConfig.mCaptureFps = config.mCaptureFps;
341 mConfig.mCodedFps = config.mCodedFps;
342 }
343
344 if (config.mStartAtUs != mConfig.mStartAtUs
345 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
346 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
347 status << " start at " << config.mStartAtUs << "us";
348 if (res != OK) {
349 status << " (=> " << asString(res) << ")";
350 err = res;
351 }
352 mConfig.mStartAtUs = config.mStartAtUs;
353 mConfig.mStopped = config.mStopped;
354 }
355
356 // suspend-resume
357 if (config.mSuspended != mConfig.mSuspended) {
358 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
359 status << " " << (config.mSuspended ? "suspend" : "resume")
360 << " at " << config.mSuspendAtUs << "us";
361 if (res != OK) {
362 status << " (=> " << asString(res) << ")";
363 err = res;
364 }
365 mConfig.mSuspended = config.mSuspended;
366 mConfig.mSuspendAtUs = config.mSuspendAtUs;
367 }
368
369 if (config.mStopped != mConfig.mStopped && config.mStopped) {
370 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
371 status << " stop at " << config.mStopAtUs << "us";
372 if (res != OK) {
373 status << " (=> " << asString(res) << ")";
374 err = res;
375 } else {
376 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700377 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
378 [&res, &delayUs = config.mInputDelayUs](
379 auto status, auto stopTimeOffsetUs) {
380 res = static_cast<status_t>(status);
381 delayUs = stopTimeOffsetUs;
382 });
383 if (!trans.isOk()) {
384 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
385 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800386 if (res != OK) {
387 status << " (=> " << asString(res) << ")";
388 } else {
389 status << "=" << config.mInputDelayUs << "us";
390 }
391 mConfig.mInputDelayUs = config.mInputDelayUs;
392 }
393 mConfig.mStopAtUs = config.mStopAtUs;
394 mConfig.mStopped = config.mStopped;
395 }
396
397 // color aspects (android._color-aspects)
398
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700399 // consumer usage is queried earlier.
400
Wonsik Kimbd557932019-07-02 15:51:20 -0700401 if (status.str().empty()) {
402 ALOGD("ISConfig not changed");
403 } else {
404 ALOGD("ISConfig%s", status.str().c_str());
405 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800406 return err;
407 }
408
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700409 void onInputBufferDone(c2_cntr64_t index) override {
410 mNode->onInputBufferDone(index);
411 }
412
Wonsik Kim673dd192021-01-29 14:58:12 -0800413 android_dataspace getDataspace() override {
414 return mNode->getDataspace();
415 }
416
Pawin Vongmasa36653902018-11-15 00:10:25 -0800417private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700418 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800419 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700420 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800421 uint32_t mWidth;
422 uint32_t mHeight;
423 Config mConfig;
424};
425
426class Codec2ClientInterfaceWrapper : public C2ComponentStore {
427 std::shared_ptr<Codec2Client> mClient;
428
429public:
430 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
431 : mClient(client) { }
432
433 virtual ~Codec2ClientInterfaceWrapper() = default;
434
435 virtual c2_status_t config_sm(
436 const std::vector<C2Param *> &params,
437 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
438 return mClient->config(params, C2_MAY_BLOCK, failures);
439 };
440
441 virtual c2_status_t copyBuffer(
442 std::shared_ptr<C2GraphicBuffer>,
443 std::shared_ptr<C2GraphicBuffer>) {
444 return C2_OMITTED;
445 }
446
447 virtual c2_status_t createComponent(
448 C2String, std::shared_ptr<C2Component> *const component) {
449 component->reset();
450 return C2_OMITTED;
451 }
452
453 virtual c2_status_t createInterface(
454 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
455 interface->reset();
456 return C2_OMITTED;
457 }
458
459 virtual c2_status_t query_sm(
460 const std::vector<C2Param *> &stackParams,
461 const std::vector<C2Param::Index> &heapParamIndices,
462 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
463 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
464 }
465
466 virtual c2_status_t querySupportedParams_nb(
467 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
468 return mClient->querySupportedParams(params);
469 }
470
471 virtual c2_status_t querySupportedValues_sm(
472 std::vector<C2FieldSupportedValuesQuery> &fields) const {
473 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
474 }
475
476 virtual C2String getName() const {
477 return mClient->getName();
478 }
479
480 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
481 return mClient->getParamReflector();
482 }
483
484 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
485 return std::vector<std::shared_ptr<const C2Component::Traits>>();
486 }
487};
488
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800489void RevertOutputFormatIfNeeded(
490 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
491 // We used to not report changes to these keys to the client.
492 const static std::set<std::string> sIgnoredKeys({
493 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800494 KEY_FRAME_RATE,
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800495 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800496 KEY_MAX_WIDTH,
497 KEY_MAX_HEIGHT,
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800498 "csd-0",
499 "csd-1",
500 "csd-2",
501 });
502 if (currentFormat == oldFormat) {
503 return;
504 }
505 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
506 AMessage::Type type;
507 for (size_t i = diff->countEntries(); i > 0; --i) {
508 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
509 diff->removeEntryAt(i - 1);
510 }
511 }
512 if (diff->countEntries() == 0) {
513 currentFormat = oldFormat;
514 }
515}
516
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700517void AmendOutputFormatWithCodecSpecificData(
518 const uint8_t *data, size_t size, const std::string mediaType,
519 const sp<AMessage> &outputFormat) {
520 if (mediaType == MIMETYPE_VIDEO_AVC) {
521 // Codec specific data should be SPS and PPS in a single buffer,
522 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
523 // We separate the two and put them into the output format
524 // under the keys "csd-0" and "csd-1".
525
526 unsigned csdIndex = 0;
527
528 const uint8_t *nalStart;
529 size_t nalSize;
530 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
531 sp<ABuffer> csd = new ABuffer(nalSize + 4);
532 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
533 memcpy(csd->data() + 4, nalStart, nalSize);
534
535 outputFormat->setBuffer(
536 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
537
538 ++csdIndex;
539 }
540
541 if (csdIndex != 2) {
542 ALOGW("Expected two NAL units from AVC codec config, but %u found",
543 csdIndex);
544 }
545 } else {
546 // For everything else we just stash the codec specific data into
547 // the output format as a single piece of csd under "csd-0".
548 sp<ABuffer> csd = new ABuffer(size);
549 memcpy(csd->data(), data, size);
550 csd->setRange(0, size);
551 outputFormat->setBuffer("csd-0", csd);
552 }
553}
554
Pawin Vongmasa36653902018-11-15 00:10:25 -0800555} // namespace
556
557// CCodec::ClientListener
558
559struct CCodec::ClientListener : public Codec2Client::Listener {
560
561 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
562
563 virtual void onWorkDone(
564 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800565 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800566 (void)component;
567 sp<CCodec> codec(mCodec.promote());
568 if (!codec) {
569 return;
570 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800571 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800572 }
573
574 virtual void onTripped(
575 const std::weak_ptr<Codec2Client::Component>& component,
576 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
577 ) override {
578 // TODO
579 (void)component;
580 (void)settingResult;
581 }
582
583 virtual void onError(
584 const std::weak_ptr<Codec2Client::Component>& component,
585 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800586 {
587 // Component is only used for reporting as we use a separate listener for each instance
588 std::shared_ptr<Codec2Client::Component> comp = component.lock();
589 if (!comp) {
590 ALOGD("Component died with error: 0x%x", errorCode);
591 } else {
592 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
593 }
594 }
595
596 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800597 // Note: for now we do not propagate the error code to MediaCodec
598 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800599 sp<CCodec> codec(mCodec.promote());
600 if (!codec || !codec->mCallback) {
601 return;
602 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800603 codec->mCallback->onError(
604 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
605 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800606 }
607
608 virtual void onDeath(
609 const std::weak_ptr<Codec2Client::Component>& component) override {
610 { // Log the death of the component.
611 std::shared_ptr<Codec2Client::Component> comp = component.lock();
612 if (!comp) {
613 ALOGE("Codec2 component died.");
614 } else {
615 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
616 }
617 }
618
619 // Report to MediaCodec.
620 sp<CCodec> codec(mCodec.promote());
621 if (!codec || !codec->mCallback) {
622 return;
623 }
624 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
625 }
626
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800627 virtual void onFrameRendered(uint64_t bufferQueueId,
628 int32_t slotId,
629 int64_t timestampNs) override {
630 // TODO: implement
631 (void)bufferQueueId;
632 (void)slotId;
633 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800634 }
635
636 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800637 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800638 sp<CCodec> codec(mCodec.promote());
639 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800640 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800641 }
642 }
643
644private:
645 wp<CCodec> mCodec;
646};
647
648// CCodecCallbackImpl
649
650class CCodecCallbackImpl : public CCodecCallback {
651public:
652 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
653 ~CCodecCallbackImpl() override = default;
654
655 void onError(status_t err, enum ActionCode actionCode) override {
656 mCodec->mCallback->onError(err, actionCode);
657 }
658
659 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
660 mCodec->mCallback->onOutputFramesRendered(
661 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
662 }
663
Pawin Vongmasa36653902018-11-15 00:10:25 -0800664 void onOutputBuffersChanged() override {
665 mCodec->mCallback->onOutputBuffersChanged();
666 }
667
668private:
669 CCodec *mCodec;
670};
671
672// CCodec
673
674CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700675 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
676 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800677}
678
679CCodec::~CCodec() {
680}
681
682std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
683 return mChannel;
684}
685
686status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
687 status_t err = job();
688 if (err != C2_OK) {
689 mCallback->onError(err, ACTION_CODE_FATAL);
690 }
691 return err;
692}
693
694void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
695 auto setAllocating = [this] {
696 Mutexed<State>::Locked state(mState);
697 if (state->get() != RELEASED) {
698 return INVALID_OPERATION;
699 }
700 state->set(ALLOCATING);
701 return OK;
702 };
703 if (tryAndReportOnError(setAllocating) != OK) {
704 return;
705 }
706
707 sp<RefBase> codecInfo;
708 CHECK(msg->findObject("codecInfo", &codecInfo));
709 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
710
711 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
712 allocMsg->setObject("codecInfo", codecInfo);
713 allocMsg->post();
714}
715
716void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
717 if (codecInfo == nullptr) {
718 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
719 return;
720 }
721 ALOGD("allocate(%s)", codecInfo->getCodecName());
722 mClientListener.reset(new ClientListener(this));
723
724 AString componentName = codecInfo->getCodecName();
725 std::shared_ptr<Codec2Client> client;
726
727 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700728 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800729 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800730 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800731 SetPreferredCodec2ComponentStore(
732 std::make_shared<Codec2ClientInterfaceWrapper>(client));
733 }
734
735 std::shared_ptr<Codec2Client::Component> comp =
736 Codec2Client::CreateComponentByName(
737 componentName.c_str(),
738 mClientListener,
739 &client);
740 if (!comp) {
741 ALOGE("Failed Create component: %s", componentName.c_str());
742 Mutexed<State>::Locked state(mState);
743 state->set(RELEASED);
744 state.unlock();
745 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
746 state.lock();
747 return;
748 }
749 ALOGI("Created component [%s]", componentName.c_str());
750 mChannel->setComponent(comp);
751 auto setAllocated = [this, comp, client] {
752 Mutexed<State>::Locked state(mState);
753 if (state->get() != ALLOCATING) {
754 state->set(RELEASED);
755 return UNKNOWN_ERROR;
756 }
757 state->set(ALLOCATED);
758 state->comp = comp;
759 mClient = client;
760 return OK;
761 };
762 if (tryAndReportOnError(setAllocated) != OK) {
763 return;
764 }
765
766 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700767 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
768 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800769 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800770 if (err != OK) {
771 ALOGW("Failed to initialize configuration support");
772 // TODO: report error once we complete implementation.
773 }
774 config->queryConfiguration(comp);
775
776 mCallback->onComponentAllocated(componentName.c_str());
777}
778
779void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
780 auto checkAllocated = [this] {
781 Mutexed<State>::Locked state(mState);
782 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
783 };
784 if (tryAndReportOnError(checkAllocated) != OK) {
785 return;
786 }
787
788 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
789 msg->setMessage("format", format);
790 msg->post();
791}
792
793void CCodec::configure(const sp<AMessage> &msg) {
794 std::shared_ptr<Codec2Client::Component> comp;
795 auto checkAllocated = [this, &comp] {
796 Mutexed<State>::Locked state(mState);
797 if (state->get() != ALLOCATED) {
798 state->set(RELEASED);
799 return UNKNOWN_ERROR;
800 }
801 comp = state->comp;
802 return OK;
803 };
804 if (tryAndReportOnError(checkAllocated) != OK) {
805 return;
806 }
807
808 auto doConfig = [msg, comp, this]() -> status_t {
809 AString mime;
810 if (!msg->findString("mime", &mime)) {
811 return BAD_VALUE;
812 }
813
814 int32_t encoder;
815 if (!msg->findInt32("encoder", &encoder)) {
816 encoder = false;
817 }
818
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800819 int32_t flags;
820 if (!msg->findInt32("flags", &flags)) {
821 return BAD_VALUE;
822 }
823
Pawin Vongmasa36653902018-11-15 00:10:25 -0800824 // TODO: read from intf()
825 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
826 return UNKNOWN_ERROR;
827 }
828
829 int32_t storeMeta;
830 if (encoder
831 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
832 && storeMeta != kMetadataBufferTypeInvalid) {
833 if (storeMeta != kMetadataBufferTypeANWBuffer) {
834 ALOGD("Only ANW buffers are supported for legacy metadata mode");
835 return BAD_VALUE;
836 }
837 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
838 }
839
ted.sun765db4d2020-06-23 14:03:41 +0800840 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800841 sp<RefBase> obj;
842 sp<Surface> surface;
843 if (msg->findObject("native-window", &obj)) {
844 surface = static_cast<Surface *>(obj.get());
ted.sun765db4d2020-06-23 14:03:41 +0800845 // setup tunneled playback
846 if (surface != nullptr) {
847 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
848 const std::unique_ptr<Config> &config = *configLocked;
849 if ((config->mDomain & Config::IS_DECODER)
850 && (config->mDomain & Config::IS_VIDEO)) {
851 int32_t tunneled;
852 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
853 ALOGI("Configuring TUNNELED video playback.");
854
855 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
856 if (err != OK) {
857 ALOGE("configureTunneledVideoPlayback failed!");
858 return err;
859 }
860 config->mTunneled = true;
861 }
862 }
863 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800864 setSurface(surface);
865 }
866
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700867 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
868 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800869 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800870 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
871 ALOGD("[%s] buffers are %sbound to CCodec for this session",
872 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800873
Wonsik Kim1114eea2019-02-25 14:35:24 -0800874 // Enforce required parameters
875 int32_t i32;
876 float flt;
877 if (config->mDomain & Config::IS_AUDIO) {
878 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
879 ALOGD("sample rate is missing, which is required for audio components.");
880 return BAD_VALUE;
881 }
882 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
883 ALOGD("channel count is missing, which is required for audio components.");
884 return BAD_VALUE;
885 }
886 if ((config->mDomain & Config::IS_ENCODER)
887 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
888 && !msg->findInt32(KEY_BIT_RATE, &i32)
889 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
890 ALOGD("bitrate is missing, which is required for audio encoders.");
891 return BAD_VALUE;
892 }
893 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800894 int32_t width = 0;
895 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800896 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800897 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800898 ALOGD("width is missing, which is required for image/video components.");
899 return BAD_VALUE;
900 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800901 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800902 ALOGD("height is missing, which is required for image/video components.");
903 return BAD_VALUE;
904 }
905 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700906 int32_t mode = BITRATE_MODE_VBR;
907 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700908 if (!msg->findInt32(KEY_QUALITY, &i32)) {
909 ALOGD("quality is missing, which is required for video encoders in CQ.");
910 return BAD_VALUE;
911 }
912 } else {
913 if (!msg->findInt32(KEY_BIT_RATE, &i32)
914 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
915 ALOGD("bitrate is missing, which is required for video encoders.");
916 return BAD_VALUE;
917 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800918 }
919 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
920 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
921 ALOGD("I frame interval is missing, which is required for video encoders.");
922 return BAD_VALUE;
923 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700924 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
925 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
926 ALOGD("frame rate is missing, which is required for video encoders.");
927 return BAD_VALUE;
928 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800929 }
930 }
931
Pawin Vongmasa36653902018-11-15 00:10:25 -0800932 /*
933 * Handle input surface configuration
934 */
935 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
936 && (config->mDomain & Config::IS_ENCODER)) {
937 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
938 {
939 config->mISConfig->mMinFps = 0;
940 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800941 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800942 config->mISConfig->mMinFps = 1e6 / value;
943 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700944 if (!msg->findFloat(
945 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
946 config->mISConfig->mMaxFps = -1;
947 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800948 config->mISConfig->mMinAdjustedFps = 0;
949 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800950 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800951 if (value < 0 && value >= INT32_MIN) {
952 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700953 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800954 } else if (value > 0 && value <= INT32_MAX) {
955 config->mISConfig->mMinAdjustedFps = 1e6 / value;
956 }
957 }
958 }
959
960 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700961 bool captureFpsFound = false;
962 double timeLapseFps;
963 float captureRate;
964 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
965 config->mISConfig->mCaptureFps = timeLapseFps;
966 captureFpsFound = true;
967 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
968 config->mISConfig->mCaptureFps = captureRate;
969 captureFpsFound = true;
970 }
971 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800972 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
973 }
974 }
975
976 {
977 config->mISConfig->mSuspended = false;
978 config->mISConfig->mSuspendAtUs = -1;
979 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800980 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800981 config->mISConfig->mSuspended = true;
982 }
983 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700984 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800985 }
986
987 /*
988 * Handle desired color format.
989 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700990 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800991 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700992 int32_t format = 0;
993 // Query vendor format for Flexible YUV
994 std::vector<std::unique_ptr<C2Param>> heapParams;
995 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
996 if (mClient->query(
997 {},
998 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
999 C2_MAY_BLOCK,
1000 &heapParams) == C2_OK
1001 && heapParams.size() == 1u) {
1002 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1003 heapParams[0].get());
1004 } else {
1005 pixelFormatInfo = nullptr;
1006 }
1007 std::optional<uint32_t> flexPixelFormat{};
1008 std::optional<uint32_t> flexPlanarPixelFormat{};
1009 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
1010 if (pixelFormatInfo && *pixelFormatInfo) {
1011 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1012 const C2FlexiblePixelFormatDescriptorStruct &desc =
1013 pixelFormatInfo->m.values[i];
1014 if (desc.bitDepth != 8
1015 || desc.subsampling != C2Color::YUV_420
1016 // TODO(b/180076105): some device report wrong layout
1017 // || desc.layout == C2Color::INTERLEAVED_PACKED
1018 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1019 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1020 continue;
1021 }
1022 if (!flexPixelFormat) {
1023 flexPixelFormat = desc.pixelFormat;
1024 }
1025 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
1026 flexPlanarPixelFormat = desc.pixelFormat;
1027 }
1028 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
1029 flexSemiPlanarPixelFormat = desc.pixelFormat;
1030 }
1031 }
1032 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001033 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001034 // Also handle default color format (encoders require color format, so this is only
1035 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001036 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001037 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001038 const char *prefix = "";
1039 if (flexSemiPlanarPixelFormat) {
1040 format = COLOR_FormatYUV420SemiPlanar;
1041 prefix = "semi-";
1042 } else {
1043 format = COLOR_FormatYUV420Planar;
1044 }
1045 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1046 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001047 } else {
1048 format = COLOR_FormatSurface;
1049 }
1050 defaultColorFormat = format;
1051 }
1052 } else {
1053 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
1054 switch (format) {
1055 case COLOR_FormatYUV420Flexible:
1056 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
1057 break;
1058 case COLOR_FormatYUV420Planar:
1059 case COLOR_FormatYUV420PackedPlanar:
1060 format = flexPlanarPixelFormat.value_or(
1061 flexPixelFormat.value_or(format));
1062 break;
1063 case COLOR_FormatYUV420SemiPlanar:
1064 case COLOR_FormatYUV420PackedSemiPlanar:
1065 format = flexSemiPlanarPixelFormat.value_or(
1066 flexPixelFormat.value_or(format));
1067 break;
1068 default:
1069 // No-op
1070 break;
1071 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001072 }
1073 }
1074
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001075 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001076 msg->setInt32("android._color-format", format);
1077 }
1078 }
1079
Wonsik Kim77e97c72021-01-20 10:33:22 -08001080 /*
1081 * Handle dataspace
1082 */
1083 int32_t usingRecorder;
1084 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1085 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1086 int32_t width, height;
1087 if (msg->findInt32("width", &width)
1088 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001089 ColorAspects aspects;
1090 getColorAspectsFromFormat(msg, aspects);
1091 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001092 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001093 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1094 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001095 }
1096 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1097 ALOGD("setting dataspace to %x", dataSpace);
1098 }
1099
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001100 int32_t subscribeToAllVendorParams;
1101 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1102 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1103 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1104 }
1105 }
1106
Pawin Vongmasa36653902018-11-15 00:10:25 -08001107 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001108 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1109 // the behavior here.
1110 sp<AMessage> sdkParams = msg;
1111 int32_t videoBitrate;
1112 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1113 sdkParams = msg->dup();
1114 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1115 }
ted.sun765db4d2020-06-23 14:03:41 +08001116 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001117 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001118 if (err != OK) {
1119 ALOGW("failed to convert configuration to c2 params");
1120 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001121
1122 int32_t maxBframes = 0;
1123 if ((config->mDomain & Config::IS_ENCODER)
1124 && (config->mDomain & Config::IS_VIDEO)
1125 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1126 && maxBframes > 0) {
1127 std::unique_ptr<C2StreamGopTuning::output> gop =
1128 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1129 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1130 gop->m.values[1] = {
1131 C2Config::picture_type_t(P_FRAME | B_FRAME),
1132 uint32_t(maxBframes)
1133 };
1134 configUpdate.push_back(std::move(gop));
1135 }
1136
Ray Essicka9a724a2021-03-10 19:40:01 -08001137 if ((config->mDomain & Config::IS_ENCODER)
1138 && (config->mDomain & Config::IS_VIDEO)) {
1139 // we may not use all 3 of these entries
1140 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1141 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1142 0u /* stream */);
1143
1144 int ix = 0;
1145
1146 int32_t iMax = INT32_MAX;
1147 int32_t iMin = INT32_MIN;
1148 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1149 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1150 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1151 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1152 }
1153
1154 int32_t pMax = INT32_MAX;
1155 int32_t pMin = INT32_MIN;
1156 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1157 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1158 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1159 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1160 }
1161
1162 int32_t bMax = INT32_MAX;
1163 int32_t bMin = INT32_MIN;
1164 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1165 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1166 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1167 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1168 }
1169
1170 // adjust to reflect actual use.
1171 qp->setFlexCount(ix);
1172
1173 configUpdate.push_back(std::move(qp));
1174 }
1175
Pawin Vongmasa36653902018-11-15 00:10:25 -08001176 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1177 if (err != OK) {
1178 ALOGW("failed to configure c2 params");
1179 return err;
1180 }
1181
1182 std::vector<std::unique_ptr<C2Param>> params;
1183 C2StreamUsageTuning::input usage(0u, 0u);
1184 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001185 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001186
Wonsik Kim58d83332021-02-07 22:19:56 -08001187 C2Param::Index colorAspectsRequestIndex =
1188 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001189 std::initializer_list<C2Param::Index> indices {
Wonsik Kim58d83332021-02-07 22:19:56 -08001190 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001191 };
1192 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001193 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001194 indices,
1195 C2_DONT_BLOCK,
1196 &params);
1197 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1198 ALOGE("Failed to query component interface: %d", c2err);
1199 return UNKNOWN_ERROR;
1200 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001201 if (usage) {
1202 if (usage.value & C2MemoryUsage::CPU_READ) {
1203 config->mInputFormat->setInt32("using-sw-read-often", true);
1204 }
1205 if (config->mISConfig) {
1206 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1207 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1208 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001209 }
1210
1211 // NOTE: we don't blindly use client specified input size if specified as clients
1212 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1213 // client specified size is only used to ask for bigger buffers than component suggested
1214 // size.
1215 int32_t clientInputSize = 0;
1216 bool clientSpecifiedInputSize =
1217 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1218 // TEMP: enforce minimum buffer size of 1MB for video decoders
1219 // and 16K / 4K for audio encoders/decoders
1220 if (maxInputSize.value == 0) {
1221 if (config->mDomain & Config::IS_AUDIO) {
1222 maxInputSize.value = encoder ? 16384 : 4096;
1223 } else if (!encoder) {
1224 maxInputSize.value = 1048576u;
1225 }
1226 }
1227
1228 // verify that CSD fits into this size (if defined)
1229 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1230 sp<ABuffer> csd;
1231 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1232 if (csd && csd->size() > maxInputSize.value) {
1233 maxInputSize.value = csd->size();
1234 }
1235 }
1236 }
1237
1238 // TODO: do this based on component requiring linear allocator for input
1239 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1240 if (clientSpecifiedInputSize) {
1241 // Warn that we're overriding client's max input size if necessary.
1242 if ((uint32_t)clientInputSize < maxInputSize.value) {
1243 ALOGD("client requested max input size %d, which is smaller than "
1244 "what component recommended (%u); overriding with component "
1245 "recommendation.", clientInputSize, maxInputSize.value);
1246 ALOGW("This behavior is subject to change. It is recommended that "
1247 "app developers double check whether the requested "
1248 "max input size is in reasonable range.");
1249 } else {
1250 maxInputSize.value = clientInputSize;
1251 }
1252 }
1253 // Pass max input size on input format to the buffer channel (if supplied by the
1254 // component or by a default)
1255 if (maxInputSize.value) {
1256 config->mInputFormat->setInt32(
1257 KEY_MAX_INPUT_SIZE,
1258 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1259 }
1260 }
1261
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001262 int32_t clientPrepend;
1263 if ((config->mDomain & Config::IS_VIDEO)
1264 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001265 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001266 && clientPrepend
1267 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001268 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001269 return BAD_VALUE;
1270 }
1271
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001272 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001273 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1274 // propagate HDR static info to output format for both encoders and decoders
1275 // if component supports this info, we will update from component, but only the raw port,
1276 // so don't propagate if component already filled it in.
1277 sp<ABuffer> hdrInfo;
1278 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1279 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1280 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1281 }
1282
1283 // Set desired color format from configuration parameter
1284 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001285 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1286 format = defaultColorFormat;
1287 }
1288 if (config->mDomain & Config::IS_ENCODER) {
1289 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001290 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1291 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001292 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001293 } else {
1294 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001295 }
1296 }
1297
1298 // propagate encoder delay and padding to output format
1299 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1300 int delay = 0;
1301 if (msg->findInt32("encoder-delay", &delay)) {
1302 config->mOutputFormat->setInt32("encoder-delay", delay);
1303 }
1304 int padding = 0;
1305 if (msg->findInt32("encoder-padding", &padding)) {
1306 config->mOutputFormat->setInt32("encoder-padding", padding);
1307 }
1308 }
1309
1310 // set channel-mask
1311 if (config->mDomain & Config::IS_AUDIO) {
1312 int32_t mask;
1313 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1314 if (config->mDomain & Config::IS_ENCODER) {
1315 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1316 } else {
1317 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1318 }
1319 }
1320 }
1321
Wonsik Kim58d83332021-02-07 22:19:56 -08001322 std::unique_ptr<C2Param> colorTransferRequestParam;
1323 for (std::unique_ptr<C2Param> &param : params) {
1324 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1325 ALOGI("found color transfer request param");
1326 colorTransferRequestParam = std::move(param);
1327 }
1328 }
1329 int32_t colorTransferRequest = 0;
1330 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1331 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1332 colorTransferRequest = 0;
1333 }
1334
1335 if (colorTransferRequest != 0) {
1336 if (colorTransferRequestParam && *colorTransferRequestParam) {
1337 C2StreamColorAspectsInfo::output *info =
1338 static_cast<C2StreamColorAspectsInfo::output *>(
1339 colorTransferRequestParam.get());
1340 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1341 colorTransferRequest = 0;
1342 }
1343 } else {
1344 colorTransferRequest = 0;
1345 }
1346 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1347 }
1348
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001349 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1350 // Need to get stride/vstride
1351 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1352 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1353 // TODO: retrieve these values without allocating a buffer.
1354 // Currently allocating a buffer is necessary to retrieve the layout.
1355 int64_t blockUsage =
1356 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1357 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1358 width, height, pixelFormat, blockUsage, {comp->getName()});
1359 sp<GraphicBlockBuffer> buffer;
1360 if (block) {
1361 buffer = GraphicBlockBuffer::Allocate(
1362 config->mInputFormat,
1363 block,
1364 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1365 } else {
1366 ALOGD("Failed to allocate a graphic block "
1367 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1368 width, height, pixelFormat, (long long)blockUsage);
1369 // This means that byte buffer mode is not supported in this configuration
1370 // anyway. Skip setting stride/vstride to input format.
1371 }
1372 if (buffer) {
1373 sp<ABuffer> imageData = buffer->getImageData();
1374 MediaImage2 *img = nullptr;
1375 if (imageData && imageData->data()
1376 && imageData->size() >= sizeof(MediaImage2)) {
1377 img = (MediaImage2*)imageData->data();
1378 }
1379 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1380 int32_t stride = img->mPlane[0].mRowInc;
1381 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1382 if (img->mNumPlanes > 1 && stride > 0) {
1383 int64_t offsetDelta =
1384 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1385 if (offsetDelta % stride == 0) {
1386 int32_t vstride = int32_t(offsetDelta / stride);
1387 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1388 } else {
1389 ALOGD("Cannot report accurate slice height: "
1390 "offsetDelta = %lld stride = %d",
1391 (long long)offsetDelta, stride);
1392 }
1393 }
1394 }
1395 }
1396 }
1397 }
1398
1399 ALOGD("setup formats input: %s",
1400 config->mInputFormat->debugString().c_str());
1401 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001402 config->mOutputFormat->debugString().c_str());
1403 return OK;
1404 };
1405 if (tryAndReportOnError(doConfig) != OK) {
1406 return;
1407 }
1408
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001409 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1410 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001411
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001412 config->queryConfiguration(comp);
1413
Pawin Vongmasa36653902018-11-15 00:10:25 -08001414 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1415}
1416
1417void CCodec::initiateCreateInputSurface() {
1418 status_t err = [this] {
1419 Mutexed<State>::Locked state(mState);
1420 if (state->get() != ALLOCATED) {
1421 return UNKNOWN_ERROR;
1422 }
1423 // TODO: read it from intf() properly.
1424 if (state->comp->getName().find("encoder") == std::string::npos) {
1425 return INVALID_OPERATION;
1426 }
1427 return OK;
1428 }();
1429 if (err != OK) {
1430 mCallback->onInputSurfaceCreationFailed(err);
1431 return;
1432 }
1433
1434 (new AMessage(kWhatCreateInputSurface, this))->post();
1435}
1436
Lajos Molnar47118272019-01-31 16:28:04 -08001437sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1438 using namespace android::hardware::media::omx::V1_0;
1439 using namespace android::hardware::media::omx::V1_0::utils;
1440 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1441 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1442 android::sp<IOmx> omx = IOmx::getService();
1443 typedef android::hardware::graphics::bufferqueue::V1_0::
1444 IGraphicBufferProducer HGraphicBufferProducer;
1445 typedef android::hardware::media::omx::V1_0::
1446 IGraphicBufferSource HGraphicBufferSource;
1447 OmxStatus s;
1448 android::sp<HGraphicBufferProducer> gbp;
1449 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001450
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001451 using ::android::hardware::Return;
1452 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001453 [&s, &gbp, &gbs](
1454 OmxStatus status,
1455 const android::sp<HGraphicBufferProducer>& producer,
1456 const android::sp<HGraphicBufferSource>& source) {
1457 s = status;
1458 gbp = producer;
1459 gbs = source;
1460 });
1461 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001462 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001463 }
1464
1465 return nullptr;
1466}
1467
1468sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1469 sp<PersistentSurface> surface(CreateInputSurface());
1470
1471 if (surface == nullptr) {
1472 surface = CreateOmxInputSurface();
1473 }
1474
1475 return surface;
1476}
1477
Pawin Vongmasa36653902018-11-15 00:10:25 -08001478void CCodec::createInputSurface() {
1479 status_t err;
1480 sp<IGraphicBufferProducer> bufferProducer;
1481
Pawin Vongmasa36653902018-11-15 00:10:25 -08001482 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001483 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001484 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001485 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1486 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001487 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001488 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001489 }
1490
Lajos Molnar47118272019-01-31 16:28:04 -08001491 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001492 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1493 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1494 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001495
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001496 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001497 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1498 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001499 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001500 inputSurface));
1501 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001502 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001503 int32_t width = 0;
1504 (void)outputFormat->findInt32("width", &width);
1505 int32_t height = 0;
1506 (void)outputFormat->findInt32("height", &height);
1507 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001508 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001509 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001510 } else {
1511 ALOGE("Corrupted input surface");
1512 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1513 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001514 }
1515
1516 if (err != OK) {
1517 ALOGE("Failed to set up input surface: %d", err);
1518 mCallback->onInputSurfaceCreationFailed(err);
1519 return;
1520 }
1521
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001522 // Formats can change after setupInputSurface
1523 sp<AMessage> inputFormat;
1524 {
1525 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1526 const std::unique_ptr<Config> &config = *configLocked;
1527 inputFormat = config->mInputFormat;
1528 outputFormat = config->mOutputFormat;
1529 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001530 mCallback->onInputSurfaceCreated(
1531 inputFormat,
1532 outputFormat,
1533 new BufferProducerWrapper(bufferProducer));
1534}
1535
1536status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001537 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1538 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001539 config->mUsingSurface = true;
1540
1541 // we are now using surface - apply default color aspects to input format - as well as
1542 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001543 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001544 ALOGD("input format %s to %s",
1545 inputFormatChanged ? "changed" : "unchanged",
1546 config->mInputFormat->debugString().c_str());
1547
1548 // configure dataspace
1549 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1550 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1551 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1552 surface->setDataSpace(dataSpace);
1553
1554 status_t err = mChannel->setInputSurface(surface);
1555 if (err != OK) {
1556 // undo input format update
1557 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001558 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001559 return err;
1560 }
1561 config->mInputSurface = surface;
1562
1563 if (config->mISConfig) {
1564 surface->configure(*config->mISConfig);
1565 } else {
1566 ALOGD("ISConfig: no configuration");
1567 }
1568
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001569 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001570}
1571
1572void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1573 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1574 msg->setObject("surface", surface);
1575 msg->post();
1576}
1577
1578void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001579 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001580 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001581 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001582 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1583 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001584 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001585 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001586 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001587 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1588 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1589 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1590 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001591 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1592 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1593 if (err != OK) {
1594 ALOGE("Failed to set up input surface: %d", err);
1595 mCallback->onInputSurfaceDeclined(err);
1596 return;
1597 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001598 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001599 int32_t width = 0;
1600 (void)outputFormat->findInt32("width", &width);
1601 int32_t height = 0;
1602 (void)outputFormat->findInt32("height", &height);
1603 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001604 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001605 if (err != OK) {
1606 ALOGE("Failed to set up input surface: %d", err);
1607 mCallback->onInputSurfaceDeclined(err);
1608 return;
1609 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001610 } else {
1611 ALOGE("Failed to set input surface: Corrupted surface.");
1612 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1613 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001614 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001615 // Formats can change after setupInputSurface
1616 sp<AMessage> inputFormat;
1617 {
1618 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1619 const std::unique_ptr<Config> &config = *configLocked;
1620 inputFormat = config->mInputFormat;
1621 outputFormat = config->mOutputFormat;
1622 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001623 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1624}
1625
1626void CCodec::initiateStart() {
1627 auto setStarting = [this] {
1628 Mutexed<State>::Locked state(mState);
1629 if (state->get() != ALLOCATED) {
1630 return UNKNOWN_ERROR;
1631 }
1632 state->set(STARTING);
1633 return OK;
1634 };
1635 if (tryAndReportOnError(setStarting) != OK) {
1636 return;
1637 }
1638
1639 (new AMessage(kWhatStart, this))->post();
1640}
1641
1642void CCodec::start() {
1643 std::shared_ptr<Codec2Client::Component> comp;
1644 auto checkStarting = [this, &comp] {
1645 Mutexed<State>::Locked state(mState);
1646 if (state->get() != STARTING) {
1647 return UNKNOWN_ERROR;
1648 }
1649 comp = state->comp;
1650 return OK;
1651 };
1652 if (tryAndReportOnError(checkStarting) != OK) {
1653 return;
1654 }
1655
1656 c2_status_t err = comp->start();
1657 if (err != C2_OK) {
1658 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1659 ACTION_CODE_FATAL);
1660 return;
1661 }
1662 sp<AMessage> inputFormat;
1663 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001664 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001665 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001666 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001667 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1668 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001669 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001670 // start triggers format dup
1671 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001672 if (config->mInputSurface) {
1673 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001674 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001675 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001676 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001677 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001678 if (err2 != OK) {
1679 mCallback->onError(err2, ACTION_CODE_FATAL);
1680 return;
1681 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001682 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001683 if (err2 != OK) {
1684 mCallback->onError(err2, ACTION_CODE_FATAL);
1685 return;
1686 }
1687
1688 auto setRunning = [this] {
1689 Mutexed<State>::Locked state(mState);
1690 if (state->get() != STARTING) {
1691 return UNKNOWN_ERROR;
1692 }
1693 state->set(RUNNING);
1694 return OK;
1695 };
1696 if (tryAndReportOnError(setRunning) != OK) {
1697 return;
1698 }
1699 mCallback->onStartCompleted();
1700
1701 (void)mChannel->requestInitialInputBuffers();
1702}
1703
1704void CCodec::initiateShutdown(bool keepComponentAllocated) {
1705 if (keepComponentAllocated) {
1706 initiateStop();
1707 } else {
1708 initiateRelease();
1709 }
1710}
1711
1712void CCodec::initiateStop() {
1713 {
1714 Mutexed<State>::Locked state(mState);
1715 if (state->get() == ALLOCATED
1716 || state->get() == RELEASED
1717 || state->get() == STOPPING
1718 || state->get() == RELEASING) {
1719 // We're already stopped, released, or doing it right now.
1720 state.unlock();
1721 mCallback->onStopCompleted();
1722 state.lock();
1723 return;
1724 }
1725 state->set(STOPPING);
1726 }
1727
Wonsik Kim936a89c2020-05-08 16:07:50 -07001728 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001729 (new AMessage(kWhatStop, this))->post();
1730}
1731
1732void CCodec::stop() {
1733 std::shared_ptr<Codec2Client::Component> comp;
1734 {
1735 Mutexed<State>::Locked state(mState);
1736 if (state->get() == RELEASING) {
1737 state.unlock();
1738 // We're already stopped or release is in progress.
1739 mCallback->onStopCompleted();
1740 state.lock();
1741 return;
1742 } else if (state->get() != STOPPING) {
1743 state.unlock();
1744 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1745 state.lock();
1746 return;
1747 }
1748 comp = state->comp;
1749 }
1750 status_t err = comp->stop();
1751 if (err != C2_OK) {
1752 // TODO: convert err into status_t
1753 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1754 }
1755
1756 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001757 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1758 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001759 if (config->mInputSurface) {
1760 config->mInputSurface->disconnect();
1761 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001762 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001763 }
1764 }
1765 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001766 Mutexed<State>::Locked state(mState);
1767 if (state->get() == STOPPING) {
1768 state->set(ALLOCATED);
1769 }
1770 }
1771 mCallback->onStopCompleted();
1772}
1773
1774void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001775 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001776 {
1777 Mutexed<State>::Locked state(mState);
1778 if (state->get() == RELEASED || state->get() == RELEASING) {
1779 // We're already released or doing it right now.
1780 if (sendCallback) {
1781 state.unlock();
1782 mCallback->onReleaseCompleted();
1783 state.lock();
1784 }
1785 return;
1786 }
1787 if (state->get() == ALLOCATING) {
1788 state->set(RELEASING);
1789 // With the altered state allocate() would fail and clean up.
1790 if (sendCallback) {
1791 state.unlock();
1792 mCallback->onReleaseCompleted();
1793 state.lock();
1794 }
1795 return;
1796 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001797 if (state->get() == STARTING
1798 || state->get() == RUNNING
1799 || state->get() == STOPPING) {
1800 // Input surface may have been started, so clean up is needed.
1801 clearInputSurfaceIfNeeded = true;
1802 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001803 state->set(RELEASING);
1804 }
1805
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001806 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001807 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1808 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001809 if (config->mInputSurface) {
1810 config->mInputSurface->disconnect();
1811 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001812 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001813 }
1814 }
1815
Wonsik Kim936a89c2020-05-08 16:07:50 -07001816 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001817 // thiz holds strong ref to this while the thread is running.
1818 sp<CCodec> thiz(this);
1819 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1820}
1821
1822void CCodec::release(bool sendCallback) {
1823 std::shared_ptr<Codec2Client::Component> comp;
1824 {
1825 Mutexed<State>::Locked state(mState);
1826 if (state->get() == RELEASED) {
1827 if (sendCallback) {
1828 state.unlock();
1829 mCallback->onReleaseCompleted();
1830 state.lock();
1831 }
1832 return;
1833 }
1834 comp = state->comp;
1835 }
1836 comp->release();
1837
1838 {
1839 Mutexed<State>::Locked state(mState);
1840 state->set(RELEASED);
1841 state->comp.reset();
1842 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001843 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001844 if (sendCallback) {
1845 mCallback->onReleaseCompleted();
1846 }
1847}
1848
1849status_t CCodec::setSurface(const sp<Surface> &surface) {
Wonsik Kim75e22f42021-04-14 23:34:51 -07001850 {
1851 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1852 const std::unique_ptr<Config> &config = *configLocked;
1853 if (config->mTunneled && config->mSidebandHandle != nullptr) {
1854 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
1855 status_t err = native_window_set_sideband_stream(
1856 nativeWindow.get(),
1857 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
1858 if (err != OK) {
1859 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
1860 nativeWindow.get(), config->mSidebandHandle->handle(), err);
1861 return err;
1862 }
ted.sun765db4d2020-06-23 14:03:41 +08001863 }
1864 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001865 return mChannel->setSurface(surface);
1866}
1867
1868void CCodec::signalFlush() {
1869 status_t err = [this] {
1870 Mutexed<State>::Locked state(mState);
1871 if (state->get() == FLUSHED) {
1872 return ALREADY_EXISTS;
1873 }
1874 if (state->get() != RUNNING) {
1875 return UNKNOWN_ERROR;
1876 }
1877 state->set(FLUSHING);
1878 return OK;
1879 }();
1880 switch (err) {
1881 case ALREADY_EXISTS:
1882 mCallback->onFlushCompleted();
1883 return;
1884 case OK:
1885 break;
1886 default:
1887 mCallback->onError(err, ACTION_CODE_FATAL);
1888 return;
1889 }
1890
1891 mChannel->stop();
1892 (new AMessage(kWhatFlush, this))->post();
1893}
1894
1895void CCodec::flush() {
1896 std::shared_ptr<Codec2Client::Component> comp;
1897 auto checkFlushing = [this, &comp] {
1898 Mutexed<State>::Locked state(mState);
1899 if (state->get() != FLUSHING) {
1900 return UNKNOWN_ERROR;
1901 }
1902 comp = state->comp;
1903 return OK;
1904 };
1905 if (tryAndReportOnError(checkFlushing) != OK) {
1906 return;
1907 }
1908
1909 std::list<std::unique_ptr<C2Work>> flushedWork;
1910 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1911 {
1912 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1913 flushedWork.splice(flushedWork.end(), *queue);
1914 }
1915 if (err != C2_OK) {
1916 // TODO: convert err into status_t
1917 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1918 }
1919
1920 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001921
1922 {
1923 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001924 if (state->get() == FLUSHING) {
1925 state->set(FLUSHED);
1926 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001927 }
1928 mCallback->onFlushCompleted();
1929}
1930
1931void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001932 std::shared_ptr<Codec2Client::Component> comp;
1933 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001934 Mutexed<State>::Locked state(mState);
1935 if (state->get() != FLUSHED) {
1936 return UNKNOWN_ERROR;
1937 }
1938 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001939 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001940 return OK;
1941 };
1942 if (tryAndReportOnError(setResuming) != OK) {
1943 return;
1944 }
1945
Wonsik Kime75a5da2020-02-14 17:29:03 -08001946 {
1947 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1948 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001949 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001950 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001951 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001952 }
1953
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001954 (void)mChannel->start(nullptr, nullptr, [&]{
1955 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1956 const std::unique_ptr<Config> &config = *configLocked;
1957 return config->mBuffersBoundToCodec;
1958 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001959
1960 {
1961 Mutexed<State>::Locked state(mState);
1962 if (state->get() != RESUMING) {
1963 state.unlock();
1964 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1965 state.lock();
1966 return;
1967 }
1968 state->set(RUNNING);
1969 }
1970
1971 (void)mChannel->requestInitialInputBuffers();
1972}
1973
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001974void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001975 std::shared_ptr<Codec2Client::Component> comp;
1976 auto checkState = [this, &comp] {
1977 Mutexed<State>::Locked state(mState);
1978 if (state->get() == RELEASED) {
1979 return INVALID_OPERATION;
1980 }
1981 comp = state->comp;
1982 return OK;
1983 };
1984 if (tryAndReportOnError(checkState) != OK) {
1985 return;
1986 }
1987
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001988 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1989 // the behavior here.
1990 sp<AMessage> params = msg;
1991 int32_t bitrate;
1992 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1993 params = msg->dup();
1994 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1995 }
1996
Houxiang Dai5a97b472021-03-22 17:56:04 +08001997 int32_t syncId = 0;
1998 if (params->findInt32("audio-hw-sync", &syncId)
1999 || params->findInt32("hw-av-sync-id", &syncId)) {
2000 configureTunneledVideoPlayback(comp, nullptr, params);
2001 }
2002
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002003 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2004 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002005
2006 /**
2007 * Handle input surface parameters
2008 */
2009 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002010 && (config->mDomain & Config::IS_ENCODER)
2011 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002012 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002013
2014 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2015 config->mISConfig->mStopped = false;
2016 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2017 config->mISConfig->mStopped = true;
2018 }
2019
2020 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002021 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002022 config->mISConfig->mSuspended = value;
2023 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002024 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002025 }
2026
2027 (void)config->mInputSurface->configure(*config->mISConfig);
2028 if (config->mISConfig->mStopped) {
2029 config->mInputFormat->setInt64(
2030 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2031 }
2032 }
2033
2034 std::vector<std::unique_ptr<C2Param>> configUpdate;
2035 (void)config->getConfigUpdateFromSdkParams(
2036 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2037 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2038 // Parameter synchronization is not defined when using input surface. For now, route
2039 // these directly to the component.
2040 if (config->mInputSurface == nullptr
2041 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2042 || comp->getName().find("c2.android.") == 0)) {
2043 mChannel->setParameters(configUpdate);
2044 } else {
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002045 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002046 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002047 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002048 }
2049}
2050
2051void CCodec::signalEndOfInputStream() {
2052 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2053}
2054
2055void CCodec::signalRequestIDRFrame() {
2056 std::shared_ptr<Codec2Client::Component> comp;
2057 {
2058 Mutexed<State>::Locked state(mState);
2059 if (state->get() == RELEASED) {
2060 ALOGD("no IDR request sent since component is released");
2061 return;
2062 }
2063 comp = state->comp;
2064 }
2065 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002066 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2067 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002068 std::vector<std::unique_ptr<C2Param>> params;
2069 params.push_back(
2070 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2071 config->setParameters(comp, params, C2_MAY_BLOCK);
2072}
2073
Wonsik Kim874ad382021-03-12 09:59:36 -08002074status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2075 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2076 const std::unique_ptr<Config> &config = *configLocked;
2077 return config->querySupportedParameters(names);
2078}
2079
2080status_t CCodec::describeParameter(
2081 const std::string &name, CodecParameterDescriptor *desc) {
2082 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2083 const std::unique_ptr<Config> &config = *configLocked;
2084 return config->describe(name, desc);
2085}
2086
2087status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2088 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2089 if (!comp) {
2090 return INVALID_OPERATION;
2091 }
2092 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2093 const std::unique_ptr<Config> &config = *configLocked;
2094 return config->subscribeToVendorConfigUpdate(comp, names);
2095}
2096
2097status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2098 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2099 if (!comp) {
2100 return INVALID_OPERATION;
2101 }
2102 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2103 const std::unique_ptr<Config> &config = *configLocked;
2104 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2105}
2106
Wonsik Kimab34ed62019-01-31 15:28:46 -08002107void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002108 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002109 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2110 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002111 }
2112 (new AMessage(kWhatWorkDone, this))->post();
2113}
2114
Wonsik Kimab34ed62019-01-31 15:28:46 -08002115void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2116 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002117 if (arrayIndex == 0) {
2118 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002119 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2120 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002121 if (config->mInputSurface) {
2122 config->mInputSurface->onInputBufferDone(frameIndex);
2123 }
2124 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002125}
2126
2127void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2128 TimePoint now = std::chrono::steady_clock::now();
2129 CCodecWatchdog::getInstance()->watch(this);
2130 switch (msg->what()) {
2131 case kWhatAllocate: {
2132 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002133 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002134 sp<RefBase> obj;
2135 CHECK(msg->findObject("codecInfo", &obj));
2136 allocate((MediaCodecInfo *)obj.get());
2137 break;
2138 }
2139 case kWhatConfigure: {
2140 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002141 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002142 sp<AMessage> format;
2143 CHECK(msg->findMessage("format", &format));
2144 configure(format);
2145 break;
2146 }
2147 case kWhatStart: {
2148 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002149 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002150 start();
2151 break;
2152 }
2153 case kWhatStop: {
2154 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002155 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002156 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002157 break;
2158 }
2159 case kWhatFlush: {
2160 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002161 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002162 flush();
2163 break;
2164 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002165 case kWhatRelease: {
2166 mChannel->release();
2167 mClient.reset();
2168 mClientListener.reset();
2169 break;
2170 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002171 case kWhatCreateInputSurface: {
2172 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002173 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002174 createInputSurface();
2175 break;
2176 }
2177 case kWhatSetInputSurface: {
2178 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002179 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002180 sp<RefBase> obj;
2181 CHECK(msg->findObject("surface", &obj));
2182 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2183 setInputSurface(surface);
2184 break;
2185 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002186 case kWhatWorkDone: {
2187 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002188 bool shouldPost = false;
2189 {
2190 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2191 if (queue->empty()) {
2192 break;
2193 }
2194 work.swap(queue->front());
2195 queue->pop_front();
2196 shouldPost = !queue->empty();
2197 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002198 if (shouldPost) {
2199 (new AMessage(kWhatWorkDone, this))->post();
2200 }
2201
Pawin Vongmasa36653902018-11-15 00:10:25 -08002202 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002203 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002204 sp<AMessage> outputFormat = nullptr;
2205 {
2206 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2207 const std::unique_ptr<Config> &config = *configLocked;
2208 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2209 config->watch<C2StreamInitDataInfo::output>();
2210 if (!work->worklets.empty()
2211 && (work->worklets.front()->output.flags
2212 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002213
Wonsik Kim75e22f42021-04-14 23:34:51 -07002214 // copy buffer info to config
2215 std::vector<std::unique_ptr<C2Param>> updates;
2216 for (const std::unique_ptr<C2Param> &param
2217 : work->worklets.front()->output.configUpdate) {
2218 updates.push_back(C2Param::Copy(*param));
2219 }
2220 unsigned stream = 0;
2221 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2222 work->worklets.front()->output.buffers;
2223 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2224 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2225 // move all info into output-stream #0 domain
2226 updates.emplace_back(
2227 C2Param::CopyAsStream(*info, true /* output */, stream));
2228 }
2229
2230 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2231 // for now only do the first block
2232 if (!blocks.empty()) {
2233 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2234 // block.crop().left, block.crop().top,
2235 // block.crop().width, block.crop().height,
2236 // block.width(), block.height());
2237 const C2ConstGraphicBlock &block = blocks[0];
2238 updates.emplace_back(new C2StreamCropRectInfo::output(
2239 stream, block.crop()));
2240 updates.emplace_back(new C2StreamPictureSizeInfo::output(
2241 stream, block.crop().width, block.crop().height));
2242 }
2243 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002244 }
George Burgess IVc813a592020-02-22 22:54:44 -08002245
Wonsik Kim75e22f42021-04-14 23:34:51 -07002246 sp<AMessage> oldFormat = config->mOutputFormat;
2247 config->updateConfiguration(updates, config->mOutputDomain);
2248 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002249
Wonsik Kim75e22f42021-04-14 23:34:51 -07002250 // copy standard infos to graphic buffers if not already present (otherwise, we
2251 // may overwrite the actual intermediate value with a final value)
2252 stream = 0;
2253 const static C2Param::Index stdGfxInfos[] = {
2254 C2StreamRotationInfo::output::PARAM_TYPE,
2255 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2256 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2257 C2StreamHdrStaticInfo::output::PARAM_TYPE,
2258 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
2259 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2260 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2261 };
2262 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2263 if (buf->data().graphicBlocks().size()) {
2264 for (C2Param::Index ix : stdGfxInfos) {
2265 if (!buf->hasInfo(ix)) {
2266 const C2Param *param =
2267 config->getConfigParameterValue(ix.withStream(stream));
2268 if (param) {
2269 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2270 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2271 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002272 }
2273 }
2274 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002275 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002276 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002277 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002278 if (config->mInputSurface) {
2279 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2280 }
2281 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002282 initData = initDataWatcher.update();
2283 AmendOutputFormatWithCodecSpecificData(
2284 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2285 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002286 }
2287 outputFormat = config->mOutputFormat;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002288 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002289 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002290 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002291 break;
2292 }
2293 case kWhatWatch: {
2294 // watch message already posted; no-op.
2295 break;
2296 }
2297 default: {
2298 ALOGE("unrecognized message");
2299 break;
2300 }
2301 }
2302 setDeadline(TimePoint::max(), 0ms, "none");
2303}
2304
2305void CCodec::setDeadline(
2306 const TimePoint &now,
2307 const std::chrono::milliseconds &timeout,
2308 const char *name) {
2309 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2310 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2311 deadline->set(now + (timeout * mult), name);
2312}
2313
ted.sun765db4d2020-06-23 14:03:41 +08002314status_t CCodec::configureTunneledVideoPlayback(
2315 std::shared_ptr<Codec2Client::Component> comp,
2316 sp<NativeHandle> *sidebandHandle,
2317 const sp<AMessage> &msg) {
2318 std::vector<std::unique_ptr<C2SettingResult>> failures;
2319
2320 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2321 C2PortTunneledModeTuning::output::AllocUnique(
2322 1,
2323 C2PortTunneledModeTuning::Struct::SIDEBAND,
2324 C2PortTunneledModeTuning::Struct::REALTIME,
2325 0);
2326 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2327 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2328 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2329 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2330 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2331 } else {
2332 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2333 tunneledPlayback->setFlexCount(0);
2334 }
2335 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2336 if (c2err != C2_OK) {
2337 return UNKNOWN_ERROR;
2338 }
2339
Houxiang Dai5a97b472021-03-22 17:56:04 +08002340 if (sidebandHandle == nullptr) {
2341 return OK;
2342 }
2343
ted.sun765db4d2020-06-23 14:03:41 +08002344 std::vector<std::unique_ptr<C2Param>> params;
2345 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2346 if (c2err == C2_OK && params.size() == 1u) {
2347 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2348 C2PortTunnelHandleTuning::output::From(params[0].get());
2349 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2350 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2351 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2352 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2353 memcpy(handle->data, videoTunnelSideband->m.values,
2354 sizeof(int32_t) * videoTunnelSideband->flexCount());
2355 return OK;
2356 } else {
2357 return NO_MEMORY;
2358 }
2359 }
2360 return UNKNOWN_ERROR;
2361}
2362
Pawin Vongmasa36653902018-11-15 00:10:25 -08002363void CCodec::initiateReleaseIfStuck() {
2364 std::string name;
2365 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002366 {
2367 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002368 if (deadline->get() < std::chrono::steady_clock::now()) {
2369 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002370 }
2371 if (deadline->get() != TimePoint::max()) {
2372 pendingDeadline = true;
2373 }
2374 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002375 bool tunneled = false;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002376 bool isMediaTypeKnown = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002377 {
Wonsik Kimabca11e2021-04-30 13:11:41 -07002378 static const std::set<std::string> kKnownMediaTypes{
2379 MIMETYPE_VIDEO_VP8,
2380 MIMETYPE_VIDEO_VP9,
2381 MIMETYPE_VIDEO_AV1,
2382 MIMETYPE_VIDEO_AVC,
2383 MIMETYPE_VIDEO_HEVC,
2384 MIMETYPE_VIDEO_MPEG4,
2385 MIMETYPE_VIDEO_H263,
2386 MIMETYPE_VIDEO_MPEG2,
2387 MIMETYPE_VIDEO_RAW,
2388 MIMETYPE_VIDEO_DOLBY_VISION,
2389
2390 MIMETYPE_AUDIO_AMR_NB,
2391 MIMETYPE_AUDIO_AMR_WB,
2392 MIMETYPE_AUDIO_MPEG,
2393 MIMETYPE_AUDIO_AAC,
2394 MIMETYPE_AUDIO_QCELP,
2395 MIMETYPE_AUDIO_VORBIS,
2396 MIMETYPE_AUDIO_OPUS,
2397 MIMETYPE_AUDIO_G711_ALAW,
2398 MIMETYPE_AUDIO_G711_MLAW,
2399 MIMETYPE_AUDIO_RAW,
2400 MIMETYPE_AUDIO_FLAC,
2401 MIMETYPE_AUDIO_MSGSM,
2402 MIMETYPE_AUDIO_AC3,
2403 MIMETYPE_AUDIO_EAC3,
2404
2405 MIMETYPE_IMAGE_ANDROID_HEIC,
2406 };
Wonsik Kim75e22f42021-04-14 23:34:51 -07002407 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2408 const std::unique_ptr<Config> &config = *configLocked;
2409 tunneled = config->mTunneled;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002410 isMediaTypeKnown = (kKnownMediaTypes.count(config->mCodingMediaType) != 0);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002411 }
Wonsik Kimabca11e2021-04-30 13:11:41 -07002412 if (!tunneled && isMediaTypeKnown && name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002413 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2414 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2415 if (elapsed >= kWorkDurationThreshold) {
2416 name = "queue";
2417 }
2418 if (elapsed > 0s) {
2419 pendingDeadline = true;
2420 }
2421 }
2422 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002423 // We're not stuck.
2424 if (pendingDeadline) {
2425 // If we are not stuck yet but still has deadline coming up,
2426 // post watch message to check back later.
2427 (new AMessage(kWhatWatch, this))->post();
2428 }
2429 return;
2430 }
2431
2432 ALOGW("previous call to %s exceeded timeout", name.c_str());
2433 initiateRelease(false);
2434 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2435}
2436
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002437// static
2438PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002439 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002440 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002441 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002442 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2443 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002444 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002445 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2446 sp<IGraphicBufferProducer> gbp;
2447 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2448 status_t err = gbs->initCheck();
2449 if (err != OK) {
2450 ALOGE("Failed to create persistent input surface: error %d", err);
2451 return nullptr;
2452 }
2453 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002454 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002455 } else {
2456 return nullptr;
2457 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002458 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002459 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002460 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002461 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002462 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002463}
2464
Wonsik Kimffb889a2020-05-28 11:32:25 -07002465class IntfCache {
2466public:
2467 IntfCache() = default;
2468
2469 status_t init(const std::string &name) {
2470 std::shared_ptr<Codec2Client::Interface> intf{
2471 Codec2Client::CreateInterfaceByName(name.c_str())};
2472 if (!intf) {
2473 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2474 mInitStatus = NO_INIT;
2475 return NO_INIT;
2476 }
2477 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2478 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2479 C2ParamField{&sUsage, &sUsage.value}));
2480 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2481 if (err != C2_OK) {
2482 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2483 name.c_str(), err);
2484 mFields[0].status = err;
2485 }
2486 std::vector<std::unique_ptr<C2Param>> params;
2487 err = intf->query(
2488 {&mApiFeatures},
2489 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2490 C2_MAY_BLOCK,
2491 &params);
2492 if (err != C2_OK && err != C2_BAD_INDEX) {
2493 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2494 name.c_str(), err);
2495 }
2496 while (!params.empty()) {
2497 C2Param *param = params.back().release();
2498 params.pop_back();
2499 if (!param) {
2500 continue;
2501 }
2502 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2503 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002504 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002505 }
2506 }
2507 mInitStatus = OK;
2508 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002509 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002510
2511 status_t initCheck() const { return mInitStatus; }
2512
2513 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2514 CHECK_EQ(1u, mFields.size());
2515 return mFields[0];
2516 }
2517
2518 const C2ApiFeaturesSetting &getApiFeatures() const {
2519 return mApiFeatures;
2520 }
2521
2522 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2523 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2524 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2525 C2PortAllocatorsTuning::input::AllocUnique(0);
2526 param->invalidate();
2527 return param;
2528 }();
2529 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2530 }
2531
2532private:
2533 status_t mInitStatus{NO_INIT};
2534
2535 std::vector<C2FieldSupportedValuesQuery> mFields;
2536 C2ApiFeaturesSetting mApiFeatures;
2537 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2538};
2539
2540static const IntfCache &GetIntfCache(const std::string &name) {
2541 static IntfCache sNullIntfCache;
2542 static std::mutex sMutex;
2543 static std::map<std::string, IntfCache> sCache;
2544 std::unique_lock<std::mutex> lock{sMutex};
2545 auto it = sCache.find(name);
2546 if (it == sCache.end()) {
2547 lock.unlock();
2548 IntfCache intfCache;
2549 status_t err = intfCache.init(name);
2550 if (err != OK) {
2551 return sNullIntfCache;
2552 }
2553 lock.lock();
2554 it = sCache.insert({name, std::move(intfCache)}).first;
2555 }
2556 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002557}
2558
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002559static status_t GetCommonAllocatorIds(
2560 const std::vector<std::string> &names,
2561 C2Allocator::type_t type,
2562 std::set<C2Allocator::id_t> *ids) {
2563 int poolMask = GetCodec2PoolMask();
2564 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2565 C2Allocator::id_t defaultAllocatorId =
2566 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2567
2568 ids->clear();
2569 if (names.empty()) {
2570 return OK;
2571 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002572 bool firstIteration = true;
2573 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002574 const IntfCache &intfCache = GetIntfCache(name);
2575 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002576 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002577 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002578 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002579 if (firstIteration) {
2580 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002581 if (allocators && allocators.flexCount() > 0) {
2582 ids->insert(allocators.m.values,
2583 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002584 }
2585 if (ids->empty()) {
2586 // The component does not advertise allocators. Use default.
2587 ids->insert(defaultAllocatorId);
2588 }
2589 continue;
2590 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002591 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002592 if (allocators && allocators.flexCount() > 0) {
2593 filtered = true;
2594 for (auto it = ids->begin(); it != ids->end(); ) {
2595 bool found = false;
2596 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2597 if (allocators.m.values[j] == *it) {
2598 found = true;
2599 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002600 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002601 }
2602 if (found) {
2603 ++it;
2604 } else {
2605 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002606 }
2607 }
2608 }
2609 if (!filtered) {
2610 // The component does not advertise supported allocators. Use default.
2611 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2612 if (ids->size() != (containsDefault ? 1 : 0)) {
2613 ids->clear();
2614 if (containsDefault) {
2615 ids->insert(defaultAllocatorId);
2616 }
2617 }
2618 }
2619 }
2620 // Finally, filter with pool masks
2621 for (auto it = ids->begin(); it != ids->end(); ) {
2622 if ((poolMask >> *it) & 1) {
2623 ++it;
2624 } else {
2625 it = ids->erase(it);
2626 }
2627 }
2628 return OK;
2629}
2630
2631static status_t CalculateMinMaxUsage(
2632 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2633 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2634 *minUsage = 0;
2635 *maxUsage = ~0ull;
2636 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002637 const IntfCache &intfCache = GetIntfCache(name);
2638 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002639 continue;
2640 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002641 const C2FieldSupportedValuesQuery &usageSupportedValues =
2642 intfCache.getUsageSupportedValues();
2643 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002644 continue;
2645 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002646 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002647 if (supported.type != C2FieldSupportedValues::FLAGS) {
2648 continue;
2649 }
2650 if (supported.values.empty()) {
2651 *maxUsage = 0;
2652 continue;
2653 }
2654 *minUsage |= supported.values[0].u64;
2655 int64_t currentMaxUsage = 0;
2656 for (const C2Value::Primitive &flags : supported.values) {
2657 currentMaxUsage |= flags.u64;
2658 }
2659 *maxUsage &= currentMaxUsage;
2660 }
2661 return OK;
2662}
2663
2664// static
2665status_t CCodec::CanFetchLinearBlock(
2666 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002667 for (const std::string &name : names) {
2668 const IntfCache &intfCache = GetIntfCache(name);
2669 if (intfCache.initCheck() != OK) {
2670 continue;
2671 }
2672 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2673 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2674 *isCompatible = false;
2675 return OK;
2676 }
2677 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002678 uint64_t minUsage = usage.expected;
2679 uint64_t maxUsage = ~0ull;
2680 std::set<C2Allocator::id_t> allocators;
2681 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2682 if (allocators.empty()) {
2683 *isCompatible = false;
2684 return OK;
2685 }
2686 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2687 *isCompatible = ((maxUsage & minUsage) == minUsage);
2688 return OK;
2689}
2690
2691static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2692 static std::mutex sMutex{};
2693 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2694 std::unique_lock<std::mutex> lock{sMutex};
2695 std::shared_ptr<C2BlockPool> pool;
2696 auto it = sPools.find(allocId);
2697 if (it == sPools.end()) {
2698 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2699 if (err == OK) {
2700 sPools.emplace(allocId, pool);
2701 } else {
2702 pool.reset();
2703 }
2704 } else {
2705 pool = it->second;
2706 }
2707 return pool;
2708}
2709
2710// static
2711std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2712 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
2713 uint64_t minUsage = usage.expected;
2714 uint64_t maxUsage = ~0ull;
2715 std::set<C2Allocator::id_t> allocators;
2716 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2717 if (allocators.empty()) {
2718 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2719 }
2720 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2721 if ((maxUsage & minUsage) != minUsage) {
2722 allocators.clear();
2723 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2724 }
2725 std::shared_ptr<C2LinearBlock> block;
2726 for (C2Allocator::id_t allocId : allocators) {
2727 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2728 if (!pool) {
2729 continue;
2730 }
2731 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2732 if (err != C2_OK || !block) {
2733 block.reset();
2734 continue;
2735 }
2736 break;
2737 }
2738 return block;
2739}
2740
2741// static
2742status_t CCodec::CanFetchGraphicBlock(
2743 const std::vector<std::string> &names, bool *isCompatible) {
2744 uint64_t minUsage = 0;
2745 uint64_t maxUsage = ~0ull;
2746 std::set<C2Allocator::id_t> allocators;
2747 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2748 if (allocators.empty()) {
2749 *isCompatible = false;
2750 return OK;
2751 }
2752 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2753 *isCompatible = ((maxUsage & minUsage) == minUsage);
2754 return OK;
2755}
2756
2757// static
2758std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2759 int32_t width,
2760 int32_t height,
2761 int32_t format,
2762 uint64_t usage,
2763 const std::vector<std::string> &names) {
2764 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2765 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2766 ALOGD("Unrecognized pixel format: %d", format);
2767 return nullptr;
2768 }
2769 uint64_t minUsage = 0;
2770 uint64_t maxUsage = ~0ull;
2771 std::set<C2Allocator::id_t> allocators;
2772 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2773 if (allocators.empty()) {
2774 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2775 }
2776 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2777 minUsage |= usage;
2778 if ((maxUsage & minUsage) != minUsage) {
2779 allocators.clear();
2780 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2781 }
2782 std::shared_ptr<C2GraphicBlock> block;
2783 for (C2Allocator::id_t allocId : allocators) {
2784 std::shared_ptr<C2BlockPool> pool;
2785 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2786 if (err != C2_OK || !pool) {
2787 continue;
2788 }
2789 err = pool->fetchGraphicBlock(
2790 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2791 if (err != C2_OK || !block) {
2792 block.reset();
2793 continue;
2794 }
2795 break;
2796 }
2797 return block;
2798}
2799
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002800} // namespace android