blob: 051e9cf6c74dcb13ddc0d3341cb40c6f49088e8e [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 Kima1335e12021-04-22 16:28:29 -0700401 // priority
402 if (mConfig.mPriority != config.mPriority) {
403 if (config.mPriority != INT_MAX) {
404 mNode->setPriority(config.mPriority);
405 }
406 mConfig.mPriority = config.mPriority;
407 }
408
Wonsik Kimbd557932019-07-02 15:51:20 -0700409 if (status.str().empty()) {
410 ALOGD("ISConfig not changed");
411 } else {
412 ALOGD("ISConfig%s", status.str().c_str());
413 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800414 return err;
415 }
416
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700417 void onInputBufferDone(c2_cntr64_t index) override {
418 mNode->onInputBufferDone(index);
419 }
420
Wonsik Kim673dd192021-01-29 14:58:12 -0800421 android_dataspace getDataspace() override {
422 return mNode->getDataspace();
423 }
424
Pawin Vongmasa36653902018-11-15 00:10:25 -0800425private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700426 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800427 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700428 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800429 uint32_t mWidth;
430 uint32_t mHeight;
431 Config mConfig;
432};
433
434class Codec2ClientInterfaceWrapper : public C2ComponentStore {
435 std::shared_ptr<Codec2Client> mClient;
436
437public:
438 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
439 : mClient(client) { }
440
441 virtual ~Codec2ClientInterfaceWrapper() = default;
442
443 virtual c2_status_t config_sm(
444 const std::vector<C2Param *> &params,
445 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
446 return mClient->config(params, C2_MAY_BLOCK, failures);
447 };
448
449 virtual c2_status_t copyBuffer(
450 std::shared_ptr<C2GraphicBuffer>,
451 std::shared_ptr<C2GraphicBuffer>) {
452 return C2_OMITTED;
453 }
454
455 virtual c2_status_t createComponent(
456 C2String, std::shared_ptr<C2Component> *const component) {
457 component->reset();
458 return C2_OMITTED;
459 }
460
461 virtual c2_status_t createInterface(
462 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
463 interface->reset();
464 return C2_OMITTED;
465 }
466
467 virtual c2_status_t query_sm(
468 const std::vector<C2Param *> &stackParams,
469 const std::vector<C2Param::Index> &heapParamIndices,
470 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
471 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
472 }
473
474 virtual c2_status_t querySupportedParams_nb(
475 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
476 return mClient->querySupportedParams(params);
477 }
478
479 virtual c2_status_t querySupportedValues_sm(
480 std::vector<C2FieldSupportedValuesQuery> &fields) const {
481 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
482 }
483
484 virtual C2String getName() const {
485 return mClient->getName();
486 }
487
488 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
489 return mClient->getParamReflector();
490 }
491
492 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
493 return std::vector<std::shared_ptr<const C2Component::Traits>>();
494 }
495};
496
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800497void RevertOutputFormatIfNeeded(
498 const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
499 // We used to not report changes to these keys to the client.
500 const static std::set<std::string> sIgnoredKeys({
501 KEY_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800502 KEY_FRAME_RATE,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800503 KEY_MAX_BIT_RATE,
Harish Mahendrakar8c537502021-02-23 21:20:22 -0800504 KEY_MAX_WIDTH,
505 KEY_MAX_HEIGHT,
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800506 "csd-0",
507 "csd-1",
508 "csd-2",
509 });
510 if (currentFormat == oldFormat) {
511 return;
512 }
513 sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
514 AMessage::Type type;
515 for (size_t i = diff->countEntries(); i > 0; --i) {
516 if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
517 diff->removeEntryAt(i - 1);
518 }
519 }
520 if (diff->countEntries() == 0) {
521 currentFormat = oldFormat;
522 }
523}
524
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700525void AmendOutputFormatWithCodecSpecificData(
Greg Kaiserf2572aa2021-05-10 12:50:27 -0700526 const uint8_t *data, size_t size, const std::string &mediaType,
Wonsik Kim1f5063d2021-05-03 15:41:17 -0700527 const sp<AMessage> &outputFormat) {
528 if (mediaType == MIMETYPE_VIDEO_AVC) {
529 // Codec specific data should be SPS and PPS in a single buffer,
530 // each prefixed by a startcode (0x00 0x00 0x00 0x01).
531 // We separate the two and put them into the output format
532 // under the keys "csd-0" and "csd-1".
533
534 unsigned csdIndex = 0;
535
536 const uint8_t *nalStart;
537 size_t nalSize;
538 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
539 sp<ABuffer> csd = new ABuffer(nalSize + 4);
540 memcpy(csd->data(), "\x00\x00\x00\x01", 4);
541 memcpy(csd->data() + 4, nalStart, nalSize);
542
543 outputFormat->setBuffer(
544 AStringPrintf("csd-%u", csdIndex).c_str(), csd);
545
546 ++csdIndex;
547 }
548
549 if (csdIndex != 2) {
550 ALOGW("Expected two NAL units from AVC codec config, but %u found",
551 csdIndex);
552 }
553 } else {
554 // For everything else we just stash the codec specific data into
555 // the output format as a single piece of csd under "csd-0".
556 sp<ABuffer> csd = new ABuffer(size);
557 memcpy(csd->data(), data, size);
558 csd->setRange(0, size);
559 outputFormat->setBuffer("csd-0", csd);
560 }
561}
562
Pawin Vongmasa36653902018-11-15 00:10:25 -0800563} // namespace
564
565// CCodec::ClientListener
566
567struct CCodec::ClientListener : public Codec2Client::Listener {
568
569 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
570
571 virtual void onWorkDone(
572 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800573 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800574 (void)component;
575 sp<CCodec> codec(mCodec.promote());
576 if (!codec) {
577 return;
578 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800579 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800580 }
581
582 virtual void onTripped(
583 const std::weak_ptr<Codec2Client::Component>& component,
584 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
585 ) override {
586 // TODO
587 (void)component;
588 (void)settingResult;
589 }
590
591 virtual void onError(
592 const std::weak_ptr<Codec2Client::Component>& component,
593 uint32_t errorCode) override {
Praveen Chavan72eff012020-11-20 23:20:28 -0800594 {
595 // Component is only used for reporting as we use a separate listener for each instance
596 std::shared_ptr<Codec2Client::Component> comp = component.lock();
597 if (!comp) {
598 ALOGD("Component died with error: 0x%x", errorCode);
599 } else {
600 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
601 }
602 }
603
604 // Report to MediaCodec
Wonsik Kim10f33c02021-03-04 15:04:14 -0800605 // Note: for now we do not propagate the error code to MediaCodec
606 // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
Praveen Chavan72eff012020-11-20 23:20:28 -0800607 sp<CCodec> codec(mCodec.promote());
608 if (!codec || !codec->mCallback) {
609 return;
610 }
Wonsik Kim10f33c02021-03-04 15:04:14 -0800611 codec->mCallback->onError(
612 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
613 ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800614 }
615
616 virtual void onDeath(
617 const std::weak_ptr<Codec2Client::Component>& component) override {
618 { // Log the death of the component.
619 std::shared_ptr<Codec2Client::Component> comp = component.lock();
620 if (!comp) {
621 ALOGE("Codec2 component died.");
622 } else {
623 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
624 }
625 }
626
627 // Report to MediaCodec.
628 sp<CCodec> codec(mCodec.promote());
629 if (!codec || !codec->mCallback) {
630 return;
631 }
632 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
633 }
634
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800635 virtual void onFrameRendered(uint64_t bufferQueueId,
636 int32_t slotId,
637 int64_t timestampNs) override {
638 // TODO: implement
639 (void)bufferQueueId;
640 (void)slotId;
641 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800642 }
643
644 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800645 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800646 sp<CCodec> codec(mCodec.promote());
647 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800648 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800649 }
650 }
651
652private:
653 wp<CCodec> mCodec;
654};
655
656// CCodecCallbackImpl
657
658class CCodecCallbackImpl : public CCodecCallback {
659public:
660 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
661 ~CCodecCallbackImpl() override = default;
662
663 void onError(status_t err, enum ActionCode actionCode) override {
664 mCodec->mCallback->onError(err, actionCode);
665 }
666
667 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
668 mCodec->mCallback->onOutputFramesRendered(
669 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
670 }
671
Pawin Vongmasa36653902018-11-15 00:10:25 -0800672 void onOutputBuffersChanged() override {
673 mCodec->mCallback->onOutputBuffersChanged();
674 }
675
676private:
677 CCodec *mCodec;
678};
679
680// CCodec
681
682CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700683 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
684 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800685}
686
687CCodec::~CCodec() {
688}
689
690std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
691 return mChannel;
692}
693
694status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
695 status_t err = job();
696 if (err != C2_OK) {
697 mCallback->onError(err, ACTION_CODE_FATAL);
698 }
699 return err;
700}
701
702void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
703 auto setAllocating = [this] {
704 Mutexed<State>::Locked state(mState);
705 if (state->get() != RELEASED) {
706 return INVALID_OPERATION;
707 }
708 state->set(ALLOCATING);
709 return OK;
710 };
711 if (tryAndReportOnError(setAllocating) != OK) {
712 return;
713 }
714
715 sp<RefBase> codecInfo;
716 CHECK(msg->findObject("codecInfo", &codecInfo));
717 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
718
719 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
720 allocMsg->setObject("codecInfo", codecInfo);
721 allocMsg->post();
722}
723
724void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
725 if (codecInfo == nullptr) {
726 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
727 return;
728 }
729 ALOGD("allocate(%s)", codecInfo->getCodecName());
730 mClientListener.reset(new ClientListener(this));
731
732 AString componentName = codecInfo->getCodecName();
733 std::shared_ptr<Codec2Client> client;
734
735 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700736 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800737 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800738 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800739 SetPreferredCodec2ComponentStore(
740 std::make_shared<Codec2ClientInterfaceWrapper>(client));
741 }
742
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900743 std::shared_ptr<Codec2Client::Component> comp;
744 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800745 componentName.c_str(),
746 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900747 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800748 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900749 if (status != C2_OK) {
750 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800751 Mutexed<State>::Locked state(mState);
752 state->set(RELEASED);
753 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900754 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800755 state.lock();
756 return;
757 }
758 ALOGI("Created component [%s]", componentName.c_str());
759 mChannel->setComponent(comp);
760 auto setAllocated = [this, comp, client] {
761 Mutexed<State>::Locked state(mState);
762 if (state->get() != ALLOCATING) {
763 state->set(RELEASED);
764 return UNKNOWN_ERROR;
765 }
766 state->set(ALLOCATED);
767 state->comp = comp;
768 mClient = client;
769 return OK;
770 };
771 if (tryAndReportOnError(setAllocated) != OK) {
772 return;
773 }
774
775 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700776 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
777 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800778 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800779 if (err != OK) {
780 ALOGW("Failed to initialize configuration support");
781 // TODO: report error once we complete implementation.
782 }
783 config->queryConfiguration(comp);
784
785 mCallback->onComponentAllocated(componentName.c_str());
786}
787
788void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
789 auto checkAllocated = [this] {
790 Mutexed<State>::Locked state(mState);
791 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
792 };
793 if (tryAndReportOnError(checkAllocated) != OK) {
794 return;
795 }
796
797 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
798 msg->setMessage("format", format);
799 msg->post();
800}
801
802void CCodec::configure(const sp<AMessage> &msg) {
803 std::shared_ptr<Codec2Client::Component> comp;
804 auto checkAllocated = [this, &comp] {
805 Mutexed<State>::Locked state(mState);
806 if (state->get() != ALLOCATED) {
807 state->set(RELEASED);
808 return UNKNOWN_ERROR;
809 }
810 comp = state->comp;
811 return OK;
812 };
813 if (tryAndReportOnError(checkAllocated) != OK) {
814 return;
815 }
816
817 auto doConfig = [msg, comp, this]() -> status_t {
818 AString mime;
819 if (!msg->findString("mime", &mime)) {
820 return BAD_VALUE;
821 }
822
823 int32_t encoder;
824 if (!msg->findInt32("encoder", &encoder)) {
825 encoder = false;
826 }
827
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800828 int32_t flags;
829 if (!msg->findInt32("flags", &flags)) {
830 return BAD_VALUE;
831 }
832
Pawin Vongmasa36653902018-11-15 00:10:25 -0800833 // TODO: read from intf()
834 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
835 return UNKNOWN_ERROR;
836 }
837
838 int32_t storeMeta;
839 if (encoder
840 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
841 && storeMeta != kMetadataBufferTypeInvalid) {
842 if (storeMeta != kMetadataBufferTypeANWBuffer) {
843 ALOGD("Only ANW buffers are supported for legacy metadata mode");
844 return BAD_VALUE;
845 }
846 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
847 }
848
ted.sun765db4d2020-06-23 14:03:41 +0800849 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800850 sp<RefBase> obj;
851 sp<Surface> surface;
852 if (msg->findObject("native-window", &obj)) {
853 surface = static_cast<Surface *>(obj.get());
ted.sun765db4d2020-06-23 14:03:41 +0800854 // setup tunneled playback
855 if (surface != nullptr) {
856 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
857 const std::unique_ptr<Config> &config = *configLocked;
858 if ((config->mDomain & Config::IS_DECODER)
859 && (config->mDomain & Config::IS_VIDEO)) {
860 int32_t tunneled;
861 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
862 ALOGI("Configuring TUNNELED video playback.");
863
864 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
865 if (err != OK) {
866 ALOGE("configureTunneledVideoPlayback failed!");
867 return err;
868 }
869 config->mTunneled = true;
870 }
871 }
872 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800873 setSurface(surface);
874 }
875
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700876 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
877 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800878 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800879 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
880 ALOGD("[%s] buffers are %sbound to CCodec for this session",
881 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800882
Wonsik Kim1114eea2019-02-25 14:35:24 -0800883 // Enforce required parameters
884 int32_t i32;
885 float flt;
886 if (config->mDomain & Config::IS_AUDIO) {
887 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
888 ALOGD("sample rate is missing, which is required for audio components.");
889 return BAD_VALUE;
890 }
891 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
892 ALOGD("channel count is missing, which is required for audio components.");
893 return BAD_VALUE;
894 }
895 if ((config->mDomain & Config::IS_ENCODER)
896 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
897 && !msg->findInt32(KEY_BIT_RATE, &i32)
898 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
899 ALOGD("bitrate is missing, which is required for audio encoders.");
900 return BAD_VALUE;
901 }
902 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800903 int32_t width = 0;
904 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800905 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800906 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800907 ALOGD("width is missing, which is required for image/video components.");
908 return BAD_VALUE;
909 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800910 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800911 ALOGD("height is missing, which is required for image/video components.");
912 return BAD_VALUE;
913 }
914 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700915 int32_t mode = BITRATE_MODE_VBR;
916 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700917 if (!msg->findInt32(KEY_QUALITY, &i32)) {
918 ALOGD("quality is missing, which is required for video encoders in CQ.");
919 return BAD_VALUE;
920 }
921 } else {
922 if (!msg->findInt32(KEY_BIT_RATE, &i32)
923 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
924 ALOGD("bitrate is missing, which is required for video encoders.");
925 return BAD_VALUE;
926 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800927 }
928 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
929 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
930 ALOGD("I frame interval is missing, which is required for video encoders.");
931 return BAD_VALUE;
932 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700933 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
934 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
935 ALOGD("frame rate is missing, which is required for video encoders.");
936 return BAD_VALUE;
937 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800938 }
939 }
940
Pawin Vongmasa36653902018-11-15 00:10:25 -0800941 /*
942 * Handle input surface configuration
943 */
944 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
945 && (config->mDomain & Config::IS_ENCODER)) {
946 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
947 {
948 config->mISConfig->mMinFps = 0;
949 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800950 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800951 config->mISConfig->mMinFps = 1e6 / value;
952 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700953 if (!msg->findFloat(
954 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
955 config->mISConfig->mMaxFps = -1;
956 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800957 config->mISConfig->mMinAdjustedFps = 0;
958 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800959 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800960 if (value < 0 && value >= INT32_MIN) {
961 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700962 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800963 } else if (value > 0 && value <= INT32_MAX) {
964 config->mISConfig->mMinAdjustedFps = 1e6 / value;
965 }
966 }
967 }
968
969 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700970 bool captureFpsFound = false;
971 double timeLapseFps;
972 float captureRate;
973 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
974 config->mISConfig->mCaptureFps = timeLapseFps;
975 captureFpsFound = true;
976 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
977 config->mISConfig->mCaptureFps = captureRate;
978 captureFpsFound = true;
979 }
980 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800981 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
982 }
983 }
984
985 {
986 config->mISConfig->mSuspended = false;
987 config->mISConfig->mSuspendAtUs = -1;
988 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800989 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800990 config->mISConfig->mSuspended = true;
991 }
992 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700993 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -0700994 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800995 }
996
997 /*
998 * Handle desired color format.
999 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001000 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001001 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001002 int32_t format = 0;
1003 // Query vendor format for Flexible YUV
1004 std::vector<std::unique_ptr<C2Param>> heapParams;
1005 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
1006 if (mClient->query(
1007 {},
1008 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1009 C2_MAY_BLOCK,
1010 &heapParams) == C2_OK
1011 && heapParams.size() == 1u) {
1012 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1013 heapParams[0].get());
1014 } else {
1015 pixelFormatInfo = nullptr;
1016 }
1017 std::optional<uint32_t> flexPixelFormat{};
1018 std::optional<uint32_t> flexPlanarPixelFormat{};
1019 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
1020 if (pixelFormatInfo && *pixelFormatInfo) {
1021 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1022 const C2FlexiblePixelFormatDescriptorStruct &desc =
1023 pixelFormatInfo->m.values[i];
1024 if (desc.bitDepth != 8
1025 || desc.subsampling != C2Color::YUV_420
1026 // TODO(b/180076105): some device report wrong layout
1027 // || desc.layout == C2Color::INTERLEAVED_PACKED
1028 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1029 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1030 continue;
1031 }
1032 if (!flexPixelFormat) {
1033 flexPixelFormat = desc.pixelFormat;
1034 }
1035 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
1036 flexPlanarPixelFormat = desc.pixelFormat;
1037 }
1038 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
1039 flexSemiPlanarPixelFormat = desc.pixelFormat;
1040 }
1041 }
1042 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001043 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001044 // Also handle default color format (encoders require color format, so this is only
1045 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001046 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001047 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001048 const char *prefix = "";
1049 if (flexSemiPlanarPixelFormat) {
1050 format = COLOR_FormatYUV420SemiPlanar;
1051 prefix = "semi-";
1052 } else {
1053 format = COLOR_FormatYUV420Planar;
1054 }
1055 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1056 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001057 } else {
1058 format = COLOR_FormatSurface;
1059 }
1060 defaultColorFormat = format;
1061 }
1062 } else {
1063 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
1064 switch (format) {
1065 case COLOR_FormatYUV420Flexible:
1066 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
1067 break;
1068 case COLOR_FormatYUV420Planar:
1069 case COLOR_FormatYUV420PackedPlanar:
1070 format = flexPlanarPixelFormat.value_or(
1071 flexPixelFormat.value_or(format));
1072 break;
1073 case COLOR_FormatYUV420SemiPlanar:
1074 case COLOR_FormatYUV420PackedSemiPlanar:
1075 format = flexSemiPlanarPixelFormat.value_or(
1076 flexPixelFormat.value_or(format));
1077 break;
1078 default:
1079 // No-op
1080 break;
1081 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001082 }
1083 }
1084
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001085 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001086 msg->setInt32("android._color-format", format);
1087 }
1088 }
1089
Wonsik Kim77e97c72021-01-20 10:33:22 -08001090 /*
1091 * Handle dataspace
1092 */
1093 int32_t usingRecorder;
1094 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1095 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1096 int32_t width, height;
1097 if (msg->findInt32("width", &width)
1098 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001099 ColorAspects aspects;
1100 getColorAspectsFromFormat(msg, aspects);
1101 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001102 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001103 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1104 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001105 }
1106 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1107 ALOGD("setting dataspace to %x", dataSpace);
1108 }
1109
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001110 int32_t subscribeToAllVendorParams;
1111 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1112 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1113 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1114 }
1115 }
1116
Pawin Vongmasa36653902018-11-15 00:10:25 -08001117 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001118 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1119 // the behavior here.
1120 sp<AMessage> sdkParams = msg;
1121 int32_t videoBitrate;
1122 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1123 sdkParams = msg->dup();
1124 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1125 }
ted.sun765db4d2020-06-23 14:03:41 +08001126 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001127 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001128 if (err != OK) {
1129 ALOGW("failed to convert configuration to c2 params");
1130 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001131
1132 int32_t maxBframes = 0;
1133 if ((config->mDomain & Config::IS_ENCODER)
1134 && (config->mDomain & Config::IS_VIDEO)
1135 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1136 && maxBframes > 0) {
1137 std::unique_ptr<C2StreamGopTuning::output> gop =
1138 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1139 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1140 gop->m.values[1] = {
1141 C2Config::picture_type_t(P_FRAME | B_FRAME),
1142 uint32_t(maxBframes)
1143 };
1144 configUpdate.push_back(std::move(gop));
1145 }
1146
Ray Essicka0ae6972021-03-10 19:40:01 -08001147 if ((config->mDomain & Config::IS_ENCODER)
1148 && (config->mDomain & Config::IS_VIDEO)) {
1149 // we may not use all 3 of these entries
1150 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1151 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1152 0u /* stream */);
1153
1154 int ix = 0;
1155
1156 int32_t iMax = INT32_MAX;
1157 int32_t iMin = INT32_MIN;
1158 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1159 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1160 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1161 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1162 }
1163
1164 int32_t pMax = INT32_MAX;
1165 int32_t pMin = INT32_MIN;
1166 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1167 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1168 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1169 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1170 }
1171
1172 int32_t bMax = INT32_MAX;
1173 int32_t bMin = INT32_MIN;
1174 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1175 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1176 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1177 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1178 }
1179
1180 // adjust to reflect actual use.
1181 qp->setFlexCount(ix);
1182
1183 configUpdate.push_back(std::move(qp));
1184 }
1185
Wonsik Kima1335e12021-04-22 16:28:29 -07001186 int32_t background = 0;
1187 if ((config->mDomain & Config::IS_VIDEO)
1188 && msg->findInt32("android._background-mode", &background)
1189 && background) {
1190 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1191 if (config->mISConfig) {
1192 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1193 }
1194 }
1195
Pawin Vongmasa36653902018-11-15 00:10:25 -08001196 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1197 if (err != OK) {
1198 ALOGW("failed to configure c2 params");
1199 return err;
1200 }
1201
1202 std::vector<std::unique_ptr<C2Param>> params;
1203 C2StreamUsageTuning::input usage(0u, 0u);
1204 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001205 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001206
Wonsik Kim3baecda2021-02-07 22:19:56 -08001207 C2Param::Index colorAspectsRequestIndex =
1208 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001209 std::initializer_list<C2Param::Index> indices {
Wonsik Kim3baecda2021-02-07 22:19:56 -08001210 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001211 };
1212 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001213 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001214 indices,
1215 C2_DONT_BLOCK,
1216 &params);
1217 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1218 ALOGE("Failed to query component interface: %d", c2err);
1219 return UNKNOWN_ERROR;
1220 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001221 if (usage) {
1222 if (usage.value & C2MemoryUsage::CPU_READ) {
1223 config->mInputFormat->setInt32("using-sw-read-often", true);
1224 }
1225 if (config->mISConfig) {
1226 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1227 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1228 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001229 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001230 }
1231
1232 // NOTE: we don't blindly use client specified input size if specified as clients
1233 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1234 // client specified size is only used to ask for bigger buffers than component suggested
1235 // size.
1236 int32_t clientInputSize = 0;
1237 bool clientSpecifiedInputSize =
1238 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1239 // TEMP: enforce minimum buffer size of 1MB for video decoders
1240 // and 16K / 4K for audio encoders/decoders
1241 if (maxInputSize.value == 0) {
1242 if (config->mDomain & Config::IS_AUDIO) {
1243 maxInputSize.value = encoder ? 16384 : 4096;
1244 } else if (!encoder) {
1245 maxInputSize.value = 1048576u;
1246 }
1247 }
1248
1249 // verify that CSD fits into this size (if defined)
1250 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1251 sp<ABuffer> csd;
1252 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1253 if (csd && csd->size() > maxInputSize.value) {
1254 maxInputSize.value = csd->size();
1255 }
1256 }
1257 }
1258
1259 // TODO: do this based on component requiring linear allocator for input
1260 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1261 if (clientSpecifiedInputSize) {
1262 // Warn that we're overriding client's max input size if necessary.
1263 if ((uint32_t)clientInputSize < maxInputSize.value) {
1264 ALOGD("client requested max input size %d, which is smaller than "
1265 "what component recommended (%u); overriding with component "
1266 "recommendation.", clientInputSize, maxInputSize.value);
1267 ALOGW("This behavior is subject to change. It is recommended that "
1268 "app developers double check whether the requested "
1269 "max input size is in reasonable range.");
1270 } else {
1271 maxInputSize.value = clientInputSize;
1272 }
1273 }
1274 // Pass max input size on input format to the buffer channel (if supplied by the
1275 // component or by a default)
1276 if (maxInputSize.value) {
1277 config->mInputFormat->setInt32(
1278 KEY_MAX_INPUT_SIZE,
1279 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1280 }
1281 }
1282
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001283 int32_t clientPrepend;
1284 if ((config->mDomain & Config::IS_VIDEO)
1285 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001286 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001287 && clientPrepend
1288 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001289 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001290 return BAD_VALUE;
1291 }
1292
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001293 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001294 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1295 // propagate HDR static info to output format for both encoders and decoders
1296 // if component supports this info, we will update from component, but only the raw port,
1297 // so don't propagate if component already filled it in.
1298 sp<ABuffer> hdrInfo;
1299 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1300 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1301 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1302 }
1303
1304 // Set desired color format from configuration parameter
1305 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001306 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1307 format = defaultColorFormat;
1308 }
1309 if (config->mDomain & Config::IS_ENCODER) {
1310 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001311 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1312 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001313 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001314 } else {
1315 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001316 }
1317 }
1318
1319 // propagate encoder delay and padding to output format
1320 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1321 int delay = 0;
1322 if (msg->findInt32("encoder-delay", &delay)) {
1323 config->mOutputFormat->setInt32("encoder-delay", delay);
1324 }
1325 int padding = 0;
1326 if (msg->findInt32("encoder-padding", &padding)) {
1327 config->mOutputFormat->setInt32("encoder-padding", padding);
1328 }
1329 }
1330
1331 // set channel-mask
1332 if (config->mDomain & Config::IS_AUDIO) {
1333 int32_t mask;
1334 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1335 if (config->mDomain & Config::IS_ENCODER) {
1336 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1337 } else {
1338 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1339 }
1340 }
1341 }
1342
Wonsik Kim3baecda2021-02-07 22:19:56 -08001343 std::unique_ptr<C2Param> colorTransferRequestParam;
1344 for (std::unique_ptr<C2Param> &param : params) {
1345 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1346 ALOGI("found color transfer request param");
1347 colorTransferRequestParam = std::move(param);
1348 }
1349 }
1350 int32_t colorTransferRequest = 0;
1351 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1352 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1353 colorTransferRequest = 0;
1354 }
1355
1356 if (colorTransferRequest != 0) {
1357 if (colorTransferRequestParam && *colorTransferRequestParam) {
1358 C2StreamColorAspectsInfo::output *info =
1359 static_cast<C2StreamColorAspectsInfo::output *>(
1360 colorTransferRequestParam.get());
1361 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1362 colorTransferRequest = 0;
1363 }
1364 } else {
1365 colorTransferRequest = 0;
1366 }
1367 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1368 }
1369
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001370 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1371 // Need to get stride/vstride
1372 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1373 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1374 // TODO: retrieve these values without allocating a buffer.
1375 // Currently allocating a buffer is necessary to retrieve the layout.
1376 int64_t blockUsage =
1377 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1378 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1379 width, height, pixelFormat, blockUsage, {comp->getName()});
1380 sp<GraphicBlockBuffer> buffer;
1381 if (block) {
1382 buffer = GraphicBlockBuffer::Allocate(
1383 config->mInputFormat,
1384 block,
1385 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1386 } else {
1387 ALOGD("Failed to allocate a graphic block "
1388 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1389 width, height, pixelFormat, (long long)blockUsage);
1390 // This means that byte buffer mode is not supported in this configuration
1391 // anyway. Skip setting stride/vstride to input format.
1392 }
1393 if (buffer) {
1394 sp<ABuffer> imageData = buffer->getImageData();
1395 MediaImage2 *img = nullptr;
1396 if (imageData && imageData->data()
1397 && imageData->size() >= sizeof(MediaImage2)) {
1398 img = (MediaImage2*)imageData->data();
1399 }
1400 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1401 int32_t stride = img->mPlane[0].mRowInc;
1402 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1403 if (img->mNumPlanes > 1 && stride > 0) {
1404 int64_t offsetDelta =
1405 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1406 if (offsetDelta % stride == 0) {
1407 int32_t vstride = int32_t(offsetDelta / stride);
1408 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1409 } else {
1410 ALOGD("Cannot report accurate slice height: "
1411 "offsetDelta = %lld stride = %d",
1412 (long long)offsetDelta, stride);
1413 }
1414 }
1415 }
1416 }
1417 }
1418 }
1419
1420 ALOGD("setup formats input: %s",
1421 config->mInputFormat->debugString().c_str());
1422 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001423 config->mOutputFormat->debugString().c_str());
1424 return OK;
1425 };
1426 if (tryAndReportOnError(doConfig) != OK) {
1427 return;
1428 }
1429
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001430 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1431 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001432
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001433 config->queryConfiguration(comp);
1434
Pawin Vongmasa36653902018-11-15 00:10:25 -08001435 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1436}
1437
1438void CCodec::initiateCreateInputSurface() {
1439 status_t err = [this] {
1440 Mutexed<State>::Locked state(mState);
1441 if (state->get() != ALLOCATED) {
1442 return UNKNOWN_ERROR;
1443 }
1444 // TODO: read it from intf() properly.
1445 if (state->comp->getName().find("encoder") == std::string::npos) {
1446 return INVALID_OPERATION;
1447 }
1448 return OK;
1449 }();
1450 if (err != OK) {
1451 mCallback->onInputSurfaceCreationFailed(err);
1452 return;
1453 }
1454
1455 (new AMessage(kWhatCreateInputSurface, this))->post();
1456}
1457
Lajos Molnar47118272019-01-31 16:28:04 -08001458sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1459 using namespace android::hardware::media::omx::V1_0;
1460 using namespace android::hardware::media::omx::V1_0::utils;
1461 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1462 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1463 android::sp<IOmx> omx = IOmx::getService();
1464 typedef android::hardware::graphics::bufferqueue::V1_0::
1465 IGraphicBufferProducer HGraphicBufferProducer;
1466 typedef android::hardware::media::omx::V1_0::
1467 IGraphicBufferSource HGraphicBufferSource;
1468 OmxStatus s;
1469 android::sp<HGraphicBufferProducer> gbp;
1470 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001471
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001472 using ::android::hardware::Return;
1473 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001474 [&s, &gbp, &gbs](
1475 OmxStatus status,
1476 const android::sp<HGraphicBufferProducer>& producer,
1477 const android::sp<HGraphicBufferSource>& source) {
1478 s = status;
1479 gbp = producer;
1480 gbs = source;
1481 });
1482 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001483 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001484 }
1485
1486 return nullptr;
1487}
1488
1489sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1490 sp<PersistentSurface> surface(CreateInputSurface());
1491
1492 if (surface == nullptr) {
1493 surface = CreateOmxInputSurface();
1494 }
1495
1496 return surface;
1497}
1498
Pawin Vongmasa36653902018-11-15 00:10:25 -08001499void CCodec::createInputSurface() {
1500 status_t err;
1501 sp<IGraphicBufferProducer> bufferProducer;
1502
Pawin Vongmasa36653902018-11-15 00:10:25 -08001503 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001504 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001505 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001506 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1507 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001508 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001509 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001510 }
1511
Lajos Molnar47118272019-01-31 16:28:04 -08001512 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001513 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1514 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1515 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001516
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001517 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001518 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1519 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001520 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001521 inputSurface));
1522 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001523 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001524 int32_t width = 0;
1525 (void)outputFormat->findInt32("width", &width);
1526 int32_t height = 0;
1527 (void)outputFormat->findInt32("height", &height);
1528 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001529 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001530 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001531 } else {
1532 ALOGE("Corrupted input surface");
1533 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1534 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001535 }
1536
1537 if (err != OK) {
1538 ALOGE("Failed to set up input surface: %d", err);
1539 mCallback->onInputSurfaceCreationFailed(err);
1540 return;
1541 }
1542
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001543 // Formats can change after setupInputSurface
1544 sp<AMessage> inputFormat;
1545 {
1546 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1547 const std::unique_ptr<Config> &config = *configLocked;
1548 inputFormat = config->mInputFormat;
1549 outputFormat = config->mOutputFormat;
1550 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001551 mCallback->onInputSurfaceCreated(
1552 inputFormat,
1553 outputFormat,
1554 new BufferProducerWrapper(bufferProducer));
1555}
1556
1557status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001558 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1559 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001560 config->mUsingSurface = true;
1561
1562 // we are now using surface - apply default color aspects to input format - as well as
1563 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001564 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001565 ALOGD("input format %s to %s",
1566 inputFormatChanged ? "changed" : "unchanged",
1567 config->mInputFormat->debugString().c_str());
1568
1569 // configure dataspace
1570 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1571 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1572 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1573 surface->setDataSpace(dataSpace);
1574
1575 status_t err = mChannel->setInputSurface(surface);
1576 if (err != OK) {
1577 // undo input format update
1578 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001579 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001580 return err;
1581 }
1582 config->mInputSurface = surface;
1583
1584 if (config->mISConfig) {
1585 surface->configure(*config->mISConfig);
1586 } else {
1587 ALOGD("ISConfig: no configuration");
1588 }
1589
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001590 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001591}
1592
1593void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1594 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1595 msg->setObject("surface", surface);
1596 msg->post();
1597}
1598
1599void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001600 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001601 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001602 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001603 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1604 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001605 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001606 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001607 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001608 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1609 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1610 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1611 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001612 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1613 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1614 if (err != OK) {
1615 ALOGE("Failed to set up input surface: %d", err);
1616 mCallback->onInputSurfaceDeclined(err);
1617 return;
1618 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001619 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001620 int32_t width = 0;
1621 (void)outputFormat->findInt32("width", &width);
1622 int32_t height = 0;
1623 (void)outputFormat->findInt32("height", &height);
1624 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001625 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001626 if (err != OK) {
1627 ALOGE("Failed to set up input surface: %d", err);
1628 mCallback->onInputSurfaceDeclined(err);
1629 return;
1630 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001631 } else {
1632 ALOGE("Failed to set input surface: Corrupted surface.");
1633 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1634 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001635 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001636 // Formats can change after setupInputSurface
1637 sp<AMessage> inputFormat;
1638 {
1639 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1640 const std::unique_ptr<Config> &config = *configLocked;
1641 inputFormat = config->mInputFormat;
1642 outputFormat = config->mOutputFormat;
1643 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001644 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1645}
1646
1647void CCodec::initiateStart() {
1648 auto setStarting = [this] {
1649 Mutexed<State>::Locked state(mState);
1650 if (state->get() != ALLOCATED) {
1651 return UNKNOWN_ERROR;
1652 }
1653 state->set(STARTING);
1654 return OK;
1655 };
1656 if (tryAndReportOnError(setStarting) != OK) {
1657 return;
1658 }
1659
1660 (new AMessage(kWhatStart, this))->post();
1661}
1662
1663void CCodec::start() {
1664 std::shared_ptr<Codec2Client::Component> comp;
1665 auto checkStarting = [this, &comp] {
1666 Mutexed<State>::Locked state(mState);
1667 if (state->get() != STARTING) {
1668 return UNKNOWN_ERROR;
1669 }
1670 comp = state->comp;
1671 return OK;
1672 };
1673 if (tryAndReportOnError(checkStarting) != OK) {
1674 return;
1675 }
1676
1677 c2_status_t err = comp->start();
1678 if (err != C2_OK) {
1679 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1680 ACTION_CODE_FATAL);
1681 return;
1682 }
1683 sp<AMessage> inputFormat;
1684 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001685 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001686 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001687 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001688 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1689 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001690 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001691 // start triggers format dup
1692 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001693 if (config->mInputSurface) {
1694 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001695 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001696 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001697 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001698 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001699 if (err2 != OK) {
1700 mCallback->onError(err2, ACTION_CODE_FATAL);
1701 return;
1702 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001703 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001704 if (err2 != OK) {
1705 mCallback->onError(err2, ACTION_CODE_FATAL);
1706 return;
1707 }
1708
1709 auto setRunning = [this] {
1710 Mutexed<State>::Locked state(mState);
1711 if (state->get() != STARTING) {
1712 return UNKNOWN_ERROR;
1713 }
1714 state->set(RUNNING);
1715 return OK;
1716 };
1717 if (tryAndReportOnError(setRunning) != OK) {
1718 return;
1719 }
1720 mCallback->onStartCompleted();
1721
1722 (void)mChannel->requestInitialInputBuffers();
1723}
1724
1725void CCodec::initiateShutdown(bool keepComponentAllocated) {
1726 if (keepComponentAllocated) {
1727 initiateStop();
1728 } else {
1729 initiateRelease();
1730 }
1731}
1732
1733void CCodec::initiateStop() {
1734 {
1735 Mutexed<State>::Locked state(mState);
1736 if (state->get() == ALLOCATED
1737 || state->get() == RELEASED
1738 || state->get() == STOPPING
1739 || state->get() == RELEASING) {
1740 // We're already stopped, released, or doing it right now.
1741 state.unlock();
1742 mCallback->onStopCompleted();
1743 state.lock();
1744 return;
1745 }
1746 state->set(STOPPING);
1747 }
1748
Wonsik Kim936a89c2020-05-08 16:07:50 -07001749 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001750 (new AMessage(kWhatStop, this))->post();
1751}
1752
1753void CCodec::stop() {
1754 std::shared_ptr<Codec2Client::Component> comp;
1755 {
1756 Mutexed<State>::Locked state(mState);
1757 if (state->get() == RELEASING) {
1758 state.unlock();
1759 // We're already stopped or release is in progress.
1760 mCallback->onStopCompleted();
1761 state.lock();
1762 return;
1763 } else if (state->get() != STOPPING) {
1764 state.unlock();
1765 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1766 state.lock();
1767 return;
1768 }
1769 comp = state->comp;
1770 }
1771 status_t err = comp->stop();
1772 if (err != C2_OK) {
1773 // TODO: convert err into status_t
1774 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1775 }
1776
1777 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001778 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1779 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001780 if (config->mInputSurface) {
1781 config->mInputSurface->disconnect();
1782 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001783 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001784 }
1785 }
1786 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001787 Mutexed<State>::Locked state(mState);
1788 if (state->get() == STOPPING) {
1789 state->set(ALLOCATED);
1790 }
1791 }
1792 mCallback->onStopCompleted();
1793}
1794
1795void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001796 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001797 {
1798 Mutexed<State>::Locked state(mState);
1799 if (state->get() == RELEASED || state->get() == RELEASING) {
1800 // We're already released or doing it right now.
1801 if (sendCallback) {
1802 state.unlock();
1803 mCallback->onReleaseCompleted();
1804 state.lock();
1805 }
1806 return;
1807 }
1808 if (state->get() == ALLOCATING) {
1809 state->set(RELEASING);
1810 // With the altered state allocate() would fail and clean up.
1811 if (sendCallback) {
1812 state.unlock();
1813 mCallback->onReleaseCompleted();
1814 state.lock();
1815 }
1816 return;
1817 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001818 if (state->get() == STARTING
1819 || state->get() == RUNNING
1820 || state->get() == STOPPING) {
1821 // Input surface may have been started, so clean up is needed.
1822 clearInputSurfaceIfNeeded = true;
1823 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001824 state->set(RELEASING);
1825 }
1826
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001827 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001828 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1829 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001830 if (config->mInputSurface) {
1831 config->mInputSurface->disconnect();
1832 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001833 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001834 }
1835 }
1836
Wonsik Kim936a89c2020-05-08 16:07:50 -07001837 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001838 // thiz holds strong ref to this while the thread is running.
1839 sp<CCodec> thiz(this);
1840 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1841}
1842
1843void CCodec::release(bool sendCallback) {
1844 std::shared_ptr<Codec2Client::Component> comp;
1845 {
1846 Mutexed<State>::Locked state(mState);
1847 if (state->get() == RELEASED) {
1848 if (sendCallback) {
1849 state.unlock();
1850 mCallback->onReleaseCompleted();
1851 state.lock();
1852 }
1853 return;
1854 }
1855 comp = state->comp;
1856 }
1857 comp->release();
1858
1859 {
1860 Mutexed<State>::Locked state(mState);
1861 state->set(RELEASED);
1862 state->comp.reset();
1863 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001864 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001865 if (sendCallback) {
1866 mCallback->onReleaseCompleted();
1867 }
1868}
1869
1870status_t CCodec::setSurface(const sp<Surface> &surface) {
Wonsik Kim75e22f42021-04-14 23:34:51 -07001871 {
1872 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1873 const std::unique_ptr<Config> &config = *configLocked;
1874 if (config->mTunneled && config->mSidebandHandle != nullptr) {
1875 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
1876 status_t err = native_window_set_sideband_stream(
1877 nativeWindow.get(),
1878 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
1879 if (err != OK) {
1880 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
1881 nativeWindow.get(), config->mSidebandHandle->handle(), err);
1882 return err;
1883 }
ted.sun765db4d2020-06-23 14:03:41 +08001884 }
1885 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001886 return mChannel->setSurface(surface);
1887}
1888
1889void CCodec::signalFlush() {
1890 status_t err = [this] {
1891 Mutexed<State>::Locked state(mState);
1892 if (state->get() == FLUSHED) {
1893 return ALREADY_EXISTS;
1894 }
1895 if (state->get() != RUNNING) {
1896 return UNKNOWN_ERROR;
1897 }
1898 state->set(FLUSHING);
1899 return OK;
1900 }();
1901 switch (err) {
1902 case ALREADY_EXISTS:
1903 mCallback->onFlushCompleted();
1904 return;
1905 case OK:
1906 break;
1907 default:
1908 mCallback->onError(err, ACTION_CODE_FATAL);
1909 return;
1910 }
1911
1912 mChannel->stop();
1913 (new AMessage(kWhatFlush, this))->post();
1914}
1915
1916void CCodec::flush() {
1917 std::shared_ptr<Codec2Client::Component> comp;
1918 auto checkFlushing = [this, &comp] {
1919 Mutexed<State>::Locked state(mState);
1920 if (state->get() != FLUSHING) {
1921 return UNKNOWN_ERROR;
1922 }
1923 comp = state->comp;
1924 return OK;
1925 };
1926 if (tryAndReportOnError(checkFlushing) != OK) {
1927 return;
1928 }
1929
1930 std::list<std::unique_ptr<C2Work>> flushedWork;
1931 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1932 {
1933 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1934 flushedWork.splice(flushedWork.end(), *queue);
1935 }
1936 if (err != C2_OK) {
1937 // TODO: convert err into status_t
1938 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1939 }
1940
1941 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001942
1943 {
1944 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001945 if (state->get() == FLUSHING) {
1946 state->set(FLUSHED);
1947 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001948 }
1949 mCallback->onFlushCompleted();
1950}
1951
1952void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001953 std::shared_ptr<Codec2Client::Component> comp;
1954 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001955 Mutexed<State>::Locked state(mState);
1956 if (state->get() != FLUSHED) {
1957 return UNKNOWN_ERROR;
1958 }
1959 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001960 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001961 return OK;
1962 };
1963 if (tryAndReportOnError(setResuming) != OK) {
1964 return;
1965 }
1966
Wonsik Kime75a5da2020-02-14 17:29:03 -08001967 {
1968 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1969 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001970 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001971 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001972 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001973 }
1974
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001975 (void)mChannel->start(nullptr, nullptr, [&]{
1976 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1977 const std::unique_ptr<Config> &config = *configLocked;
1978 return config->mBuffersBoundToCodec;
1979 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001980
1981 {
1982 Mutexed<State>::Locked state(mState);
1983 if (state->get() != RESUMING) {
1984 state.unlock();
1985 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1986 state.lock();
1987 return;
1988 }
1989 state->set(RUNNING);
1990 }
1991
1992 (void)mChannel->requestInitialInputBuffers();
1993}
1994
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001995void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001996 std::shared_ptr<Codec2Client::Component> comp;
1997 auto checkState = [this, &comp] {
1998 Mutexed<State>::Locked state(mState);
1999 if (state->get() == RELEASED) {
2000 return INVALID_OPERATION;
2001 }
2002 comp = state->comp;
2003 return OK;
2004 };
2005 if (tryAndReportOnError(checkState) != OK) {
2006 return;
2007 }
2008
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002009 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2010 // the behavior here.
2011 sp<AMessage> params = msg;
2012 int32_t bitrate;
2013 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2014 params = msg->dup();
2015 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2016 }
2017
Houxiang Dai5a97b472021-03-22 17:56:04 +08002018 int32_t syncId = 0;
2019 if (params->findInt32("audio-hw-sync", &syncId)
2020 || params->findInt32("hw-av-sync-id", &syncId)) {
2021 configureTunneledVideoPlayback(comp, nullptr, params);
2022 }
2023
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002024 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2025 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002026
2027 /**
2028 * Handle input surface parameters
2029 */
2030 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002031 && (config->mDomain & Config::IS_ENCODER)
2032 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002033 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002034
2035 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2036 config->mISConfig->mStopped = false;
2037 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2038 config->mISConfig->mStopped = true;
2039 }
2040
2041 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002042 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002043 config->mISConfig->mSuspended = value;
2044 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002045 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002046 }
2047
2048 (void)config->mInputSurface->configure(*config->mISConfig);
2049 if (config->mISConfig->mStopped) {
2050 config->mInputFormat->setInt64(
2051 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2052 }
2053 }
2054
2055 std::vector<std::unique_ptr<C2Param>> configUpdate;
2056 (void)config->getConfigUpdateFromSdkParams(
2057 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2058 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2059 // Parameter synchronization is not defined when using input surface. For now, route
2060 // these directly to the component.
2061 if (config->mInputSurface == nullptr
2062 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2063 || comp->getName().find("c2.android.") == 0)) {
2064 mChannel->setParameters(configUpdate);
2065 } else {
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002066 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002067 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim3b4349a2020-11-10 11:54:15 -08002068 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002069 }
2070}
2071
2072void CCodec::signalEndOfInputStream() {
2073 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2074}
2075
2076void CCodec::signalRequestIDRFrame() {
2077 std::shared_ptr<Codec2Client::Component> comp;
2078 {
2079 Mutexed<State>::Locked state(mState);
2080 if (state->get() == RELEASED) {
2081 ALOGD("no IDR request sent since component is released");
2082 return;
2083 }
2084 comp = state->comp;
2085 }
2086 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002087 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2088 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002089 std::vector<std::unique_ptr<C2Param>> params;
2090 params.push_back(
2091 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2092 config->setParameters(comp, params, C2_MAY_BLOCK);
2093}
2094
Wonsik Kim874ad382021-03-12 09:59:36 -08002095status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2096 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2097 const std::unique_ptr<Config> &config = *configLocked;
2098 return config->querySupportedParameters(names);
2099}
2100
2101status_t CCodec::describeParameter(
2102 const std::string &name, CodecParameterDescriptor *desc) {
2103 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2104 const std::unique_ptr<Config> &config = *configLocked;
2105 return config->describe(name, desc);
2106}
2107
2108status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2109 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2110 if (!comp) {
2111 return INVALID_OPERATION;
2112 }
2113 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2114 const std::unique_ptr<Config> &config = *configLocked;
2115 return config->subscribeToVendorConfigUpdate(comp, names);
2116}
2117
2118status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2119 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2120 if (!comp) {
2121 return INVALID_OPERATION;
2122 }
2123 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2124 const std::unique_ptr<Config> &config = *configLocked;
2125 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2126}
2127
Wonsik Kimab34ed62019-01-31 15:28:46 -08002128void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002129 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002130 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2131 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002132 }
2133 (new AMessage(kWhatWorkDone, this))->post();
2134}
2135
Wonsik Kimab34ed62019-01-31 15:28:46 -08002136void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2137 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002138 if (arrayIndex == 0) {
2139 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002140 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2141 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002142 if (config->mInputSurface) {
2143 config->mInputSurface->onInputBufferDone(frameIndex);
2144 }
2145 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002146}
2147
2148void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2149 TimePoint now = std::chrono::steady_clock::now();
2150 CCodecWatchdog::getInstance()->watch(this);
2151 switch (msg->what()) {
2152 case kWhatAllocate: {
2153 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002154 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002155 sp<RefBase> obj;
2156 CHECK(msg->findObject("codecInfo", &obj));
2157 allocate((MediaCodecInfo *)obj.get());
2158 break;
2159 }
2160 case kWhatConfigure: {
2161 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002162 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002163 sp<AMessage> format;
2164 CHECK(msg->findMessage("format", &format));
2165 configure(format);
2166 break;
2167 }
2168 case kWhatStart: {
2169 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002170 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002171 start();
2172 break;
2173 }
2174 case kWhatStop: {
2175 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002176 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002177 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002178 break;
2179 }
2180 case kWhatFlush: {
2181 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002182 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002183 flush();
2184 break;
2185 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002186 case kWhatRelease: {
2187 mChannel->release();
2188 mClient.reset();
2189 mClientListener.reset();
2190 break;
2191 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002192 case kWhatCreateInputSurface: {
2193 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002194 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002195 createInputSurface();
2196 break;
2197 }
2198 case kWhatSetInputSurface: {
2199 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002200 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002201 sp<RefBase> obj;
2202 CHECK(msg->findObject("surface", &obj));
2203 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2204 setInputSurface(surface);
2205 break;
2206 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002207 case kWhatWorkDone: {
2208 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002209 bool shouldPost = false;
2210 {
2211 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2212 if (queue->empty()) {
2213 break;
2214 }
2215 work.swap(queue->front());
2216 queue->pop_front();
2217 shouldPost = !queue->empty();
2218 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002219 if (shouldPost) {
2220 (new AMessage(kWhatWorkDone, this))->post();
2221 }
2222
Pawin Vongmasa36653902018-11-15 00:10:25 -08002223 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002224 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002225 sp<AMessage> outputFormat = nullptr;
2226 {
2227 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2228 const std::unique_ptr<Config> &config = *configLocked;
2229 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2230 config->watch<C2StreamInitDataInfo::output>();
2231 if (!work->worklets.empty()
2232 && (work->worklets.front()->output.flags
2233 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002234
Wonsik Kim75e22f42021-04-14 23:34:51 -07002235 // copy buffer info to config
2236 std::vector<std::unique_ptr<C2Param>> updates;
2237 for (const std::unique_ptr<C2Param> &param
2238 : work->worklets.front()->output.configUpdate) {
2239 updates.push_back(C2Param::Copy(*param));
2240 }
2241 unsigned stream = 0;
2242 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2243 work->worklets.front()->output.buffers;
2244 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2245 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2246 // move all info into output-stream #0 domain
2247 updates.emplace_back(
2248 C2Param::CopyAsStream(*info, true /* output */, stream));
2249 }
2250
2251 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2252 // for now only do the first block
2253 if (!blocks.empty()) {
2254 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2255 // block.crop().left, block.crop().top,
2256 // block.crop().width, block.crop().height,
2257 // block.width(), block.height());
2258 const C2ConstGraphicBlock &block = blocks[0];
2259 updates.emplace_back(new C2StreamCropRectInfo::output(
2260 stream, block.crop()));
2261 updates.emplace_back(new C2StreamPictureSizeInfo::output(
2262 stream, block.crop().width, block.crop().height));
2263 }
2264 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002265 }
George Burgess IVc813a592020-02-22 22:54:44 -08002266
Wonsik Kim75e22f42021-04-14 23:34:51 -07002267 sp<AMessage> oldFormat = config->mOutputFormat;
2268 config->updateConfiguration(updates, config->mOutputDomain);
2269 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002270
Wonsik Kim75e22f42021-04-14 23:34:51 -07002271 // copy standard infos to graphic buffers if not already present (otherwise, we
2272 // may overwrite the actual intermediate value with a final value)
2273 stream = 0;
2274 const static C2Param::Index stdGfxInfos[] = {
2275 C2StreamRotationInfo::output::PARAM_TYPE,
2276 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2277 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2278 C2StreamHdrStaticInfo::output::PARAM_TYPE,
2279 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
2280 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2281 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2282 };
2283 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2284 if (buf->data().graphicBlocks().size()) {
2285 for (C2Param::Index ix : stdGfxInfos) {
2286 if (!buf->hasInfo(ix)) {
2287 const C2Param *param =
2288 config->getConfigParameterValue(ix.withStream(stream));
2289 if (param) {
2290 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2291 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2292 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002293 }
2294 }
2295 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002296 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002297 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002298 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002299 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302300 if (work->worklets.empty()
2301 || !work->worklets.back()
2302 || (work->worklets.back()->output.flags
2303 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2304 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2305 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002306 }
2307 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002308 initData = initDataWatcher.update();
2309 AmendOutputFormatWithCodecSpecificData(
2310 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2311 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002312 }
2313 outputFormat = config->mOutputFormat;
Wonsik Kim9c387412021-04-19 21:03:53 +00002314 }
2315 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002316 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002317 break;
2318 }
2319 case kWhatWatch: {
2320 // watch message already posted; no-op.
2321 break;
2322 }
2323 default: {
2324 ALOGE("unrecognized message");
2325 break;
2326 }
2327 }
2328 setDeadline(TimePoint::max(), 0ms, "none");
2329}
2330
2331void CCodec::setDeadline(
2332 const TimePoint &now,
2333 const std::chrono::milliseconds &timeout,
2334 const char *name) {
2335 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2336 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2337 deadline->set(now + (timeout * mult), name);
2338}
2339
ted.sun765db4d2020-06-23 14:03:41 +08002340status_t CCodec::configureTunneledVideoPlayback(
2341 std::shared_ptr<Codec2Client::Component> comp,
2342 sp<NativeHandle> *sidebandHandle,
2343 const sp<AMessage> &msg) {
2344 std::vector<std::unique_ptr<C2SettingResult>> failures;
2345
2346 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2347 C2PortTunneledModeTuning::output::AllocUnique(
2348 1,
2349 C2PortTunneledModeTuning::Struct::SIDEBAND,
2350 C2PortTunneledModeTuning::Struct::REALTIME,
2351 0);
2352 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2353 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2354 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2355 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2356 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2357 } else {
2358 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2359 tunneledPlayback->setFlexCount(0);
2360 }
2361 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2362 if (c2err != C2_OK) {
2363 return UNKNOWN_ERROR;
2364 }
2365
Houxiang Dai5a97b472021-03-22 17:56:04 +08002366 if (sidebandHandle == nullptr) {
2367 return OK;
2368 }
2369
ted.sun765db4d2020-06-23 14:03:41 +08002370 std::vector<std::unique_ptr<C2Param>> params;
2371 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2372 if (c2err == C2_OK && params.size() == 1u) {
2373 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2374 C2PortTunnelHandleTuning::output::From(params[0].get());
2375 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2376 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2377 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2378 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2379 memcpy(handle->data, videoTunnelSideband->m.values,
2380 sizeof(int32_t) * videoTunnelSideband->flexCount());
2381 return OK;
2382 } else {
2383 return NO_MEMORY;
2384 }
2385 }
2386 return UNKNOWN_ERROR;
2387}
2388
Pawin Vongmasa36653902018-11-15 00:10:25 -08002389void CCodec::initiateReleaseIfStuck() {
2390 std::string name;
2391 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002392 {
2393 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002394 if (deadline->get() < std::chrono::steady_clock::now()) {
2395 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002396 }
2397 if (deadline->get() != TimePoint::max()) {
2398 pendingDeadline = true;
2399 }
2400 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002401 bool tunneled = false;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002402 bool isMediaTypeKnown = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002403 {
Wonsik Kimabca11e2021-04-30 13:11:41 -07002404 static const std::set<std::string> kKnownMediaTypes{
2405 MIMETYPE_VIDEO_VP8,
2406 MIMETYPE_VIDEO_VP9,
2407 MIMETYPE_VIDEO_AV1,
2408 MIMETYPE_VIDEO_AVC,
2409 MIMETYPE_VIDEO_HEVC,
2410 MIMETYPE_VIDEO_MPEG4,
2411 MIMETYPE_VIDEO_H263,
2412 MIMETYPE_VIDEO_MPEG2,
2413 MIMETYPE_VIDEO_RAW,
2414 MIMETYPE_VIDEO_DOLBY_VISION,
2415
2416 MIMETYPE_AUDIO_AMR_NB,
2417 MIMETYPE_AUDIO_AMR_WB,
2418 MIMETYPE_AUDIO_MPEG,
2419 MIMETYPE_AUDIO_AAC,
2420 MIMETYPE_AUDIO_QCELP,
2421 MIMETYPE_AUDIO_VORBIS,
2422 MIMETYPE_AUDIO_OPUS,
2423 MIMETYPE_AUDIO_G711_ALAW,
2424 MIMETYPE_AUDIO_G711_MLAW,
2425 MIMETYPE_AUDIO_RAW,
2426 MIMETYPE_AUDIO_FLAC,
2427 MIMETYPE_AUDIO_MSGSM,
2428 MIMETYPE_AUDIO_AC3,
2429 MIMETYPE_AUDIO_EAC3,
2430
2431 MIMETYPE_IMAGE_ANDROID_HEIC,
2432 };
Wonsik Kim75e22f42021-04-14 23:34:51 -07002433 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2434 const std::unique_ptr<Config> &config = *configLocked;
2435 tunneled = config->mTunneled;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002436 isMediaTypeKnown = (kKnownMediaTypes.count(config->mCodingMediaType) != 0);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002437 }
Wonsik Kimabca11e2021-04-30 13:11:41 -07002438 if (!tunneled && isMediaTypeKnown && name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002439 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2440 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2441 if (elapsed >= kWorkDurationThreshold) {
2442 name = "queue";
2443 }
2444 if (elapsed > 0s) {
2445 pendingDeadline = true;
2446 }
2447 }
2448 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002449 // We're not stuck.
2450 if (pendingDeadline) {
2451 // If we are not stuck yet but still has deadline coming up,
2452 // post watch message to check back later.
2453 (new AMessage(kWhatWatch, this))->post();
2454 }
2455 return;
2456 }
2457
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002458 C2String compName;
2459 {
2460 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002461 if (!state->comp) {
2462 ALOGD("previous call to %s exceeded timeout "
2463 "and the component is already released", name.c_str());
2464 return;
2465 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002466 compName = state->comp->getName();
2467 }
2468 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2469
Pawin Vongmasa36653902018-11-15 00:10:25 -08002470 initiateRelease(false);
2471 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2472}
2473
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002474// static
2475PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002476 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002477 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002478 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002479 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2480 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002481 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002482 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2483 sp<IGraphicBufferProducer> gbp;
2484 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2485 status_t err = gbs->initCheck();
2486 if (err != OK) {
2487 ALOGE("Failed to create persistent input surface: error %d", err);
2488 return nullptr;
2489 }
2490 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002491 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002492 } else {
2493 return nullptr;
2494 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002495 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002496 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002497 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002498 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002499 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002500}
2501
Wonsik Kimffb889a2020-05-28 11:32:25 -07002502class IntfCache {
2503public:
2504 IntfCache() = default;
2505
2506 status_t init(const std::string &name) {
2507 std::shared_ptr<Codec2Client::Interface> intf{
2508 Codec2Client::CreateInterfaceByName(name.c_str())};
2509 if (!intf) {
2510 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2511 mInitStatus = NO_INIT;
2512 return NO_INIT;
2513 }
2514 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2515 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2516 C2ParamField{&sUsage, &sUsage.value}));
2517 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2518 if (err != C2_OK) {
2519 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2520 name.c_str(), err);
2521 mFields[0].status = err;
2522 }
2523 std::vector<std::unique_ptr<C2Param>> params;
2524 err = intf->query(
2525 {&mApiFeatures},
2526 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2527 C2_MAY_BLOCK,
2528 &params);
2529 if (err != C2_OK && err != C2_BAD_INDEX) {
2530 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2531 name.c_str(), err);
2532 }
2533 while (!params.empty()) {
2534 C2Param *param = params.back().release();
2535 params.pop_back();
2536 if (!param) {
2537 continue;
2538 }
2539 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2540 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002541 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002542 }
2543 }
2544 mInitStatus = OK;
2545 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002546 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002547
2548 status_t initCheck() const { return mInitStatus; }
2549
2550 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2551 CHECK_EQ(1u, mFields.size());
2552 return mFields[0];
2553 }
2554
2555 const C2ApiFeaturesSetting &getApiFeatures() const {
2556 return mApiFeatures;
2557 }
2558
2559 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2560 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2561 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2562 C2PortAllocatorsTuning::input::AllocUnique(0);
2563 param->invalidate();
2564 return param;
2565 }();
2566 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2567 }
2568
2569private:
2570 status_t mInitStatus{NO_INIT};
2571
2572 std::vector<C2FieldSupportedValuesQuery> mFields;
2573 C2ApiFeaturesSetting mApiFeatures;
2574 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2575};
2576
2577static const IntfCache &GetIntfCache(const std::string &name) {
2578 static IntfCache sNullIntfCache;
2579 static std::mutex sMutex;
2580 static std::map<std::string, IntfCache> sCache;
2581 std::unique_lock<std::mutex> lock{sMutex};
2582 auto it = sCache.find(name);
2583 if (it == sCache.end()) {
2584 lock.unlock();
2585 IntfCache intfCache;
2586 status_t err = intfCache.init(name);
2587 if (err != OK) {
2588 return sNullIntfCache;
2589 }
2590 lock.lock();
2591 it = sCache.insert({name, std::move(intfCache)}).first;
2592 }
2593 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002594}
2595
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002596static status_t GetCommonAllocatorIds(
2597 const std::vector<std::string> &names,
2598 C2Allocator::type_t type,
2599 std::set<C2Allocator::id_t> *ids) {
2600 int poolMask = GetCodec2PoolMask();
2601 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2602 C2Allocator::id_t defaultAllocatorId =
2603 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2604
2605 ids->clear();
2606 if (names.empty()) {
2607 return OK;
2608 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002609 bool firstIteration = true;
2610 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002611 const IntfCache &intfCache = GetIntfCache(name);
2612 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002613 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002614 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002615 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002616 if (firstIteration) {
2617 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002618 if (allocators && allocators.flexCount() > 0) {
2619 ids->insert(allocators.m.values,
2620 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002621 }
2622 if (ids->empty()) {
2623 // The component does not advertise allocators. Use default.
2624 ids->insert(defaultAllocatorId);
2625 }
2626 continue;
2627 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002628 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002629 if (allocators && allocators.flexCount() > 0) {
2630 filtered = true;
2631 for (auto it = ids->begin(); it != ids->end(); ) {
2632 bool found = false;
2633 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2634 if (allocators.m.values[j] == *it) {
2635 found = true;
2636 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002637 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002638 }
2639 if (found) {
2640 ++it;
2641 } else {
2642 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002643 }
2644 }
2645 }
2646 if (!filtered) {
2647 // The component does not advertise supported allocators. Use default.
2648 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2649 if (ids->size() != (containsDefault ? 1 : 0)) {
2650 ids->clear();
2651 if (containsDefault) {
2652 ids->insert(defaultAllocatorId);
2653 }
2654 }
2655 }
2656 }
2657 // Finally, filter with pool masks
2658 for (auto it = ids->begin(); it != ids->end(); ) {
2659 if ((poolMask >> *it) & 1) {
2660 ++it;
2661 } else {
2662 it = ids->erase(it);
2663 }
2664 }
2665 return OK;
2666}
2667
2668static status_t CalculateMinMaxUsage(
2669 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2670 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2671 *minUsage = 0;
2672 *maxUsage = ~0ull;
2673 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002674 const IntfCache &intfCache = GetIntfCache(name);
2675 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002676 continue;
2677 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002678 const C2FieldSupportedValuesQuery &usageSupportedValues =
2679 intfCache.getUsageSupportedValues();
2680 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002681 continue;
2682 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002683 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002684 if (supported.type != C2FieldSupportedValues::FLAGS) {
2685 continue;
2686 }
2687 if (supported.values.empty()) {
2688 *maxUsage = 0;
2689 continue;
2690 }
2691 *minUsage |= supported.values[0].u64;
2692 int64_t currentMaxUsage = 0;
2693 for (const C2Value::Primitive &flags : supported.values) {
2694 currentMaxUsage |= flags.u64;
2695 }
2696 *maxUsage &= currentMaxUsage;
2697 }
2698 return OK;
2699}
2700
2701// static
2702status_t CCodec::CanFetchLinearBlock(
2703 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002704 for (const std::string &name : names) {
2705 const IntfCache &intfCache = GetIntfCache(name);
2706 if (intfCache.initCheck() != OK) {
2707 continue;
2708 }
2709 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2710 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2711 *isCompatible = false;
2712 return OK;
2713 }
2714 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002715 std::set<C2Allocator::id_t> allocators;
2716 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2717 if (allocators.empty()) {
2718 *isCompatible = false;
2719 return OK;
2720 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002721
2722 uint64_t minUsage = 0;
2723 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002724 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002725 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002726 *isCompatible = ((maxUsage & minUsage) == minUsage);
2727 return OK;
2728}
2729
2730static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2731 static std::mutex sMutex{};
2732 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2733 std::unique_lock<std::mutex> lock{sMutex};
2734 std::shared_ptr<C2BlockPool> pool;
2735 auto it = sPools.find(allocId);
2736 if (it == sPools.end()) {
2737 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2738 if (err == OK) {
2739 sPools.emplace(allocId, pool);
2740 } else {
2741 pool.reset();
2742 }
2743 } else {
2744 pool = it->second;
2745 }
2746 return pool;
2747}
2748
2749// static
2750std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2751 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002752 std::set<C2Allocator::id_t> allocators;
2753 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2754 if (allocators.empty()) {
2755 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2756 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002757
2758 uint64_t minUsage = 0;
2759 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002760 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002761 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002762 if ((maxUsage & minUsage) != minUsage) {
2763 allocators.clear();
2764 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2765 }
2766 std::shared_ptr<C2LinearBlock> block;
2767 for (C2Allocator::id_t allocId : allocators) {
2768 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2769 if (!pool) {
2770 continue;
2771 }
2772 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2773 if (err != C2_OK || !block) {
2774 block.reset();
2775 continue;
2776 }
2777 break;
2778 }
2779 return block;
2780}
2781
2782// static
2783status_t CCodec::CanFetchGraphicBlock(
2784 const std::vector<std::string> &names, bool *isCompatible) {
2785 uint64_t minUsage = 0;
2786 uint64_t maxUsage = ~0ull;
2787 std::set<C2Allocator::id_t> allocators;
2788 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2789 if (allocators.empty()) {
2790 *isCompatible = false;
2791 return OK;
2792 }
2793 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2794 *isCompatible = ((maxUsage & minUsage) == minUsage);
2795 return OK;
2796}
2797
2798// static
2799std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2800 int32_t width,
2801 int32_t height,
2802 int32_t format,
2803 uint64_t usage,
2804 const std::vector<std::string> &names) {
2805 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2806 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2807 ALOGD("Unrecognized pixel format: %d", format);
2808 return nullptr;
2809 }
2810 uint64_t minUsage = 0;
2811 uint64_t maxUsage = ~0ull;
2812 std::set<C2Allocator::id_t> allocators;
2813 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2814 if (allocators.empty()) {
2815 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2816 }
2817 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2818 minUsage |= usage;
2819 if ((maxUsage & minUsage) != minUsage) {
2820 allocators.clear();
2821 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2822 }
2823 std::shared_ptr<C2GraphicBlock> block;
2824 for (C2Allocator::id_t allocId : allocators) {
2825 std::shared_ptr<C2BlockPool> pool;
2826 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2827 if (err != C2_OK || !pool) {
2828 continue;
2829 }
2830 err = pool->fetchGraphicBlock(
2831 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2832 if (err != C2_OK || !block) {
2833 block.reset();
2834 continue;
2835 }
2836 break;
2837 }
2838 return block;
2839}
2840
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002841} // namespace android