blob: cb2924323b52adb0555d765812898b15a1936343 [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 Kim970bf0b2020-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 Kim970bf0b2020-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 Kim970bf0b2020-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
Guillaume Chelfi867d4dd2021-07-01 18:38:45 +0200676 void onFirstTunnelFrameReady() override {
677 mCodec->mCallback->onFirstTunnelFrameReady();
678 }
679
Pawin Vongmasa36653902018-11-15 00:10:25 -0800680private:
681 CCodec *mCodec;
682};
683
684// CCodec
685
686CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700687 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
688 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800689}
690
691CCodec::~CCodec() {
692}
693
694std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
695 return mChannel;
696}
697
698status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
699 status_t err = job();
700 if (err != C2_OK) {
701 mCallback->onError(err, ACTION_CODE_FATAL);
702 }
703 return err;
704}
705
706void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
707 auto setAllocating = [this] {
708 Mutexed<State>::Locked state(mState);
709 if (state->get() != RELEASED) {
710 return INVALID_OPERATION;
711 }
712 state->set(ALLOCATING);
713 return OK;
714 };
715 if (tryAndReportOnError(setAllocating) != OK) {
716 return;
717 }
718
719 sp<RefBase> codecInfo;
720 CHECK(msg->findObject("codecInfo", &codecInfo));
721 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
722
723 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
724 allocMsg->setObject("codecInfo", codecInfo);
725 allocMsg->post();
726}
727
728void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
729 if (codecInfo == nullptr) {
730 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
731 return;
732 }
733 ALOGD("allocate(%s)", codecInfo->getCodecName());
734 mClientListener.reset(new ClientListener(this));
735
736 AString componentName = codecInfo->getCodecName();
737 std::shared_ptr<Codec2Client> client;
738
739 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700740 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800741 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800742 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800743 SetPreferredCodec2ComponentStore(
744 std::make_shared<Codec2ClientInterfaceWrapper>(client));
745 }
746
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900747 std::shared_ptr<Codec2Client::Component> comp;
748 c2_status_t status = Codec2Client::CreateComponentByName(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800749 componentName.c_str(),
750 mClientListener,
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900751 &comp,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800752 &client);
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900753 if (status != C2_OK) {
754 ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800755 Mutexed<State>::Locked state(mState);
756 state->set(RELEASED);
757 state.unlock();
Chih-Yu Huangb8fe0792020-12-07 17:14:55 +0900758 mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800759 state.lock();
760 return;
761 }
762 ALOGI("Created component [%s]", componentName.c_str());
763 mChannel->setComponent(comp);
764 auto setAllocated = [this, comp, client] {
765 Mutexed<State>::Locked state(mState);
766 if (state->get() != ALLOCATING) {
767 state->set(RELEASED);
768 return UNKNOWN_ERROR;
769 }
770 state->set(ALLOCATED);
771 state->comp = comp;
772 mClient = client;
773 return OK;
774 };
775 if (tryAndReportOnError(setAllocated) != OK) {
776 return;
777 }
778
779 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700780 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
781 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800782 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800783 if (err != OK) {
784 ALOGW("Failed to initialize configuration support");
785 // TODO: report error once we complete implementation.
786 }
787 config->queryConfiguration(comp);
788
789 mCallback->onComponentAllocated(componentName.c_str());
790}
791
792void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
793 auto checkAllocated = [this] {
794 Mutexed<State>::Locked state(mState);
795 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
796 };
797 if (tryAndReportOnError(checkAllocated) != OK) {
798 return;
799 }
800
801 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
802 msg->setMessage("format", format);
803 msg->post();
804}
805
806void CCodec::configure(const sp<AMessage> &msg) {
807 std::shared_ptr<Codec2Client::Component> comp;
808 auto checkAllocated = [this, &comp] {
809 Mutexed<State>::Locked state(mState);
810 if (state->get() != ALLOCATED) {
811 state->set(RELEASED);
812 return UNKNOWN_ERROR;
813 }
814 comp = state->comp;
815 return OK;
816 };
817 if (tryAndReportOnError(checkAllocated) != OK) {
818 return;
819 }
820
821 auto doConfig = [msg, comp, this]() -> status_t {
822 AString mime;
823 if (!msg->findString("mime", &mime)) {
824 return BAD_VALUE;
825 }
826
827 int32_t encoder;
828 if (!msg->findInt32("encoder", &encoder)) {
829 encoder = false;
830 }
831
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800832 int32_t flags;
833 if (!msg->findInt32("flags", &flags)) {
834 return BAD_VALUE;
835 }
836
Pawin Vongmasa36653902018-11-15 00:10:25 -0800837 // TODO: read from intf()
838 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
839 return UNKNOWN_ERROR;
840 }
841
842 int32_t storeMeta;
843 if (encoder
844 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
845 && storeMeta != kMetadataBufferTypeInvalid) {
846 if (storeMeta != kMetadataBufferTypeANWBuffer) {
847 ALOGD("Only ANW buffers are supported for legacy metadata mode");
848 return BAD_VALUE;
849 }
850 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
851 }
852
ted.sun765db4d2020-06-23 14:03:41 +0800853 status_t err = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800854 sp<RefBase> obj;
855 sp<Surface> surface;
856 if (msg->findObject("native-window", &obj)) {
857 surface = static_cast<Surface *>(obj.get());
ted.sun765db4d2020-06-23 14:03:41 +0800858 // setup tunneled playback
859 if (surface != nullptr) {
860 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
861 const std::unique_ptr<Config> &config = *configLocked;
862 if ((config->mDomain & Config::IS_DECODER)
863 && (config->mDomain & Config::IS_VIDEO)) {
864 int32_t tunneled;
865 if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
866 ALOGI("Configuring TUNNELED video playback.");
867
868 err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
869 if (err != OK) {
870 ALOGE("configureTunneledVideoPlayback failed!");
871 return err;
872 }
873 config->mTunneled = true;
874 }
875 }
876 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800877 setSurface(surface);
878 }
879
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700880 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
881 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800882 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800883 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
884 ALOGD("[%s] buffers are %sbound to CCodec for this session",
885 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800886
Wonsik Kim1114eea2019-02-25 14:35:24 -0800887 // Enforce required parameters
888 int32_t i32;
889 float flt;
890 if (config->mDomain & Config::IS_AUDIO) {
891 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
892 ALOGD("sample rate is missing, which is required for audio components.");
893 return BAD_VALUE;
894 }
895 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
896 ALOGD("channel count is missing, which is required for audio components.");
897 return BAD_VALUE;
898 }
899 if ((config->mDomain & Config::IS_ENCODER)
900 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
901 && !msg->findInt32(KEY_BIT_RATE, &i32)
902 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
903 ALOGD("bitrate is missing, which is required for audio encoders.");
904 return BAD_VALUE;
905 }
906 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800907 int32_t width = 0;
908 int32_t height = 0;
Wonsik Kim1114eea2019-02-25 14:35:24 -0800909 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800910 if (!msg->findInt32(KEY_WIDTH, &width)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800911 ALOGD("width is missing, which is required for image/video components.");
912 return BAD_VALUE;
913 }
Wonsik Kimd91f3fb2021-02-24 12:35:31 -0800914 if (!msg->findInt32(KEY_HEIGHT, &height)) {
Wonsik Kim1114eea2019-02-25 14:35:24 -0800915 ALOGD("height is missing, which is required for image/video components.");
916 return BAD_VALUE;
917 }
918 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700919 int32_t mode = BITRATE_MODE_VBR;
920 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700921 if (!msg->findInt32(KEY_QUALITY, &i32)) {
922 ALOGD("quality is missing, which is required for video encoders in CQ.");
923 return BAD_VALUE;
924 }
925 } else {
926 if (!msg->findInt32(KEY_BIT_RATE, &i32)
927 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
928 ALOGD("bitrate is missing, which is required for video encoders.");
929 return BAD_VALUE;
930 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800931 }
932 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
933 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
934 ALOGD("I frame interval is missing, which is required for video encoders.");
935 return BAD_VALUE;
936 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700937 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
938 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
939 ALOGD("frame rate is missing, which is required for video encoders.");
940 return BAD_VALUE;
941 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800942 }
943 }
944
Pawin Vongmasa36653902018-11-15 00:10:25 -0800945 /*
946 * Handle input surface configuration
947 */
948 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
949 && (config->mDomain & Config::IS_ENCODER)) {
950 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
951 {
952 config->mISConfig->mMinFps = 0;
953 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800954 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800955 config->mISConfig->mMinFps = 1e6 / value;
956 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700957 if (!msg->findFloat(
958 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
959 config->mISConfig->mMaxFps = -1;
960 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800961 config->mISConfig->mMinAdjustedFps = 0;
962 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800963 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800964 if (value < 0 && value >= INT32_MIN) {
965 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700966 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800967 } else if (value > 0 && value <= INT32_MAX) {
968 config->mISConfig->mMinAdjustedFps = 1e6 / value;
969 }
970 }
971 }
972
973 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700974 bool captureFpsFound = false;
975 double timeLapseFps;
976 float captureRate;
977 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
978 config->mISConfig->mCaptureFps = timeLapseFps;
979 captureFpsFound = true;
980 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
981 config->mISConfig->mCaptureFps = captureRate;
982 captureFpsFound = true;
983 }
984 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800985 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
986 }
987 }
988
989 {
990 config->mISConfig->mSuspended = false;
991 config->mISConfig->mSuspendAtUs = -1;
992 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800993 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800994 config->mISConfig->mSuspended = true;
995 }
996 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700997 config->mISConfig->mUsage = 0;
Wonsik Kima1335e12021-04-22 16:28:29 -0700998 config->mISConfig->mPriority = INT_MAX;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800999 }
1000
1001 /*
1002 * Handle desired color format.
1003 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001004 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001005 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001006 int32_t format = 0;
1007 // Query vendor format for Flexible YUV
1008 std::vector<std::unique_ptr<C2Param>> heapParams;
1009 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
1010 if (mClient->query(
1011 {},
1012 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1013 C2_MAY_BLOCK,
1014 &heapParams) == C2_OK
1015 && heapParams.size() == 1u) {
1016 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1017 heapParams[0].get());
1018 } else {
1019 pixelFormatInfo = nullptr;
1020 }
1021 std::optional<uint32_t> flexPixelFormat{};
1022 std::optional<uint32_t> flexPlanarPixelFormat{};
1023 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
1024 if (pixelFormatInfo && *pixelFormatInfo) {
1025 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1026 const C2FlexiblePixelFormatDescriptorStruct &desc =
1027 pixelFormatInfo->m.values[i];
1028 if (desc.bitDepth != 8
1029 || desc.subsampling != C2Color::YUV_420
1030 // TODO(b/180076105): some device report wrong layout
1031 // || desc.layout == C2Color::INTERLEAVED_PACKED
1032 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1033 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1034 continue;
1035 }
1036 if (!flexPixelFormat) {
1037 flexPixelFormat = desc.pixelFormat;
1038 }
1039 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
1040 flexPlanarPixelFormat = desc.pixelFormat;
1041 }
1042 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
1043 flexSemiPlanarPixelFormat = desc.pixelFormat;
1044 }
1045 }
1046 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001047 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001048 // Also handle default color format (encoders require color format, so this is only
1049 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -08001050 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001051 if (surface == nullptr) {
Wonsik Kim1eb88a92021-03-29 20:44:04 -07001052 const char *prefix = "";
1053 if (flexSemiPlanarPixelFormat) {
1054 format = COLOR_FormatYUV420SemiPlanar;
1055 prefix = "semi-";
1056 } else {
1057 format = COLOR_FormatYUV420Planar;
1058 }
1059 ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1060 "using default %splanar color format", prefix);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001061 } else {
1062 format = COLOR_FormatSurface;
1063 }
1064 defaultColorFormat = format;
1065 }
1066 } else {
1067 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
1068 switch (format) {
1069 case COLOR_FormatYUV420Flexible:
1070 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
1071 break;
1072 case COLOR_FormatYUV420Planar:
1073 case COLOR_FormatYUV420PackedPlanar:
1074 format = flexPlanarPixelFormat.value_or(
1075 flexPixelFormat.value_or(format));
1076 break;
1077 case COLOR_FormatYUV420SemiPlanar:
1078 case COLOR_FormatYUV420PackedSemiPlanar:
1079 format = flexSemiPlanarPixelFormat.value_or(
1080 flexPixelFormat.value_or(format));
1081 break;
1082 default:
1083 // No-op
1084 break;
1085 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001086 }
1087 }
1088
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001089 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001090 msg->setInt32("android._color-format", format);
1091 }
1092 }
1093
Wonsik Kim77e97c72021-01-20 10:33:22 -08001094 /*
1095 * Handle dataspace
1096 */
1097 int32_t usingRecorder;
1098 if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1099 android_dataspace dataSpace = HAL_DATASPACE_BT709;
1100 int32_t width, height;
1101 if (msg->findInt32("width", &width)
1102 && msg->findInt32("height", &height)) {
Wonsik Kim4f13d112021-03-17 04:37:46 +00001103 ColorAspects aspects;
1104 getColorAspectsFromFormat(msg, aspects);
1105 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001106 // TODO: read dataspace / color aspect from the component
Wonsik Kim4f13d112021-03-17 04:37:46 +00001107 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1108 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
Wonsik Kim77e97c72021-01-20 10:33:22 -08001109 }
1110 msg->setInt32("android._dataspace", (int32_t)dataSpace);
1111 ALOGD("setting dataspace to %x", dataSpace);
1112 }
1113
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001114 int32_t subscribeToAllVendorParams;
1115 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1116 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1117 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1118 }
1119 }
1120
Pawin Vongmasa36653902018-11-15 00:10:25 -08001121 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001122 // NOTE: We used to ignore "video-bitrate" at configure; replicate
1123 // the behavior here.
1124 sp<AMessage> sdkParams = msg;
1125 int32_t videoBitrate;
1126 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1127 sdkParams = msg->dup();
1128 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1129 }
ted.sun765db4d2020-06-23 14:03:41 +08001130 err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001131 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001132 if (err != OK) {
1133 ALOGW("failed to convert configuration to c2 params");
1134 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -07001135
1136 int32_t maxBframes = 0;
1137 if ((config->mDomain & Config::IS_ENCODER)
1138 && (config->mDomain & Config::IS_VIDEO)
1139 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1140 && maxBframes > 0) {
1141 std::unique_ptr<C2StreamGopTuning::output> gop =
1142 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1143 gop->m.values[0] = { P_FRAME, UINT32_MAX };
1144 gop->m.values[1] = {
1145 C2Config::picture_type_t(P_FRAME | B_FRAME),
1146 uint32_t(maxBframes)
1147 };
1148 configUpdate.push_back(std::move(gop));
1149 }
1150
Ray Essicka9a724a2021-03-10 19:40:01 -08001151 if ((config->mDomain & Config::IS_ENCODER)
1152 && (config->mDomain & Config::IS_VIDEO)) {
1153 // we may not use all 3 of these entries
1154 std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1155 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1156 0u /* stream */);
1157
1158 int ix = 0;
1159
1160 int32_t iMax = INT32_MAX;
1161 int32_t iMin = INT32_MIN;
1162 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1163 (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1164 if (iMax != INT32_MAX || iMin != INT32_MIN) {
1165 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1166 }
1167
1168 int32_t pMax = INT32_MAX;
1169 int32_t pMin = INT32_MIN;
1170 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1171 (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1172 if (pMax != INT32_MAX || pMin != INT32_MIN) {
1173 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1174 }
1175
1176 int32_t bMax = INT32_MAX;
1177 int32_t bMin = INT32_MIN;
1178 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1179 (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1180 if (bMax != INT32_MAX || bMin != INT32_MIN) {
1181 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1182 }
1183
1184 // adjust to reflect actual use.
1185 qp->setFlexCount(ix);
1186
1187 configUpdate.push_back(std::move(qp));
1188 }
1189
Wonsik Kima1335e12021-04-22 16:28:29 -07001190 int32_t background = 0;
1191 if ((config->mDomain & Config::IS_VIDEO)
1192 && msg->findInt32("android._background-mode", &background)
1193 && background) {
1194 androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1195 if (config->mISConfig) {
1196 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1197 }
1198 }
1199
Pawin Vongmasa36653902018-11-15 00:10:25 -08001200 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1201 if (err != OK) {
1202 ALOGW("failed to configure c2 params");
1203 return err;
1204 }
1205
1206 std::vector<std::unique_ptr<C2Param>> params;
1207 C2StreamUsageTuning::input usage(0u, 0u);
1208 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001209 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001210
Wonsik Kim58d83332021-02-07 22:19:56 -08001211 C2Param::Index colorAspectsRequestIndex =
1212 C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001213 std::initializer_list<C2Param::Index> indices {
Wonsik Kim58d83332021-02-07 22:19:56 -08001214 colorAspectsRequestIndex.withStream(0u),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001215 };
1216 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001217 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001218 indices,
1219 C2_DONT_BLOCK,
1220 &params);
1221 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1222 ALOGE("Failed to query component interface: %d", c2err);
1223 return UNKNOWN_ERROR;
1224 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001225 if (usage) {
1226 if (usage.value & C2MemoryUsage::CPU_READ) {
1227 config->mInputFormat->setInt32("using-sw-read-often", true);
1228 }
1229 if (config->mISConfig) {
1230 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1231 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1232 }
Wonsik Kim666604a2020-05-14 16:57:49 -07001233 config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001234 }
1235
1236 // NOTE: we don't blindly use client specified input size if specified as clients
1237 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1238 // client specified size is only used to ask for bigger buffers than component suggested
1239 // size.
1240 int32_t clientInputSize = 0;
1241 bool clientSpecifiedInputSize =
1242 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1243 // TEMP: enforce minimum buffer size of 1MB for video decoders
1244 // and 16K / 4K for audio encoders/decoders
1245 if (maxInputSize.value == 0) {
1246 if (config->mDomain & Config::IS_AUDIO) {
1247 maxInputSize.value = encoder ? 16384 : 4096;
1248 } else if (!encoder) {
1249 maxInputSize.value = 1048576u;
1250 }
1251 }
1252
1253 // verify that CSD fits into this size (if defined)
1254 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1255 sp<ABuffer> csd;
1256 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1257 if (csd && csd->size() > maxInputSize.value) {
1258 maxInputSize.value = csd->size();
1259 }
1260 }
1261 }
1262
1263 // TODO: do this based on component requiring linear allocator for input
1264 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1265 if (clientSpecifiedInputSize) {
1266 // Warn that we're overriding client's max input size if necessary.
1267 if ((uint32_t)clientInputSize < maxInputSize.value) {
1268 ALOGD("client requested max input size %d, which is smaller than "
1269 "what component recommended (%u); overriding with component "
1270 "recommendation.", clientInputSize, maxInputSize.value);
1271 ALOGW("This behavior is subject to change. It is recommended that "
1272 "app developers double check whether the requested "
1273 "max input size is in reasonable range.");
1274 } else {
1275 maxInputSize.value = clientInputSize;
1276 }
1277 }
1278 // Pass max input size on input format to the buffer channel (if supplied by the
1279 // component or by a default)
1280 if (maxInputSize.value) {
1281 config->mInputFormat->setInt32(
1282 KEY_MAX_INPUT_SIZE,
1283 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1284 }
1285 }
1286
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001287 int32_t clientPrepend;
1288 if ((config->mDomain & Config::IS_VIDEO)
1289 && (config->mDomain & Config::IS_ENCODER)
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001290 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001291 && clientPrepend
1292 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
Lajos Molnara2b5f5a2020-10-14 16:36:18 -07001293 ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001294 return BAD_VALUE;
1295 }
1296
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001297 int32_t componentColorFormat = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001298 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1299 // propagate HDR static info to output format for both encoders and decoders
1300 // if component supports this info, we will update from component, but only the raw port,
1301 // so don't propagate if component already filled it in.
1302 sp<ABuffer> hdrInfo;
1303 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1304 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1305 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1306 }
1307
1308 // Set desired color format from configuration parameter
1309 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001310 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1311 format = defaultColorFormat;
1312 }
1313 if (config->mDomain & Config::IS_ENCODER) {
1314 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001315 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1316 config->mInputFormat->setInt32("android._color-format", componentColorFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001317 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001318 } else {
1319 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001320 }
1321 }
1322
1323 // propagate encoder delay and padding to output format
1324 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1325 int delay = 0;
1326 if (msg->findInt32("encoder-delay", &delay)) {
1327 config->mOutputFormat->setInt32("encoder-delay", delay);
1328 }
1329 int padding = 0;
1330 if (msg->findInt32("encoder-padding", &padding)) {
1331 config->mOutputFormat->setInt32("encoder-padding", padding);
1332 }
1333 }
1334
Pawin Vongmasa36653902018-11-15 00:10:25 -08001335 if (config->mDomain & Config::IS_AUDIO) {
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001336 // set channel-mask
Pawin Vongmasa36653902018-11-15 00:10:25 -08001337 int32_t mask;
1338 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1339 if (config->mDomain & Config::IS_ENCODER) {
1340 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1341 } else {
1342 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1343 }
1344 }
Wonsik Kim6f23cfc2021-09-24 05:45:52 -07001345
1346 // set PCM encoding
1347 int32_t pcmEncoding = kAudioEncodingPcm16bit;
1348 msg->findInt32(KEY_PCM_ENCODING, &pcmEncoding);
1349 if (encoder) {
1350 config->mInputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1351 } else {
1352 config->mOutputFormat->setInt32("android._config-pcm-encoding", pcmEncoding);
1353 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001354 }
1355
Wonsik Kim58d83332021-02-07 22:19:56 -08001356 std::unique_ptr<C2Param> colorTransferRequestParam;
1357 for (std::unique_ptr<C2Param> &param : params) {
1358 if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1359 ALOGI("found color transfer request param");
1360 colorTransferRequestParam = std::move(param);
1361 }
1362 }
1363 int32_t colorTransferRequest = 0;
1364 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1365 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1366 colorTransferRequest = 0;
1367 }
1368
1369 if (colorTransferRequest != 0) {
1370 if (colorTransferRequestParam && *colorTransferRequestParam) {
1371 C2StreamColorAspectsInfo::output *info =
1372 static_cast<C2StreamColorAspectsInfo::output *>(
1373 colorTransferRequestParam.get());
1374 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1375 colorTransferRequest = 0;
1376 }
1377 } else {
1378 colorTransferRequest = 0;
1379 }
1380 config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1381 }
1382
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001383 if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1384 // Need to get stride/vstride
1385 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1386 if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1387 // TODO: retrieve these values without allocating a buffer.
1388 // Currently allocating a buffer is necessary to retrieve the layout.
1389 int64_t blockUsage =
1390 usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1391 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1392 width, height, pixelFormat, blockUsage, {comp->getName()});
1393 sp<GraphicBlockBuffer> buffer;
1394 if (block) {
1395 buffer = GraphicBlockBuffer::Allocate(
1396 config->mInputFormat,
1397 block,
1398 [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1399 } else {
1400 ALOGD("Failed to allocate a graphic block "
1401 "(width=%d height=%d pixelFormat=%u usage=%llx)",
1402 width, height, pixelFormat, (long long)blockUsage);
1403 // This means that byte buffer mode is not supported in this configuration
1404 // anyway. Skip setting stride/vstride to input format.
1405 }
1406 if (buffer) {
1407 sp<ABuffer> imageData = buffer->getImageData();
1408 MediaImage2 *img = nullptr;
1409 if (imageData && imageData->data()
1410 && imageData->size() >= sizeof(MediaImage2)) {
1411 img = (MediaImage2*)imageData->data();
1412 }
1413 if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1414 int32_t stride = img->mPlane[0].mRowInc;
1415 config->mInputFormat->setInt32(KEY_STRIDE, stride);
1416 if (img->mNumPlanes > 1 && stride > 0) {
1417 int64_t offsetDelta =
1418 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1419 if (offsetDelta % stride == 0) {
1420 int32_t vstride = int32_t(offsetDelta / stride);
1421 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1422 } else {
1423 ALOGD("Cannot report accurate slice height: "
1424 "offsetDelta = %lld stride = %d",
1425 (long long)offsetDelta, stride);
1426 }
1427 }
1428 }
1429 }
1430 }
1431 }
1432
Wonsik Kimec585c32021-10-01 01:11:00 -07001433 if (config->mTunneled) {
1434 config->mOutputFormat->setInt32("android._tunneled", 1);
1435 }
1436
Wonsik Kimd91f3fb2021-02-24 12:35:31 -08001437 ALOGD("setup formats input: %s",
1438 config->mInputFormat->debugString().c_str());
1439 ALOGD("setup formats output: %s",
Pawin Vongmasa36653902018-11-15 00:10:25 -08001440 config->mOutputFormat->debugString().c_str());
1441 return OK;
1442 };
1443 if (tryAndReportOnError(doConfig) != OK) {
1444 return;
1445 }
1446
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001447 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1448 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001449
Houxiang Dai183ca3d2021-02-04 14:20:11 +08001450 config->queryConfiguration(comp);
1451
Pawin Vongmasa36653902018-11-15 00:10:25 -08001452 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1453}
1454
1455void CCodec::initiateCreateInputSurface() {
1456 status_t err = [this] {
1457 Mutexed<State>::Locked state(mState);
1458 if (state->get() != ALLOCATED) {
1459 return UNKNOWN_ERROR;
1460 }
1461 // TODO: read it from intf() properly.
1462 if (state->comp->getName().find("encoder") == std::string::npos) {
1463 return INVALID_OPERATION;
1464 }
1465 return OK;
1466 }();
1467 if (err != OK) {
1468 mCallback->onInputSurfaceCreationFailed(err);
1469 return;
1470 }
1471
1472 (new AMessage(kWhatCreateInputSurface, this))->post();
1473}
1474
Lajos Molnar47118272019-01-31 16:28:04 -08001475sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1476 using namespace android::hardware::media::omx::V1_0;
1477 using namespace android::hardware::media::omx::V1_0::utils;
1478 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1479 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1480 android::sp<IOmx> omx = IOmx::getService();
1481 typedef android::hardware::graphics::bufferqueue::V1_0::
1482 IGraphicBufferProducer HGraphicBufferProducer;
1483 typedef android::hardware::media::omx::V1_0::
1484 IGraphicBufferSource HGraphicBufferSource;
1485 OmxStatus s;
1486 android::sp<HGraphicBufferProducer> gbp;
1487 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001488
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001489 using ::android::hardware::Return;
1490 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001491 [&s, &gbp, &gbs](
1492 OmxStatus status,
1493 const android::sp<HGraphicBufferProducer>& producer,
1494 const android::sp<HGraphicBufferSource>& source) {
1495 s = status;
1496 gbp = producer;
1497 gbs = source;
1498 });
1499 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001500 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001501 }
1502
1503 return nullptr;
1504}
1505
1506sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1507 sp<PersistentSurface> surface(CreateInputSurface());
1508
1509 if (surface == nullptr) {
1510 surface = CreateOmxInputSurface();
1511 }
1512
1513 return surface;
1514}
1515
Pawin Vongmasa36653902018-11-15 00:10:25 -08001516void CCodec::createInputSurface() {
1517 status_t err;
1518 sp<IGraphicBufferProducer> bufferProducer;
1519
Pawin Vongmasa36653902018-11-15 00:10:25 -08001520 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001521 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001522 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001523 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1524 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001525 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001526 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001527 }
1528
Lajos Molnar47118272019-01-31 16:28:04 -08001529 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001530 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1531 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1532 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001533
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001534 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001535 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1536 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001537 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001538 inputSurface));
1539 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001540 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001541 int32_t width = 0;
1542 (void)outputFormat->findInt32("width", &width);
1543 int32_t height = 0;
1544 (void)outputFormat->findInt32("height", &height);
1545 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001546 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001547 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001548 } else {
1549 ALOGE("Corrupted input surface");
1550 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1551 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001552 }
1553
1554 if (err != OK) {
1555 ALOGE("Failed to set up input surface: %d", err);
1556 mCallback->onInputSurfaceCreationFailed(err);
1557 return;
1558 }
1559
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001560 // Formats can change after setupInputSurface
1561 sp<AMessage> inputFormat;
1562 {
1563 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1564 const std::unique_ptr<Config> &config = *configLocked;
1565 inputFormat = config->mInputFormat;
1566 outputFormat = config->mOutputFormat;
1567 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001568 mCallback->onInputSurfaceCreated(
1569 inputFormat,
1570 outputFormat,
1571 new BufferProducerWrapper(bufferProducer));
1572}
1573
1574status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001575 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1576 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001577 config->mUsingSurface = true;
1578
1579 // we are now using surface - apply default color aspects to input format - as well as
1580 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001581 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001582 ALOGD("input format %s to %s",
1583 inputFormatChanged ? "changed" : "unchanged",
1584 config->mInputFormat->debugString().c_str());
1585
1586 // configure dataspace
1587 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1588 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1589 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1590 surface->setDataSpace(dataSpace);
1591
1592 status_t err = mChannel->setInputSurface(surface);
1593 if (err != OK) {
1594 // undo input format update
1595 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001596 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001597 return err;
1598 }
1599 config->mInputSurface = surface;
1600
1601 if (config->mISConfig) {
1602 surface->configure(*config->mISConfig);
1603 } else {
1604 ALOGD("ISConfig: no configuration");
1605 }
1606
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001607 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001608}
1609
1610void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1611 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1612 msg->setObject("surface", surface);
1613 msg->post();
1614}
1615
1616void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001617 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001618 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001619 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001620 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1621 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001622 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001623 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001624 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001625 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1626 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1627 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1628 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001629 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1630 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1631 if (err != OK) {
1632 ALOGE("Failed to set up input surface: %d", err);
1633 mCallback->onInputSurfaceDeclined(err);
1634 return;
1635 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001636 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001637 int32_t width = 0;
1638 (void)outputFormat->findInt32("width", &width);
1639 int32_t height = 0;
1640 (void)outputFormat->findInt32("height", &height);
1641 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001642 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001643 if (err != OK) {
1644 ALOGE("Failed to set up input surface: %d", err);
1645 mCallback->onInputSurfaceDeclined(err);
1646 return;
1647 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001648 } else {
1649 ALOGE("Failed to set input surface: Corrupted surface.");
1650 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1651 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001652 }
Wonsik Kim7b9e6db2021-05-10 13:31:40 -07001653 // Formats can change after setupInputSurface
1654 sp<AMessage> inputFormat;
1655 {
1656 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1657 const std::unique_ptr<Config> &config = *configLocked;
1658 inputFormat = config->mInputFormat;
1659 outputFormat = config->mOutputFormat;
1660 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001661 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1662}
1663
1664void CCodec::initiateStart() {
1665 auto setStarting = [this] {
1666 Mutexed<State>::Locked state(mState);
1667 if (state->get() != ALLOCATED) {
1668 return UNKNOWN_ERROR;
1669 }
1670 state->set(STARTING);
1671 return OK;
1672 };
1673 if (tryAndReportOnError(setStarting) != OK) {
1674 return;
1675 }
1676
1677 (new AMessage(kWhatStart, this))->post();
1678}
1679
1680void CCodec::start() {
1681 std::shared_ptr<Codec2Client::Component> comp;
1682 auto checkStarting = [this, &comp] {
1683 Mutexed<State>::Locked state(mState);
1684 if (state->get() != STARTING) {
1685 return UNKNOWN_ERROR;
1686 }
1687 comp = state->comp;
1688 return OK;
1689 };
1690 if (tryAndReportOnError(checkStarting) != OK) {
1691 return;
1692 }
1693
1694 c2_status_t err = comp->start();
1695 if (err != C2_OK) {
1696 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1697 ACTION_CODE_FATAL);
1698 return;
1699 }
1700 sp<AMessage> inputFormat;
1701 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001702 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001703 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001704 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001705 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1706 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001707 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001708 // start triggers format dup
1709 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001710 if (config->mInputSurface) {
1711 err2 = config->mInputSurface->start();
Wonsik Kim673dd192021-01-29 14:58:12 -08001712 config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001713 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001714 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001715 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001716 if (err2 != OK) {
1717 mCallback->onError(err2, ACTION_CODE_FATAL);
1718 return;
1719 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001720 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001721 if (err2 != OK) {
1722 mCallback->onError(err2, ACTION_CODE_FATAL);
1723 return;
1724 }
1725
1726 auto setRunning = [this] {
1727 Mutexed<State>::Locked state(mState);
1728 if (state->get() != STARTING) {
1729 return UNKNOWN_ERROR;
1730 }
1731 state->set(RUNNING);
1732 return OK;
1733 };
1734 if (tryAndReportOnError(setRunning) != OK) {
1735 return;
1736 }
1737 mCallback->onStartCompleted();
1738
1739 (void)mChannel->requestInitialInputBuffers();
1740}
1741
1742void CCodec::initiateShutdown(bool keepComponentAllocated) {
1743 if (keepComponentAllocated) {
1744 initiateStop();
1745 } else {
1746 initiateRelease();
1747 }
1748}
1749
1750void CCodec::initiateStop() {
1751 {
1752 Mutexed<State>::Locked state(mState);
1753 if (state->get() == ALLOCATED
1754 || state->get() == RELEASED
1755 || state->get() == STOPPING
1756 || state->get() == RELEASING) {
1757 // We're already stopped, released, or doing it right now.
1758 state.unlock();
1759 mCallback->onStopCompleted();
1760 state.lock();
1761 return;
1762 }
1763 state->set(STOPPING);
1764 }
1765
Wonsik Kim936a89c2020-05-08 16:07:50 -07001766 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001767 (new AMessage(kWhatStop, this))->post();
1768}
1769
1770void CCodec::stop() {
1771 std::shared_ptr<Codec2Client::Component> comp;
1772 {
1773 Mutexed<State>::Locked state(mState);
1774 if (state->get() == RELEASING) {
1775 state.unlock();
1776 // We're already stopped or release is in progress.
1777 mCallback->onStopCompleted();
1778 state.lock();
1779 return;
1780 } else if (state->get() != STOPPING) {
1781 state.unlock();
1782 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1783 state.lock();
1784 return;
1785 }
1786 comp = state->comp;
1787 }
1788 status_t err = comp->stop();
1789 if (err != C2_OK) {
1790 // TODO: convert err into status_t
1791 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1792 }
1793
1794 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001795 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1796 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001797 if (config->mInputSurface) {
1798 config->mInputSurface->disconnect();
1799 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001800 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001801 }
1802 }
1803 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001804 Mutexed<State>::Locked state(mState);
1805 if (state->get() == STOPPING) {
1806 state->set(ALLOCATED);
1807 }
1808 }
1809 mCallback->onStopCompleted();
1810}
1811
1812void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001813 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001814 {
1815 Mutexed<State>::Locked state(mState);
1816 if (state->get() == RELEASED || state->get() == RELEASING) {
1817 // We're already released or doing it right now.
1818 if (sendCallback) {
1819 state.unlock();
1820 mCallback->onReleaseCompleted();
1821 state.lock();
1822 }
1823 return;
1824 }
1825 if (state->get() == ALLOCATING) {
1826 state->set(RELEASING);
1827 // With the altered state allocate() would fail and clean up.
1828 if (sendCallback) {
1829 state.unlock();
1830 mCallback->onReleaseCompleted();
1831 state.lock();
1832 }
1833 return;
1834 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001835 if (state->get() == STARTING
1836 || state->get() == RUNNING
1837 || state->get() == STOPPING) {
1838 // Input surface may have been started, so clean up is needed.
1839 clearInputSurfaceIfNeeded = true;
1840 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001841 state->set(RELEASING);
1842 }
1843
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001844 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001845 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1846 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001847 if (config->mInputSurface) {
1848 config->mInputSurface->disconnect();
1849 config->mInputSurface = nullptr;
Wonsik Kim673dd192021-01-29 14:58:12 -08001850 config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001851 }
1852 }
1853
Wonsik Kim936a89c2020-05-08 16:07:50 -07001854 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001855 // thiz holds strong ref to this while the thread is running.
1856 sp<CCodec> thiz(this);
1857 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1858}
1859
1860void CCodec::release(bool sendCallback) {
1861 std::shared_ptr<Codec2Client::Component> comp;
1862 {
1863 Mutexed<State>::Locked state(mState);
1864 if (state->get() == RELEASED) {
1865 if (sendCallback) {
1866 state.unlock();
1867 mCallback->onReleaseCompleted();
1868 state.lock();
1869 }
1870 return;
1871 }
1872 comp = state->comp;
1873 }
1874 comp->release();
1875
1876 {
1877 Mutexed<State>::Locked state(mState);
1878 state->set(RELEASED);
1879 state->comp.reset();
1880 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001881 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001882 if (sendCallback) {
1883 mCallback->onReleaseCompleted();
1884 }
1885}
1886
1887status_t CCodec::setSurface(const sp<Surface> &surface) {
Wonsik Kim75e22f42021-04-14 23:34:51 -07001888 {
1889 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1890 const std::unique_ptr<Config> &config = *configLocked;
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08001891 sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
1892 status_t err = OK;
1893
Wonsik Kim75e22f42021-04-14 23:34:51 -07001894 if (config->mTunneled && config->mSidebandHandle != nullptr) {
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08001895 err = native_window_set_sideband_stream(
Wonsik Kim75e22f42021-04-14 23:34:51 -07001896 nativeWindow.get(),
1897 const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
1898 if (err != OK) {
1899 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
1900 nativeWindow.get(), config->mSidebandHandle->handle(), err);
1901 return err;
1902 }
Houxiang Dai7ab7ee62021-09-30 16:08:51 +08001903 } else {
1904 // Explicitly reset the sideband handle of the window for
1905 // non-tunneled video in case the window was previously used
1906 // for a tunneled video playback.
1907 err = native_window_set_sideband_stream(nativeWindow.get(), nullptr);
1908 if (err != OK) {
1909 ALOGE("native_window_set_sideband_stream(nullptr) failed! (err %d).", err);
1910 return err;
1911 }
ted.sun765db4d2020-06-23 14:03:41 +08001912 }
1913 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001914 return mChannel->setSurface(surface);
1915}
1916
1917void CCodec::signalFlush() {
1918 status_t err = [this] {
1919 Mutexed<State>::Locked state(mState);
1920 if (state->get() == FLUSHED) {
1921 return ALREADY_EXISTS;
1922 }
1923 if (state->get() != RUNNING) {
1924 return UNKNOWN_ERROR;
1925 }
1926 state->set(FLUSHING);
1927 return OK;
1928 }();
1929 switch (err) {
1930 case ALREADY_EXISTS:
1931 mCallback->onFlushCompleted();
1932 return;
1933 case OK:
1934 break;
1935 default:
1936 mCallback->onError(err, ACTION_CODE_FATAL);
1937 return;
1938 }
1939
1940 mChannel->stop();
1941 (new AMessage(kWhatFlush, this))->post();
1942}
1943
1944void CCodec::flush() {
1945 std::shared_ptr<Codec2Client::Component> comp;
1946 auto checkFlushing = [this, &comp] {
1947 Mutexed<State>::Locked state(mState);
1948 if (state->get() != FLUSHING) {
1949 return UNKNOWN_ERROR;
1950 }
1951 comp = state->comp;
1952 return OK;
1953 };
1954 if (tryAndReportOnError(checkFlushing) != OK) {
1955 return;
1956 }
1957
1958 std::list<std::unique_ptr<C2Work>> flushedWork;
1959 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1960 {
1961 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1962 flushedWork.splice(flushedWork.end(), *queue);
1963 }
1964 if (err != C2_OK) {
1965 // TODO: convert err into status_t
1966 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1967 }
1968
1969 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001970
1971 {
1972 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001973 if (state->get() == FLUSHING) {
1974 state->set(FLUSHED);
1975 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001976 }
1977 mCallback->onFlushCompleted();
1978}
1979
1980void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001981 std::shared_ptr<Codec2Client::Component> comp;
1982 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001983 Mutexed<State>::Locked state(mState);
1984 if (state->get() != FLUSHED) {
1985 return UNKNOWN_ERROR;
1986 }
1987 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001988 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001989 return OK;
1990 };
1991 if (tryAndReportOnError(setResuming) != OK) {
1992 return;
1993 }
1994
Wonsik Kime75a5da2020-02-14 17:29:03 -08001995 {
1996 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1997 const std::unique_ptr<Config> &config = *configLocked;
Harish Mahendrakar8c537502021-02-23 21:20:22 -08001998 sp<AMessage> outputFormat = config->mOutputFormat;
Wonsik Kime75a5da2020-02-14 17:29:03 -08001999 config->queryConfiguration(comp);
Harish Mahendrakar8c537502021-02-23 21:20:22 -08002000 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Wonsik Kime75a5da2020-02-14 17:29:03 -08002001 }
2002
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002003 (void)mChannel->start(nullptr, nullptr, [&]{
2004 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2005 const std::unique_ptr<Config> &config = *configLocked;
2006 return config->mBuffersBoundToCodec;
2007 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002008
2009 {
2010 Mutexed<State>::Locked state(mState);
2011 if (state->get() != RESUMING) {
2012 state.unlock();
2013 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2014 state.lock();
2015 return;
2016 }
2017 state->set(RUNNING);
2018 }
2019
2020 (void)mChannel->requestInitialInputBuffers();
2021}
2022
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002023void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002024 std::shared_ptr<Codec2Client::Component> comp;
2025 auto checkState = [this, &comp] {
2026 Mutexed<State>::Locked state(mState);
2027 if (state->get() == RELEASED) {
2028 return INVALID_OPERATION;
2029 }
2030 comp = state->comp;
2031 return OK;
2032 };
2033 if (tryAndReportOnError(checkState) != OK) {
2034 return;
2035 }
2036
Wonsik Kimaa484ac2019-02-13 16:54:02 -08002037 // NOTE: We used to ignore "bitrate" at setParameters; replicate
2038 // the behavior here.
2039 sp<AMessage> params = msg;
2040 int32_t bitrate;
2041 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2042 params = msg->dup();
2043 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2044 }
2045
Houxiang Dai5a97b472021-03-22 17:56:04 +08002046 int32_t syncId = 0;
2047 if (params->findInt32("audio-hw-sync", &syncId)
2048 || params->findInt32("hw-av-sync-id", &syncId)) {
2049 configureTunneledVideoPlayback(comp, nullptr, params);
2050 }
2051
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002052 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2053 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002054
2055 /**
2056 * Handle input surface parameters
2057 */
2058 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08002059 && (config->mDomain & Config::IS_ENCODER)
2060 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08002061 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002062
2063 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2064 config->mISConfig->mStopped = false;
2065 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2066 config->mISConfig->mStopped = true;
2067 }
2068
2069 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08002070 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002071 config->mISConfig->mSuspended = value;
2072 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08002073 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002074 }
2075
2076 (void)config->mInputSurface->configure(*config->mISConfig);
2077 if (config->mISConfig->mStopped) {
2078 config->mInputFormat->setInt64(
2079 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2080 }
2081 }
2082
2083 std::vector<std::unique_ptr<C2Param>> configUpdate;
2084 (void)config->getConfigUpdateFromSdkParams(
2085 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2086 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2087 // Parameter synchronization is not defined when using input surface. For now, route
2088 // these directly to the component.
2089 if (config->mInputSurface == nullptr
2090 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2091 || comp->getName().find("c2.android.") == 0)) {
2092 mChannel->setParameters(configUpdate);
2093 } else {
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002094 sp<AMessage> outputFormat = config->mOutputFormat;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002095 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
Wonsik Kim970bf0b2020-11-10 11:54:15 -08002096 RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002097 }
2098}
2099
2100void CCodec::signalEndOfInputStream() {
2101 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2102}
2103
2104void CCodec::signalRequestIDRFrame() {
2105 std::shared_ptr<Codec2Client::Component> comp;
2106 {
2107 Mutexed<State>::Locked state(mState);
2108 if (state->get() == RELEASED) {
2109 ALOGD("no IDR request sent since component is released");
2110 return;
2111 }
2112 comp = state->comp;
2113 }
2114 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002115 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2116 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002117 std::vector<std::unique_ptr<C2Param>> params;
2118 params.push_back(
2119 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2120 config->setParameters(comp, params, C2_MAY_BLOCK);
2121}
2122
Wonsik Kim874ad382021-03-12 09:59:36 -08002123status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2124 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2125 const std::unique_ptr<Config> &config = *configLocked;
2126 return config->querySupportedParameters(names);
2127}
2128
2129status_t CCodec::describeParameter(
2130 const std::string &name, CodecParameterDescriptor *desc) {
2131 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2132 const std::unique_ptr<Config> &config = *configLocked;
2133 return config->describe(name, desc);
2134}
2135
2136status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2137 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2138 if (!comp) {
2139 return INVALID_OPERATION;
2140 }
2141 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2142 const std::unique_ptr<Config> &config = *configLocked;
2143 return config->subscribeToVendorConfigUpdate(comp, names);
2144}
2145
2146status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2147 std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2148 if (!comp) {
2149 return INVALID_OPERATION;
2150 }
2151 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2152 const std::unique_ptr<Config> &config = *configLocked;
2153 return config->unsubscribeFromVendorConfigUpdate(comp, names);
2154}
2155
Wonsik Kimab34ed62019-01-31 15:28:46 -08002156void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002157 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002158 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2159 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002160 }
2161 (new AMessage(kWhatWorkDone, this))->post();
2162}
2163
Wonsik Kimab34ed62019-01-31 15:28:46 -08002164void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2165 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002166 if (arrayIndex == 0) {
2167 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002168 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2169 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002170 if (config->mInputSurface) {
2171 config->mInputSurface->onInputBufferDone(frameIndex);
2172 }
2173 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002174}
2175
2176void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2177 TimePoint now = std::chrono::steady_clock::now();
2178 CCodecWatchdog::getInstance()->watch(this);
2179 switch (msg->what()) {
2180 case kWhatAllocate: {
2181 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002182 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002183 sp<RefBase> obj;
2184 CHECK(msg->findObject("codecInfo", &obj));
2185 allocate((MediaCodecInfo *)obj.get());
2186 break;
2187 }
2188 case kWhatConfigure: {
2189 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002190 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002191 sp<AMessage> format;
2192 CHECK(msg->findMessage("format", &format));
2193 configure(format);
2194 break;
2195 }
2196 case kWhatStart: {
2197 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002198 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002199 start();
2200 break;
2201 }
2202 case kWhatStop: {
2203 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002204 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002205 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002206 break;
2207 }
2208 case kWhatFlush: {
2209 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002210 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002211 flush();
2212 break;
2213 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07002214 case kWhatRelease: {
2215 mChannel->release();
2216 mClient.reset();
2217 mClientListener.reset();
2218 break;
2219 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002220 case kWhatCreateInputSurface: {
2221 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002222 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002223 createInputSurface();
2224 break;
2225 }
2226 case kWhatSetInputSurface: {
2227 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07002228 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08002229 sp<RefBase> obj;
2230 CHECK(msg->findObject("surface", &obj));
2231 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2232 setInputSurface(surface);
2233 break;
2234 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002235 case kWhatWorkDone: {
2236 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002237 bool shouldPost = false;
2238 {
2239 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2240 if (queue->empty()) {
2241 break;
2242 }
2243 work.swap(queue->front());
2244 queue->pop_front();
2245 shouldPost = !queue->empty();
2246 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002247 if (shouldPost) {
2248 (new AMessage(kWhatWorkDone, this))->post();
2249 }
2250
Pawin Vongmasa36653902018-11-15 00:10:25 -08002251 // handle configuration changes in work done
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002252 std::shared_ptr<const C2StreamInitDataInfo::output> initData;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002253 sp<AMessage> outputFormat = nullptr;
2254 {
2255 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2256 const std::unique_ptr<Config> &config = *configLocked;
2257 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2258 config->watch<C2StreamInitDataInfo::output>();
2259 if (!work->worklets.empty()
2260 && (work->worklets.front()->output.flags
2261 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002262
Wonsik Kim75e22f42021-04-14 23:34:51 -07002263 // copy buffer info to config
2264 std::vector<std::unique_ptr<C2Param>> updates;
2265 for (const std::unique_ptr<C2Param> &param
2266 : work->worklets.front()->output.configUpdate) {
2267 updates.push_back(C2Param::Copy(*param));
2268 }
2269 unsigned stream = 0;
2270 std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2271 work->worklets.front()->output.buffers;
2272 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2273 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2274 // move all info into output-stream #0 domain
2275 updates.emplace_back(
2276 C2Param::CopyAsStream(*info, true /* output */, stream));
2277 }
2278
2279 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2280 // for now only do the first block
2281 if (!blocks.empty()) {
2282 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2283 // block.crop().left, block.crop().top,
2284 // block.crop().width, block.crop().height,
2285 // block.width(), block.height());
2286 const C2ConstGraphicBlock &block = blocks[0];
2287 updates.emplace_back(new C2StreamCropRectInfo::output(
2288 stream, block.crop()));
2289 updates.emplace_back(new C2StreamPictureSizeInfo::output(
2290 stream, block.crop().width, block.crop().height));
2291 }
2292 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002293 }
George Burgess IVc813a592020-02-22 22:54:44 -08002294
Wonsik Kim75e22f42021-04-14 23:34:51 -07002295 sp<AMessage> oldFormat = config->mOutputFormat;
2296 config->updateConfiguration(updates, config->mOutputDomain);
2297 RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002298
Wonsik Kim75e22f42021-04-14 23:34:51 -07002299 // copy standard infos to graphic buffers if not already present (otherwise, we
2300 // may overwrite the actual intermediate value with a final value)
2301 stream = 0;
2302 const static C2Param::Index stdGfxInfos[] = {
2303 C2StreamRotationInfo::output::PARAM_TYPE,
2304 C2StreamColorAspectsInfo::output::PARAM_TYPE,
2305 C2StreamDataSpaceInfo::output::PARAM_TYPE,
2306 C2StreamHdrStaticInfo::output::PARAM_TYPE,
2307 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
2308 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2309 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2310 };
2311 for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2312 if (buf->data().graphicBlocks().size()) {
2313 for (C2Param::Index ix : stdGfxInfos) {
2314 if (!buf->hasInfo(ix)) {
2315 const C2Param *param =
2316 config->getConfigParameterValue(ix.withStream(stream));
2317 if (param) {
2318 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2319 buf->setInfo(std::static_pointer_cast<C2Info>(info));
2320 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002321 }
2322 }
2323 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002324 ++stream;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002325 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002326 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002327 if (config->mInputSurface) {
Brijesh Patelab463672020-11-25 15:38:28 +05302328 if (work->worklets.empty()
2329 || !work->worklets.back()
2330 || (work->worklets.back()->output.flags
2331 & C2FrameData::FLAG_INCOMPLETE) == 0) {
2332 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2333 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002334 }
2335 if (initDataWatcher.hasChanged()) {
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002336 initData = initDataWatcher.update();
2337 AmendOutputFormatWithCodecSpecificData(
2338 initData->m.value, initData->flexCount(), config->mCodingMediaType,
2339 config->mOutputFormat);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002340 }
2341 outputFormat = config->mOutputFormat;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07002342 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002343 mChannel->onWorkDone(
Wonsik Kim1f5063d2021-05-03 15:41:17 -07002344 std::move(work), outputFormat, initData ? initData.get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002345 break;
2346 }
2347 case kWhatWatch: {
2348 // watch message already posted; no-op.
2349 break;
2350 }
2351 default: {
2352 ALOGE("unrecognized message");
2353 break;
2354 }
2355 }
2356 setDeadline(TimePoint::max(), 0ms, "none");
2357}
2358
2359void CCodec::setDeadline(
2360 const TimePoint &now,
2361 const std::chrono::milliseconds &timeout,
2362 const char *name) {
2363 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2364 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2365 deadline->set(now + (timeout * mult), name);
2366}
2367
ted.sun765db4d2020-06-23 14:03:41 +08002368status_t CCodec::configureTunneledVideoPlayback(
2369 std::shared_ptr<Codec2Client::Component> comp,
2370 sp<NativeHandle> *sidebandHandle,
2371 const sp<AMessage> &msg) {
2372 std::vector<std::unique_ptr<C2SettingResult>> failures;
2373
2374 std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2375 C2PortTunneledModeTuning::output::AllocUnique(
2376 1,
2377 C2PortTunneledModeTuning::Struct::SIDEBAND,
2378 C2PortTunneledModeTuning::Struct::REALTIME,
2379 0);
2380 // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2381 if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2382 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2383 } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2384 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2385 } else {
2386 tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2387 tunneledPlayback->setFlexCount(0);
2388 }
2389 c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2390 if (c2err != C2_OK) {
2391 return UNKNOWN_ERROR;
2392 }
2393
Houxiang Dai5a97b472021-03-22 17:56:04 +08002394 if (sidebandHandle == nullptr) {
2395 return OK;
2396 }
2397
ted.sun765db4d2020-06-23 14:03:41 +08002398 std::vector<std::unique_ptr<C2Param>> params;
2399 c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2400 if (c2err == C2_OK && params.size() == 1u) {
2401 C2PortTunnelHandleTuning::output *videoTunnelSideband =
2402 C2PortTunnelHandleTuning::output::From(params[0].get());
2403 // Currently, Codec2 only supports non-fd case for sideband native_handle.
2404 native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2405 *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2406 if (handle != nullptr && videoTunnelSideband->flexCount()) {
2407 memcpy(handle->data, videoTunnelSideband->m.values,
2408 sizeof(int32_t) * videoTunnelSideband->flexCount());
2409 return OK;
2410 } else {
2411 return NO_MEMORY;
2412 }
2413 }
2414 return UNKNOWN_ERROR;
2415}
2416
Pawin Vongmasa36653902018-11-15 00:10:25 -08002417void CCodec::initiateReleaseIfStuck() {
2418 std::string name;
2419 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08002420 {
2421 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002422 if (deadline->get() < std::chrono::steady_clock::now()) {
2423 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002424 }
2425 if (deadline->get() != TimePoint::max()) {
2426 pendingDeadline = true;
2427 }
2428 }
Wonsik Kim75e22f42021-04-14 23:34:51 -07002429 bool tunneled = false;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002430 bool isMediaTypeKnown = false;
Wonsik Kim75e22f42021-04-14 23:34:51 -07002431 {
Wonsik Kimabca11e2021-04-30 13:11:41 -07002432 static const std::set<std::string> kKnownMediaTypes{
2433 MIMETYPE_VIDEO_VP8,
2434 MIMETYPE_VIDEO_VP9,
2435 MIMETYPE_VIDEO_AV1,
2436 MIMETYPE_VIDEO_AVC,
2437 MIMETYPE_VIDEO_HEVC,
2438 MIMETYPE_VIDEO_MPEG4,
2439 MIMETYPE_VIDEO_H263,
2440 MIMETYPE_VIDEO_MPEG2,
2441 MIMETYPE_VIDEO_RAW,
2442 MIMETYPE_VIDEO_DOLBY_VISION,
2443
2444 MIMETYPE_AUDIO_AMR_NB,
2445 MIMETYPE_AUDIO_AMR_WB,
2446 MIMETYPE_AUDIO_MPEG,
2447 MIMETYPE_AUDIO_AAC,
2448 MIMETYPE_AUDIO_QCELP,
2449 MIMETYPE_AUDIO_VORBIS,
2450 MIMETYPE_AUDIO_OPUS,
2451 MIMETYPE_AUDIO_G711_ALAW,
2452 MIMETYPE_AUDIO_G711_MLAW,
2453 MIMETYPE_AUDIO_RAW,
2454 MIMETYPE_AUDIO_FLAC,
2455 MIMETYPE_AUDIO_MSGSM,
2456 MIMETYPE_AUDIO_AC3,
2457 MIMETYPE_AUDIO_EAC3,
2458
2459 MIMETYPE_IMAGE_ANDROID_HEIC,
2460 };
Wonsik Kim75e22f42021-04-14 23:34:51 -07002461 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2462 const std::unique_ptr<Config> &config = *configLocked;
2463 tunneled = config->mTunneled;
Wonsik Kimabca11e2021-04-30 13:11:41 -07002464 isMediaTypeKnown = (kKnownMediaTypes.count(config->mCodingMediaType) != 0);
Wonsik Kim75e22f42021-04-14 23:34:51 -07002465 }
Wonsik Kimabca11e2021-04-30 13:11:41 -07002466 if (!tunneled && isMediaTypeKnown && name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002467 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2468 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2469 if (elapsed >= kWorkDurationThreshold) {
2470 name = "queue";
2471 }
2472 if (elapsed > 0s) {
2473 pendingDeadline = true;
2474 }
2475 }
2476 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002477 // We're not stuck.
2478 if (pendingDeadline) {
2479 // If we are not stuck yet but still has deadline coming up,
2480 // post watch message to check back later.
2481 (new AMessage(kWhatWatch, this))->post();
2482 }
2483 return;
2484 }
2485
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002486 C2String compName;
2487 {
2488 Mutexed<State>::Locked state(mState);
Wonsik Kim12380072021-05-11 09:59:20 -07002489 if (!state->comp) {
2490 ALOGD("previous call to %s exceeded timeout "
2491 "and the component is already released", name.c_str());
2492 return;
2493 }
Chih-Yu Huang82e5ab32021-02-17 16:27:08 +09002494 compName = state->comp->getName();
2495 }
2496 ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2497
Pawin Vongmasa36653902018-11-15 00:10:25 -08002498 initiateRelease(false);
2499 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2500}
2501
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002502// static
2503PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002504 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002505 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002506 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002507 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2508 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002509 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002510 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2511 sp<IGraphicBufferProducer> gbp;
2512 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2513 status_t err = gbs->initCheck();
2514 if (err != OK) {
2515 ALOGE("Failed to create persistent input surface: error %d", err);
2516 return nullptr;
2517 }
2518 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002519 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002520 } else {
2521 return nullptr;
2522 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002523 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002524 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002525 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002526 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002527 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002528}
2529
Wonsik Kimffb889a2020-05-28 11:32:25 -07002530class IntfCache {
2531public:
2532 IntfCache() = default;
2533
2534 status_t init(const std::string &name) {
2535 std::shared_ptr<Codec2Client::Interface> intf{
2536 Codec2Client::CreateInterfaceByName(name.c_str())};
2537 if (!intf) {
2538 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2539 mInitStatus = NO_INIT;
2540 return NO_INIT;
2541 }
2542 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2543 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2544 C2ParamField{&sUsage, &sUsage.value}));
2545 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2546 if (err != C2_OK) {
2547 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2548 name.c_str(), err);
2549 mFields[0].status = err;
2550 }
2551 std::vector<std::unique_ptr<C2Param>> params;
2552 err = intf->query(
2553 {&mApiFeatures},
2554 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2555 C2_MAY_BLOCK,
2556 &params);
2557 if (err != C2_OK && err != C2_BAD_INDEX) {
2558 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2559 name.c_str(), err);
2560 }
2561 while (!params.empty()) {
2562 C2Param *param = params.back().release();
2563 params.pop_back();
2564 if (!param) {
2565 continue;
2566 }
2567 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2568 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002569 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002570 }
2571 }
2572 mInitStatus = OK;
2573 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002574 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002575
2576 status_t initCheck() const { return mInitStatus; }
2577
2578 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2579 CHECK_EQ(1u, mFields.size());
2580 return mFields[0];
2581 }
2582
2583 const C2ApiFeaturesSetting &getApiFeatures() const {
2584 return mApiFeatures;
2585 }
2586
2587 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2588 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2589 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2590 C2PortAllocatorsTuning::input::AllocUnique(0);
2591 param->invalidate();
2592 return param;
2593 }();
2594 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2595 }
2596
2597private:
2598 status_t mInitStatus{NO_INIT};
2599
2600 std::vector<C2FieldSupportedValuesQuery> mFields;
2601 C2ApiFeaturesSetting mApiFeatures;
2602 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2603};
2604
2605static const IntfCache &GetIntfCache(const std::string &name) {
2606 static IntfCache sNullIntfCache;
2607 static std::mutex sMutex;
2608 static std::map<std::string, IntfCache> sCache;
2609 std::unique_lock<std::mutex> lock{sMutex};
2610 auto it = sCache.find(name);
2611 if (it == sCache.end()) {
2612 lock.unlock();
2613 IntfCache intfCache;
2614 status_t err = intfCache.init(name);
2615 if (err != OK) {
2616 return sNullIntfCache;
2617 }
2618 lock.lock();
2619 it = sCache.insert({name, std::move(intfCache)}).first;
2620 }
2621 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002622}
2623
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002624static status_t GetCommonAllocatorIds(
2625 const std::vector<std::string> &names,
2626 C2Allocator::type_t type,
2627 std::set<C2Allocator::id_t> *ids) {
2628 int poolMask = GetCodec2PoolMask();
2629 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2630 C2Allocator::id_t defaultAllocatorId =
2631 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2632
2633 ids->clear();
2634 if (names.empty()) {
2635 return OK;
2636 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002637 bool firstIteration = true;
2638 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002639 const IntfCache &intfCache = GetIntfCache(name);
2640 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002641 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002642 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002643 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002644 if (firstIteration) {
2645 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002646 if (allocators && allocators.flexCount() > 0) {
2647 ids->insert(allocators.m.values,
2648 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002649 }
2650 if (ids->empty()) {
2651 // The component does not advertise allocators. Use default.
2652 ids->insert(defaultAllocatorId);
2653 }
2654 continue;
2655 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002656 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002657 if (allocators && allocators.flexCount() > 0) {
2658 filtered = true;
2659 for (auto it = ids->begin(); it != ids->end(); ) {
2660 bool found = false;
2661 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2662 if (allocators.m.values[j] == *it) {
2663 found = true;
2664 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002665 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002666 }
2667 if (found) {
2668 ++it;
2669 } else {
2670 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002671 }
2672 }
2673 }
2674 if (!filtered) {
2675 // The component does not advertise supported allocators. Use default.
2676 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2677 if (ids->size() != (containsDefault ? 1 : 0)) {
2678 ids->clear();
2679 if (containsDefault) {
2680 ids->insert(defaultAllocatorId);
2681 }
2682 }
2683 }
2684 }
2685 // Finally, filter with pool masks
2686 for (auto it = ids->begin(); it != ids->end(); ) {
2687 if ((poolMask >> *it) & 1) {
2688 ++it;
2689 } else {
2690 it = ids->erase(it);
2691 }
2692 }
2693 return OK;
2694}
2695
2696static status_t CalculateMinMaxUsage(
2697 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2698 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2699 *minUsage = 0;
2700 *maxUsage = ~0ull;
2701 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002702 const IntfCache &intfCache = GetIntfCache(name);
2703 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002704 continue;
2705 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002706 const C2FieldSupportedValuesQuery &usageSupportedValues =
2707 intfCache.getUsageSupportedValues();
2708 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002709 continue;
2710 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002711 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002712 if (supported.type != C2FieldSupportedValues::FLAGS) {
2713 continue;
2714 }
2715 if (supported.values.empty()) {
2716 *maxUsage = 0;
2717 continue;
2718 }
Houxiang Daibfb8a722021-04-13 17:34:40 +08002719 if (supported.values.size() > 1) {
2720 *minUsage |= supported.values[1].u64;
2721 } else {
2722 *minUsage |= supported.values[0].u64;
2723 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002724 int64_t currentMaxUsage = 0;
2725 for (const C2Value::Primitive &flags : supported.values) {
2726 currentMaxUsage |= flags.u64;
2727 }
2728 *maxUsage &= currentMaxUsage;
2729 }
2730 return OK;
2731}
2732
2733// static
2734status_t CCodec::CanFetchLinearBlock(
2735 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002736 for (const std::string &name : names) {
2737 const IntfCache &intfCache = GetIntfCache(name);
2738 if (intfCache.initCheck() != OK) {
2739 continue;
2740 }
2741 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2742 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2743 *isCompatible = false;
2744 return OK;
2745 }
2746 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002747 std::set<C2Allocator::id_t> allocators;
2748 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2749 if (allocators.empty()) {
2750 *isCompatible = false;
2751 return OK;
2752 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002753
2754 uint64_t minUsage = 0;
2755 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002756 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002757 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002758 *isCompatible = ((maxUsage & minUsage) == minUsage);
2759 return OK;
2760}
2761
2762static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2763 static std::mutex sMutex{};
2764 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2765 std::unique_lock<std::mutex> lock{sMutex};
2766 std::shared_ptr<C2BlockPool> pool;
2767 auto it = sPools.find(allocId);
2768 if (it == sPools.end()) {
2769 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2770 if (err == OK) {
2771 sPools.emplace(allocId, pool);
2772 } else {
2773 pool.reset();
2774 }
2775 } else {
2776 pool = it->second;
2777 }
2778 return pool;
2779}
2780
2781// static
2782std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2783 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002784 std::set<C2Allocator::id_t> allocators;
2785 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2786 if (allocators.empty()) {
2787 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2788 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002789
2790 uint64_t minUsage = 0;
2791 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002792 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002793 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002794 if ((maxUsage & minUsage) != minUsage) {
2795 allocators.clear();
2796 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2797 }
2798 std::shared_ptr<C2LinearBlock> block;
2799 for (C2Allocator::id_t allocId : allocators) {
2800 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2801 if (!pool) {
2802 continue;
2803 }
2804 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2805 if (err != C2_OK || !block) {
2806 block.reset();
2807 continue;
2808 }
2809 break;
2810 }
2811 return block;
2812}
2813
2814// static
2815status_t CCodec::CanFetchGraphicBlock(
2816 const std::vector<std::string> &names, bool *isCompatible) {
2817 uint64_t minUsage = 0;
2818 uint64_t maxUsage = ~0ull;
2819 std::set<C2Allocator::id_t> allocators;
2820 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2821 if (allocators.empty()) {
2822 *isCompatible = false;
2823 return OK;
2824 }
2825 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2826 *isCompatible = ((maxUsage & minUsage) == minUsage);
2827 return OK;
2828}
2829
2830// static
2831std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2832 int32_t width,
2833 int32_t height,
2834 int32_t format,
2835 uint64_t usage,
2836 const std::vector<std::string> &names) {
2837 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2838 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2839 ALOGD("Unrecognized pixel format: %d", format);
2840 return nullptr;
2841 }
2842 uint64_t minUsage = 0;
2843 uint64_t maxUsage = ~0ull;
2844 std::set<C2Allocator::id_t> allocators;
2845 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2846 if (allocators.empty()) {
2847 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2848 }
2849 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2850 minUsage |= usage;
2851 if ((maxUsage & minUsage) != minUsage) {
2852 allocators.clear();
2853 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2854 }
2855 std::shared_ptr<C2GraphicBlock> block;
2856 for (C2Allocator::id_t allocId : allocators) {
2857 std::shared_ptr<C2BlockPool> pool;
2858 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2859 if (err != C2_OK || !pool) {
2860 continue;
2861 }
2862 err = pool->fetchGraphicBlock(
2863 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2864 if (err != C2_OK || !block) {
2865 block.reset();
2866 continue;
2867 }
2868 break;
2869 }
2870 return block;
2871}
2872
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002873} // namespace android